//Для каждой точки составляем звезду из индексов точек private static List<List<int>> GetAllStars(List<Triangle> triangles, List<Point> orderedPoints) { List<List<int>> starsForPoints = new List<List<int>>(); for (int i = 0; i < orderedPoints.Count; i++) { List<int> curStar = new List<int>(); Point currentPoint = orderedPoints.ElementAt(i); foreach (Triangle tr in triangles) { if (tr.I == currentPoint) { if (!curStar.Contains(tr.J.Index)) curStar.Add(tr.J.Index); if (!curStar.Contains(tr.K.Index)) curStar.Add(tr.K.Index); continue; } if (tr.J == currentPoint) { if (!curStar.Contains(tr.I.Index)) curStar.Add(tr.I.Index); if (!curStar.Contains(tr.K.Index)) curStar.Add(tr.K.Index); continue; } if (tr.K == currentPoint) { if (!curStar.Contains(tr.J.Index)) curStar.Add(tr.J.Index); if (!curStar.Contains(tr.I.Index)) curStar.Add(tr.I.Index); continue; } } starsForPoints.Add(curStar); } return starsForPoints; }
internal void Initialize(List<VobSubMergedPack> mergedVobSubPacks, List<Color> palette, List<string> languages, string selectedLanguage) { _mergedVobSubPacks = mergedVobSubPacks; _palette = palette; List<int> uniqueLanguageStreamIds = new List<int>(); foreach (var pack in mergedVobSubPacks) { if (!uniqueLanguageStreamIds.Contains(pack.StreamId)) uniqueLanguageStreamIds.Add(pack.StreamId); } comboBoxLanguages.Items.Clear(); foreach (string languageName in languages) { if (uniqueLanguageStreamIds.Contains(GetLanguageIdFromString(languageName))) // only list languages actually found in vob { comboBoxLanguages.Items.Add(languageName); if (languageName == selectedLanguage) comboBoxLanguages.SelectedIndex = comboBoxLanguages.Items.Count - 1; uniqueLanguageStreamIds.Remove(GetLanguageIdFromString(languageName)); } } foreach (var existingLanguageId in uniqueLanguageStreamIds) comboBoxLanguages.Items.Add(string.Format(Configuration.Settings.Language.DvdSubRipChooseLanguage.UnknownLanguage + " (0x{0:x})", existingLanguageId)); // subtitle track not supplied from IFO if (comboBoxLanguages.Items.Count > 0 && comboBoxLanguages.SelectedIndex < 0) comboBoxLanguages.SelectedIndex = 0; _languages = languages; }
public List<int> FabonacciSequence(int number) { List<int> lstNumbers = new List<int>(); int x = 0; int y = 1; for (int i = 0; i < number; i++) { int temp = x; x = y; y = temp + y; if (x > number) { if (!lstNumbers.Contains(number)) { lstNumbers.Add(number); } } lstNumbers.Add(x); } if (!lstNumbers.Contains(number)) { lstNumbers.Add(number); } return lstNumbers; }
public static void TestAndAddRecursive(Type type, String declaringTypeNamespace, List<Type> valueTypes, List<String> namespaces) { if (type.IsGenericType) { if (type.GetGenericArguments() != null) { foreach (var genericArg in type.GetGenericArguments()) { TestAndAddRecursive(genericArg, declaringTypeNamespace, valueTypes, namespaces); } } return; } if (IsValueTypeNoEnumOrPrimitve(type) && !valueTypes.Contains(type) && type.Namespace != "System" && type.Namespace != declaringTypeNamespace) { valueTypes.Add(type); } if (!IsValueTypeNoEnumOrPrimitve(type) && type.Namespace != declaringTypeNamespace) { if (!ExcludedExternalNamespaces.Contains(type.Namespace) && !namespaces.Contains(type.Namespace)) { namespaces.Add(type.Namespace); } else if (type.Namespace == "System" && type.Name == "Uri" && !namespaces.Contains("Windows.Foundation")) // Uri is special.. { namespaces.Add("Windows.Foundation"); } } }
public static Form DecideForm() { var args = new List<string>(Environment.GetCommandLineArgs()); // TODO. if (args.Contains(@"-i") || args.Count <= 1 && !Installer.IsInstalled) { return new InstallForm(); } else if (args.Contains(@"-u") || args.Count <= 1 && Installer.IsInstalled) { return new UninstallForm(); } else if (args.Contains(@"-b") && args.Count == 3) { var r = new BackupForm(); r.Initialize(args[2]); return r; } else if (args.Contains(@"-r") && args.Count == 3) { var r = new RestoreForm(); r.Initialize(args[2]); return r; } else { throw new Exception("Unknown/invalid command line arguments."); } }
public void ReplaceInFiles(string rootDir, string include,string exclude,IDictionary<string,string>replacements,StringBuilder logger = null) { if (string.IsNullOrEmpty(rootDir)) { throw new ArgumentNullException("rootDir"); } if (!Directory.Exists(rootDir)) { throw new ArgumentException(string.Format("rootDir doesn't exist at [{0}]", rootDir)); } string rootDirFullPath = Path.GetFullPath(rootDir); // search for all include files List<string> pathsToInclude = new List<string>(); List<string> pathsToExclude = new List<string>(); if (!string.IsNullOrEmpty(include)) { string[] includeParts = include.Split(';'); foreach (string includeStr in includeParts) { var results = RobustReplacer.Search(rootDirFullPath, includeStr); foreach (var result in results) { if (!pathsToInclude.Contains(result)) { pathsToInclude.Add(result); } } } } if (!string.IsNullOrEmpty(exclude)) { string[] excludeParts = exclude.Split(';'); foreach (string excludeStr in excludeParts) { var results = RobustReplacer.Search(rootDirFullPath, excludeStr); foreach (var result in results) { if (!pathsToExclude.Contains(result)) { pathsToExclude.Add(result); } } } } int numFilesExcluded = pathsToInclude.RemoveAll(p => pathsToExclude.Contains(p)); LogMessageLine(logger,"Number of files excluded based on pattern: [{0}]", numFilesExcluded); foreach (string file in pathsToInclude) { string fileFullPath = Path.GetFullPath(file); bool modified = false; using (var fileStream = File.Open(fileFullPath, FileMode.Open, FileAccess.ReadWrite)) { using (var replacer = new TokenReplacer(fileStream)) { foreach (string key in replacements.Keys) { modified |= replacer.Replace(key, replacements[key]); } } fileStream.Flush(); } if (modified) { LogMessageLine(logger,"Updating text after replacements in file [{0}]", fileFullPath); } else { LogMessageLine(logger,"Not writing out file because no replacments detected [{0}]", fileFullPath); } } }
public static void DeleteCustomersDAL(List<string> customers) { //Take custoners in KHACHHANGs which have MAKH var query = from item in db.KHACHHANGs where customers.Contains(item.MAKH) select item; //Detele MAKH in CONGNO var queryCN = from item in db.CONGNOs where customers.Contains(item.MAKH) select item; //Delete MAKH in TON var queryTON = from item in db.TONs where customers.Contains(item.MAKH) select item; //Delete MAKH in HOADON var queryHD = from item in db.HOADONs where customers.Contains(item.MAKH) select item; //Delete HOADON in CTHD var queryCTHD = from item in db.CTHDs join hd in queryHD on item.MAHD equals hd.MAHD select item; //Detele db.CTHDs.DeleteAllOnSubmit(queryCTHD); db.HOADONs.DeleteAllOnSubmit(queryHD); db.TONs.DeleteAllOnSubmit(queryTON); db.CONGNOs.DeleteAllOnSubmit(queryCN); db.KHACHHANGs.DeleteAllOnSubmit(query); //Confirm database db.SubmitChanges(); }
public override List<WiiType> getRequiredDevices() { List<WiiType> wt = new List<WiiType>(); WiiType wti; if (primaryInput != null) { if (!wt.Contains(wti = primaryInput.getInputEnum())) wt.Add(wti); } if (additionalInput != null && additionalInput.Count > 0) { foreach (InputDevice id in additionalInput) if (!wt.Contains(wti = id.getInputEnum())) wt.Add(wti); } List<WiiType> wt2; if ((wt2 = endCondition.getRequiredDevices()).Count > 0) { foreach (WiiType wte in wt2) { if (!wt.Contains(wte)) wt.Add(wte); } } return wt; }
public override void KeyDown(List<Keys> keys) { //StepingAngle: if (keys.Contains(Keys.A)) StepAngle(Directions.Left, 3); if (keys.Contains(Keys.D)) StepAngle(Directions.Right, 3); if (keys.Contains(Keys.W)) StepAngle(Directions.Up, 3); if (keys.Contains(Keys.S)) StepAngle(Directions.Down, 3); ////MovingAngle: //if (keys.Contains(Keys.A)) // MoveAngle(Directions.Left, 3); //if (keys.Contains(Keys.D)) // MoveAngle(Directions.Right, 3); //if (keys.Contains(Keys.W)) // MoveAngle(Directions.Up, 3); //if (keys.Contains(Keys.S)) // MoveAngle(Directions.Down, 3); ////Steping towards: //Vector2 somePoint = new Vector2(300, 300); //if (keys.Contains(Keys.Space)) // StepTowards(somePoint, 10); ////Moving towards: //Vector2 someOtherPoint = new Vector2(400, 300); //if (keys.Contains(Keys.Space)) // MoveTowards(someOtherPoint, 3); }
public bool AreAdjacent(IRectangle rectangle, IRectangle anotherRectangle) { //If any lines are inside another rectangle it can't be adjacent if(_decomposer.GetLines(anotherRectangle).Any(line => rectangle.Contains(line.StartingPoint) && rectangle.Contains(line.EndingPoint))) return false; if (_decomposer.GetLines(rectangle).Any(line => anotherRectangle.Contains(line.StartingPoint) && anotherRectangle.Contains(line.EndingPoint))) return false; //If rectangles intersect they are not adjacent if (_intersectionService.Solve(rectangle, anotherRectangle).HasIntersection) return false; //For two rectangles to be adjacent the must share exactly 1 one or have 1 line exist in another var matchingLines = new List<ILine>(); foreach (var line in _decomposer.GetLines(rectangle)) { foreach (var anotherLine in _decomposer.GetLines(anotherRectangle)) { if (line.Contains(anotherLine) || anotherLine.Contains(line)) { if(line.Contains(anotherLine) && !matchingLines.Contains(anotherLine)) matchingLines.Add(anotherLine); if(anotherLine.Contains(line) && !matchingLines.Contains(line)) matchingLines.Add(line); } } } return matchingLines.Count == 1; }
public List<Guid> GetUCError() { List<Guid> ret = new List<Guid>(); using (UserRepository repo = new UserRepository()) { foreach(var v in repo.GetAllUserAcadmic()) { if(!string.IsNullOrEmpty(v.Association) && string.IsNullOrEmpty(v.AssociationPost)) { if (!ret.Contains(v.AccountEmail_uuid)) ret.Add(v.AccountEmail_uuid); } if (!string.IsNullOrEmpty(v.Magazine) && string.IsNullOrEmpty(v.MagazinePost)) { if (!ret.Contains(v.AccountEmail_uuid)) ret.Add(v.AccountEmail_uuid); } if (!string.IsNullOrEmpty(v.Fund) && string.IsNullOrEmpty(v.FundPost)) { if (!ret.Contains(v.AccountEmail_uuid)) ret.Add(v.AccountEmail_uuid); } } } return ret; }
/// <summary> /// Tries to implement the Get [] semantics, but it cuts corners like crazy. /// Specifically, it relies on the knowledge that the only Gets used are /// keyed on PrincipalID, Email, and FirstName+LastName. /// </summary> /// <param name="fields"></param> /// <param name="values"></param> /// <returns></returns> public UserAccountData[] Get(string[] fields, string[] values) { List<string> fieldsLst = new List<string>(fields); if (fieldsLst.Contains("PrincipalID")) { int i = fieldsLst.IndexOf("PrincipalID"); UUID id = UUID.Zero; if (UUID.TryParse(values[i], out id)) if (m_DataByUUID.ContainsKey(id)) return new UserAccountData[] { m_DataByUUID[id] }; } if (fieldsLst.Contains("FirstName") && fieldsLst.Contains("LastName")) { int findex = fieldsLst.IndexOf("FirstName"); int lindex = fieldsLst.IndexOf("LastName"); if (m_DataByName.ContainsKey(values[findex] + " " + values[lindex])) return new UserAccountData[] { m_DataByName[values[findex] + " " + values[lindex]] }; } if (fieldsLst.Contains("Email")) { int i = fieldsLst.IndexOf("Email"); if (m_DataByEmail.ContainsKey(values[i])) return new UserAccountData[] { m_DataByEmail[values[i]] }; } // Fail return new UserAccountData[0]; }
public List<Vector2> Generate() { List<Vector2> open = new List<Vector2>(); List<Vector2> closed = new List<Vector2>(); open.Add(start); gScore[(int) start.X, (int) start.Y] = 0; hScore[(int) start.X, (int) start.Y] = calculateHeuristic(start); fScore[(int) start.X, (int) start.Y] = hScore[(int) start.X, (int) start.Y]; while(open.Count > 0) { Vector2 point = getLowestPointIn(open); if(point == end) return reconstructPath(cameFrom[(int) point.X, (int) point.Y]); open.Remove(point); closed.Add(point); List<Vector2> neighbours = getNeighbourPoints(point); foreach(Vector2 p in neighbours) { if(closed.Contains(p)) continue; int gPossible = gScore[(int) point.X, (int) point.Y] + distanceBetween(p, point); if(!open.Contains(p) || (open.Contains(p) && gPossible < gScore[(int) p.X, (int) p.Y])) { if(!open.Contains(p)) open.Add(p); cameFrom[(int) p.X, (int) p.Y] = point; gScore[(int) p.X, (int) p.Y] = gPossible; hScore[(int) p.X, (int) p.Y] = calculateHeuristic(p); fScore[(int) p.X, (int) p.Y] = gPossible + hScore[(int) p.X, (int) p.Y]; } } } return null; }
/// <summary> /// Объединение списков в указанном порядке /// </summary> /// <param name="simbolsToMarge"></param> /// <param name="mergeMode"></param> /// <returns></returns> public List<QuoteRecord> Merge(List<string> simbolsToMarge, MergeMode mergeMode = MergeMode.OutputMain) { List<QuoteRecord> result; var resourseDate = ((BaseParseFormat) Resourse).QuotesDate.Where(x => simbolsToMarge.Contains(x.Simbol)).ToList(); var outputDate = ((BaseParseFormat)Output).QuotesDate.Where(x => simbolsToMarge.Contains(x.Simbol)).ToList(); switch (mergeMode) { case MergeMode.ResourseMain: result = resourseDate; var exOutput = outputDate.Except(resourseDate, new QouteRecordDateComparer()); result.AddRange(exOutput); break; case MergeMode.OutputMain: result = outputDate; var exResourse = resourseDate.Except(outputDate, new QouteRecordDateComparer()); result.AddRange(exResourse); break; default: throw new ArgumentOutOfRangeException("mergeMode"); } return result.OrderBy(x => x.Simbol).ThenBy(x => x.Date).ToList(); }
/// <summary> /// Returns a collection of active <see cref="Rock.Model.PrayerRequest">PrayerRequests</see> that /// are in a specified <see cref="Rock.Model.Category"/> or any of its subcategories. /// </summary> /// <param name="categoryIds">A <see cref="System.Collections.Generic.List{Int32}"/> of /// the <see cref="Rock.Model.Category"/> IDs to retrieve PrayerRequests for.</param> /// <param name="onlyApproved">set false to include un-approved requests.</param> /// <param name="onlyUnexpired">set false to include expired requests.</param> /// <returns>An enumerable collection of <see cref="Rock.Model.PrayerRequest"/> that /// are in the specified <see cref="Rock.Model.Category"/> or any of its subcategories.</returns> public IEnumerable<PrayerRequest> GetByCategoryIds( List<int> categoryIds, bool onlyApproved = true, bool onlyUnexpired = true ) { PrayerRequest prayerRequest = new PrayerRequest(); Type type = prayerRequest.GetType(); var prayerRequestEntityTypeId = Rock.Web.Cache.EntityTypeCache.GetId( type ); // Get all PrayerRequest category Ids that are the **parent or child** of the given categoryIds. CategoryService categoryService = new CategoryService( (RockContext)Context ); IEnumerable<int> expandedCategoryIds = categoryService.GetByEntityTypeId( prayerRequestEntityTypeId ) .Where( c => categoryIds.Contains( c.Id ) || categoryIds.Contains( c.ParentCategoryId ?? -1 ) ) .Select( a => a.Id ); // Now find the active PrayerRequests that have any of those category Ids. var list = Queryable( "RequestedByPersonAlias.Person" ).Where( p => p.IsActive == true && expandedCategoryIds.Contains( p.CategoryId ?? -1 ) ); if ( onlyApproved ) { list = list.Where( p => p.IsApproved == true ); } if ( onlyUnexpired ) { list = list.Where( p => RockDateTime.Today <= p.ExpirationDate ); } return list; }
protected virtual void PromptForMissing(SemanticValueDict semantics, List<Slots> missing) { if (missing.Count == 4) { RecoManager.Instance.Say("What would you like to take?"); } else { if (missing.Contains(Slots.Semester) || missing.Contains(Slots.Year)) { RecoManager.Instance.Say("When would you like to take this course?"); } if (missing.Contains(Slots.Department)) { if (missing.Contains(Slots.Number)) { RecoManager.Instance.Say("Which course was that?"); } else { RecoManager.Instance.Say("What department is this course in?"); } } } }
public bool Activate(List<string> portIds, bool deactivateOtherPorts) { bool success; // update statuses SIMPLDbEnums.EquipStatusEnum status = SIMPLDbEnums.EquipStatusEnum.Active; IEnumerable<DeviceBase> portsToUpdate = Ports.Where(p => portIds.Contains(p.SerialNumber)).ToList(); success = MagnumApi.Actions.BulkStatusUpdate(status, ref portsToUpdate); if (success) { AssignMagnumActionResults(portsToUpdate); } foreach (string port in portIds) { ONTPort ontPort = Ports.FirstOrDefault(p => p.SerialNumber == port); if (ontPort != null) { ontPort.IsActive = true; } } if (deactivateOtherPorts) { IEnumerable<DeviceBase> deacPorts = this.Ports.Where(p => !portIds.Contains(p.SerialNumber)).AsEnumerable<DeviceBase>(); status = SIMPLDbEnums.EquipStatusEnum.Disabled; MagnumApi.Actions.BulkStatusUpdate(SIMPLDbEnums.EquipStatusEnum.Disabled, ref deacPorts); } this.IsActive = true; return true; }
private static void DFS( Dictionary<int, List<int>> graph, int start, int end, List<int> visited, List<int> path) { if (start == end) { if (distance > path.Count) { distance = path.Count; } return; } if (!visited.Contains(start)) { visited.Add(start); foreach (var node in graph[start]) { if (!visited.Contains(node)) { path.Add(node); DFS(graph, node, end, visited, path); path.Remove(node); visited.Remove(node); } } } }
public MonthPickerViewModel(List<DateTime> existingDates) { if (DesignerProperties.IsInDesignTool) { return; } Dates = new List<MonthPickerModel>(); var currentMonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1); var decemberIntwoYears = new DateTime(currentMonth.Year + 2, 12, 1); DateTime addMonth = currentMonth; //Months should start from Current Month. //Show monthly until December of Current Year + 2 (ie Current year = 2015 + 2 = 2017 so show All Months from May 2015 until December 2017). while (addMonth <= decemberIntwoYears) { if (!existingDates.Contains(addMonth)) { Dates.Add(new MonthPickerModel {Date = addMonth}); } addMonth = addMonth.AddMonths(1); } //Then only show December for next 18 years. (ie Dec 2018, Dec 2019, Dec 2020...... Dec 2035) for (int i = 1; i <= 18; i++) { if (!existingDates.Contains(addMonth)) { Dates.Add(new MonthPickerModel {Date = decemberIntwoYears.AddYears(i)}); } } OkButtonCommand = new DelegateCommand<object>(OkButtonHandler, CanExecuteOkButtonHandler); CancelButtonCommand = new DelegateCommand<object>(CanelButtonHandler, CanExecuteOkButtonHandler); }
protected override void Check(object sender, NewSkeletonEventArgs e) { checker.GetAbsoluteMovement(JointType.HandRight); _handToHeadDirections = checker.GetRelativePosition(JointType.ShoulderCenter, JointType.HandRight).ToList(); // Prüfe ob Handbewegung nach links abläuft und ob sich die Hand über dem Kopf befindet double handspeed = checker.GetAbsoluteVelocity(JointType.HandRight); //Debug.WriteLine(handspeed); // min required speed if (handspeed < 2) { _index = 0; } // hand must be right if (_index == 0 && _handToHeadDirections.Contains(Direction.Right)) { _index = 1; } // hand is on top else if (_index == 1 && _handToHeadDirections.Contains(Direction.Upward)) { _index = 2; } //hand is left else if (_index == 2 && _handToHeadDirections.Contains(Direction.Left)) { FireSucceeded(this, null); //Debug.WriteLine("triggered" + e.Skeleton.Timestamp); _index = 0; //if (index >= LOWER_BOUND_FOR_SUCCESS) //{ // fireSucceeded(this, null); //} } }
//----------------< process analysis and display >---------------- private static void analysisAndDisplay(string[] args, string[] files, string path, List<string> patterns, List<string> options) { bool R = false; bool X = false; if (options.Contains("/R") || options.Contains("/r")) R = true; if (options.Contains("/X") || options.Contains("/x")) X = true; Analyzer.doAnalysis(files); Display.displayArgument(args, files, path, patterns, options); Display.displayTypeDefined(files); if (R) { Analyzer.doRelationAnalysis(files); Display.displayRelation(files); } else { Display.displayOutput(files); } if (X) { XMLFileRedirection xml = new XMLFileRedirection(); xml.displayxml(R, files); } }
private static void ProcessDiagramsLinkShapes(Diagram diagram, List<NodeShape> allShapes, LayoutInfo info) { foreach (LinkShape shape in diagram.LinkShapes) { if (allShapes.Contains(shape.FromShape) && allShapes.Contains(shape.ToShape)) { LinkShapeInfo lInfo = new LinkShapeInfo(info.Store); lInfo.ElementId = shape.Element.Id; lInfo.SourceElementId = shape.FromShape.Element.Id; lInfo.TargetElementId = shape.ToShape.Element.Id; lInfo.LinkDomainClassId = shape.Element.GetDomainClass().Id; lInfo.SourceLocation = shape.SourceAnchor.GetRelativeLocation(); lInfo.TargetLocation = shape.TargetAnchor.GetRelativeLocation(); lInfo.RoutingMode = shape.RoutingMode; lInfo.EdgePoints = ConvertToRelativeEdgePoints(shape.EdgePoints, shape.SourceAnchor.AbsoluteLocation); info.LinkShapeInfos.Add(lInfo); } } foreach (Diagram d in diagram.IncludedDiagrams) ProcessDiagramsLinkShapes(d, allShapes, info); }
public static List<string> GetSqlParamNameList(string sqlText) { List<string> varList = new List<string>(); MatchCollection matchCollection = s_RegexVar.Matches(sqlText); for (int i = 0; i < matchCollection.Count; i++) { string txt = matchCollection[i].Groups["Variable"].Value.Trim(); if (!varList.Contains(txt)) { varList.Add(txt); } } List<string> rstList = new List<string>(matchCollection.Count); matchCollection = s_RegexParam.Matches(sqlText); for (int i = 0; i < matchCollection.Count; i++) { string txt = matchCollection[i].Groups["Variable"].Value.Trim(); if (!rstList.Contains(txt) && !varList.Contains(txt)) { rstList.Add(txt); } } return rstList; }
private void EnsureUniqueConstraintNames() { var names = new List<string>(); foreach (var table in Schema.Tables) { var pk = table.PrimaryKey; if (pk != null) { var name = pk.Name; if (names.Contains(name)) { pk.Name = table.Name + name; continue; } names.Add(name); } foreach (var fk in table.ForeignKeys) { var name = fk.Name; if (names.Contains(name)) { fk.Name = table.Name + name; continue; } names.Add(name); } } }
private List<SemanticObject> PerformTest(SemanticObject obj1, HashSet<SemanticObject> allObservedObjects) { List<SemanticObject> retList = new List<SemanticObject>(); foreach(Collision col in obj1.GetActiveCollisions()) { SemanticObjectSimple hitObj = (col.rigidbody == null) ? null : col.rigidbody.GetComponent<SemanticObjectSimple>(); // Ensures sufficiently low vertical relative velocity to be treated as "at rest" if (hitObj != null && Mathf.Abs(col.relativeVelocity.y) < 0.1f && !retList.Contains(hitObj) && !hitObj.IsChildObjectOf(obj1)) { // Check to see if there exists a contact where this object is above the other object foreach(ContactPoint pt in col.contacts) { if (pt.normal.y > 0.1f) { retList.Add(hitObj); foreach(SemanticObjectComplex parentObj in hitObj.GetParentObjects()) { // Add parent objects, unless we are also a child object of that parent if (!retList.Contains(parentObj) && !obj1.IsChildObjectOf(parentObj)) retList.Add(parentObj); } break; } } } } if (retList.Count > 0) return retList; return null; }
private IEnumerable<string> MergeInDefaultCompileTypes(IEnumerable<string> referencedAssemblyLocations) { var result = new List<string>(referencedAssemblyLocations); foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { if (assembly is AssemblyBuilder) continue; string location; try { location = assembly.Location; } catch (NotSupportedException) { continue; } if (result.Contains(location) == false) result.Add(location); } if (result.Contains(typeof(TemplateBase.Template).Assembly.Location) == false) result.Add(typeof(TemplateBase.Template).Assembly.Location); if (result.Contains(typeof(System.Web.HttpUtility).Assembly.Location) == false) result.Add(typeof(System.Web.HttpUtility).Assembly.Location); return result; }
/// <summary> /// Gets the aggregated list of pages that is expanded based on the current page, primary used for creating page navigation. /// </summary> /// <param name="documentSession">The document session.</param> /// <param name="id">The id of the current page</param> /// <returns></returns> public static IQueryable<IPage> GetPublishedPages(this IDocumentSession documentSession, string id) { if(string.IsNullOrEmpty(id)) { throw new ArgumentNullException("id","cannot be null"); } var page = documentSession.Query<Page, PageModelWithParentsAndChildren>() .Include(x => x.Ancestors) .Include(x => x.Children) .SingleOrDefault(x => x.Id == id); var ids = new List<string> { page.Id }; ids.AddRange(page.Children); foreach (var ancestor in page.Ancestors.Where(ancestor => ancestor.Children != null)) { if (!ids.Contains(ancestor.Id)) { ids.Add(ancestor.Id); } foreach (var child in ancestor.Children.Where(child => !ids.Contains(child))) { ids.Add(child); } } return documentSession.Load<IPage>(ids).AsQueryable(); }
public List<Fixture> GetFixturesForTeamLeagues(List<int> teamLeagueIds) { return (from f in fixtureRepository.Get() where teamLeagueIds.Contains(f.HomeTeamLeague.Id) || teamLeagueIds.Contains(f.AwayTeamLeague.Id) select f).ToList(); }
static void Main(string[] args) { var pentagons = new List<int>(); var differences = new List<int>(); var diff = 0; var sum = 0; for (var i = 1; i < 5000; i++) { var result1 = (i * ((3 * i) - 1)) / 2; pentagons.Add(result1); } var currPent = pentagons[0]; for (var j = 0; j < 3000; j++) { for (var k = j + 1; k < 3000; k++) { diff = Math.Abs(pentagons[j] - pentagons[k]); sum = pentagons[j] + pentagons[k]; if (pentagons.Contains(diff) && pentagons.Contains(sum)) { Console.WriteLine("Pof{0} and Pof{1}: Difference = {2}, Sum = {3}", j - 1, k - 1, diff, sum); differences.Add(Math.Abs(pentagons[j] - pentagons[k])); } //Console.WriteLine("{0} {1} {2} {3}", k, j, sum, diff); } if (j % 500 == 0) { Console.WriteLine("Finished with {0}", j); } } int smallestDiff = 999999999; foreach(var num in differences) { if (smallestDiff > num) { smallestDiff = num; } } Console.WriteLine(smallestDiff); Console.ReadLine(); }
static void Main(string[] args) { Console.WriteLine("start running client: " + DateTime.Now); bool runOnYarn = false; List<string> testToRun = new List<string>(); if (args != null) { if (args.Length > 0) { runOnYarn = bool.Parse(args[0].ToLower()); } for (int i = 1; i < args.Length; i++) { testToRun.Add(args[i].ToLower()); } } if (testToRun.Contains("RunPipelineBroadcastAndReduce".ToLower()) || testToRun.Contains("all") || testToRun.Count == 0) { new PipelineBroadcastAndReduceClient().RunPipelineBroadcastAndReduce(runOnYarn, 9); Console.WriteLine("RunPipelineBroadcastAndReduce completed!!!"); } if (testToRun.Contains("RunBroadcastAndReduce".ToLower()) || testToRun.Contains("all") || testToRun.Count == 0) { new BroadcastAndReduceClient().RunBroadcastAndReduce(runOnYarn, 9); Console.WriteLine("RunBroadcastAndReduce completed!!!"); } }
/// <summary> /// Add a list of files to the beginning of the most recently used characters. /// </summary> /// <param name="lstFilesToAdd">Names of the files to add (files added in reverse order).</param> public static void AddToMRUList(List <string> lstFilesToAdd, string strMRUType = "mru", bool blnDoMRUChanged = true) { bool blnAnyChange = false; List <string> strFiles = ReadMRUList(strMRUType); List <string> strStickyFiles = strMRUType == "mru" ? ReadMRUList("stickymru") : null; foreach (string strFile in lstFilesToAdd) { if (string.IsNullOrEmpty(strFile)) { continue; } // Make sure the file doesn't exist in the sticky MRU list if we're adding to base MRU list. if (strStickyFiles?.Contains(strFile) == true) { continue; } blnAnyChange = true; // Make sure the file does not already exist in the MRU list. if (strFiles.Contains(strFile)) { strFiles.Remove(strFile); } strFiles.Insert(0, strFile); } if (strFiles.Count > 10) { strFiles.RemoveRange(10, strFiles.Count - 10); } if (blnAnyChange) { int i = 0; foreach (string strItem in strFiles) { i++; _objBaseChummerKey.SetValue(strMRUType + i.ToString(), strItem); } if (blnDoMRUChanged && MRUChanged != null) { MRUChanged.Invoke(); } } }
/// <summary> /// Returns a collection of routes that satisfies a specified condition by stop count (used recursion). /// </summary> /// <param name="currentPort">The point of the routes that we will try visit.</param> /// <param name="endPort">The end point of the routes.</param> /// <param name="maxCountStops">The maximum number of stops.</param> /// <param name="path">The collection of ports that already were visited.</param> /// <returns>A collection of routes that satisfies a specified condition by stop count.</returns> private List <List <IPort> > GetRoutesWithStopsLimit(IPort currentPort, IPort endPort, int?maxCountStops, List <IPort> path) { // if the port already in the path we haven't a route if (path?.Contains(currentPort) ?? false) { return(null); } var currentPath = path?.ToList() ?? new List <IPort>(); currentPath.Add(currentPort); var result = new List <List <IPort> >(); // if the current route is equal the end port we find a route if (currentPort == endPort && path?.Count > 0) { result.Add(currentPath); return(result); } // check '>' because the first item is a start if (maxCountStops.HasValue && currentPath.Count > maxCountStops.Value) { return(null); } // check all routes from the current port foreach (var route in _shippingNetwork.Routes.Where(r => r.PortFrom == currentPort)) { // if the current route is equal the end port we find a route if (route.PortTo == endPort) { var findedPath = currentPath.ToList(); findedPath.Add(route.PortTo); result.Add(findedPath); continue; } var nodeRoutes = GetRoutesWithStopsLimit(route.PortTo, endPort, maxCountStops, currentPath); if (nodeRoutes != null && nodeRoutes.Count > 0) { result.AddRange(nodeRoutes); } } return(result); }
public bool Allowed( IContext context, SiteSettings ss, Permissions.Types?type, List <string> mine) { if (Depts?.Any() != true && Groups?.Any() != true && Users?.Any() != true && RecordUsers?.Any() != true && (Type ?? Permissions.Types.NotSet) == Permissions.Types.NotSet) { return(true); } else if (Depts?.Contains(context.DeptId) == true) { return(true); } else if (GroupContains(context: context, ss: ss)) { return(true); } else if (Users?.Contains(context.UserId) == true) { return(true); } else if (Type != null && Type != Permissions.Types.NotSet && (Type & type) == Type) { return(true); } else if (Type != null && Type != Permissions.Types.NotSet && RecordUsers?.Any() != true) { return(false); } else if (RecordUsers?.Any(o => mine == null || mine?.Contains(o) == true) == true) { return(true); } else { return(false); } }
public async void ReloadIfNeeded() { // Read completed schedules from preferences List <string> completedScheduleIds = appRepository.GetCompletedScheduleIds(); // TEST BEGIN Debug.WriteLine("Completed schedule IDs from user preferences:"); if (completedScheduleIds?.Count > 0) { foreach (string scheduleId in completedScheduleIds) { Debug.WriteLine(scheduleId); } } else { Debug.WriteLine("None."); } // TEST END if (!IsLoading) { if (ThemeModels == null) { IsLoading = true; Result <List <Theme> > result = await appRepository.GetAllThemesAsync(); if (result.Succeeded) { ThemeModels = result.Data .FindAll(t => t?.Content?.ScheduleIds?.Count > 0) .ConvertAll(t => new ThemeViewModel(t)); } else { Debug.WriteLine("Failed to load themes"); ThemeLoadFailed?.Invoke(this, EventArgs.Empty); } IsLoading = false; } // update completed flags on every call.. data binding will update list data template ThemeModels?.ForEach(t => t.IsCompleted = completedScheduleIds?.Contains(t.FirstScheduleId) == true); } }
private UserElementView SetUserViewList(string userId, Action <UserElementView> OnAddNewElement) { bool isBlocked = UserProfile.GetOwnUserProfile().blocked.Contains(userId); bool isAddedRol = usersInRolList?.Contains(userId) ?? false; if (!userElementViews.TryGetValue(userId, out UserElementView userElementView)) { userElementView = GetUserView(); OnAddNewElement?.Invoke(userElementView); userElementView.SetAlwaysHighlighted(true); userElementViews.Add(userId, userElementView); } userElementView.SetBlocked(isBlocked); userElementView.SetIsAdded(isAddedRol); return(userElementView); }
public BulkUpdateColumn GetRecordingData() { var bulkUpdateColumn = new BulkUpdateColumn(); bulkUpdateColumn.Id = Id; bulkUpdateColumn.Title = Title; if (Columns?.Any() == true) { bulkUpdateColumn.Columns = Columns; } if (Details?.Any() == true) { bulkUpdateColumn.Details = Details; bulkUpdateColumn.Details.RemoveAll((key, value) => Columns?.Contains(key) != true); } return(bulkUpdateColumn); }
private void OnPlayerJoined(object sender, EventArgs e) { if (!(bool)friendList?.Contains(sender as string)) { return; } for (int i = 0; i < joinedDateTimeList.Count; i++) { if (joinedDateTimeList[i].AddSeconds(10) < DateTime.Now) { joinedPlayerList.RemoveAt(i); joinedDateTimeList.RemoveAt(i); i--; } } joinedPlayerList.Add(sender as string); joinedDateTimeList.Add(DateTime.Now); VRNotify.BalloonTipTitle = "VRC 参加通知"; if (joinedPlayerList.Count == 1) { VRNotify.BalloonTipText = joinedPlayerList[0] + " さんがこのセッションに参加しています"; } else { VRNotify.BalloonTipText = ""; int i; for (i = 0; i < joinedPlayerList.Count; i++) { VRNotify.BalloonTipText += joinedPlayerList[i] + ","; if (VRNotify.BalloonTipText.Length > 32) { break; } } if (i != joinedPlayerList.Count) { VRNotify.BalloonTipText += "他" + (joinedPlayerList.Count - i) + "名がこのセッションに参加しています"; } else { VRNotify.BalloonTipText += "さんらがこのセッションに参加しています"; } } VRNotify.ShowBalloonTip(5000); }
private void ValidateScreenName(List <Entity> screenEntities, List <Entity> screens) { if (screenEntities == null || screenEntities.Count < 1) { return; } List <string> screenNames = screenEntities.Select(r => r.Name)?.ToList(); foreach (var screen in screens) { if (screenNames?.Contains(screen.Name) ?? false) { var newName = _helper.GetNewName(screen.Name); _helper.RenameControl(screen.EntityObject, newName); } } }
public ChooseFromCheckList(List <CheckListOption <T> > checklistElements, List <CheckListOption <T> > checkedElements, string windowTitle, string label, bool resetToDefault = false) { InitializeComponent(); buttonResetToDefault.Visible = resetToDefault; buttonResetToDefault.Text = "Reset"; foreach (var element in checklistElements) { checkedListBox.Items.Add(element, checkedElements?.Contains(element) ?? false); } Text = windowTitle; label1.Text = label; buttonOk.Text = "OK"; buttonCancel.Text = "Cancel"; Height = Math.Min(350, 125 + 17 * checklistElements.Count); }
public FormViews(Document document, List <int> selectedViewIds) : this() { var viewItems = GetViewItems(document); lvViews.Items.Clear(); var items = viewItems.OrderBy(x => x.ViewType).ThenBy(x => x.ViewName).ToList(); foreach (var item in items) { var viewItem = new ListViewItem(new[] { item.ViewType, item.ViewName }, 0) { Tag = item, Checked = selectedViewIds?.Contains(item.ViewId) ?? false }; lvViews.Items.Add(viewItem); } }
// SkyBox Specific Parsers internal List <Mode> Parse(string[] s, List <Mode> defaultValue) { if (defaultValue == null) { return(null); } for (int i = 0; i < s?.Length; i++) { Mode?mode = Parse(s[i], (Mode?)null); if (mode != null && defaultValue?.Contains((Mode)mode) == false) { defaultValue.Add((Mode)mode); } } return(defaultValue); }
private async Task <bool> CallNodeObserversAsync(ISnCancellableEvent snEvent, List <Type> disabledNodeObservers) { if (!IsFeatureEnabled(1)) { return(false); } var tasks = Providers.Instance.NodeObservers .Where(x => !disabledNodeObservers?.Contains(x.GetType()) ?? true) .Select(x => FireCancellableNodeObserverEventAsync(snEvent, x)) .ToArray(); await Task.WhenAll(tasks).ConfigureAwait(false); var canceled = tasks.Any(t => t.Result); return(canceled); }
public ItemSelectorForm(List <int> selectedItems = null, bool checkboxes = true, List <int> highlightedItems = null) { InitializeComponent(); for (int i = 0; i < ITEM_NAMES.Length; i++) { var item = new ListViewItem(ITEM_NAMES[i]); item.Checked = selectedItems?.Contains(i) ?? false; lItems.Items.Add(item); if (highlightedItems != null) { item.ForeColor = highlightedItems.Contains(i) ? Color.Black : Color.LightGray; } } ; this.ActiveControl = textBoxFilter; lItems.CheckBoxes = checkboxes; }
internal void LoadTables(List <string> loadTables = null) { var xmlApp = GetApplicationSchema(Client.AdminUserName, Client.AdminPassword, Client.AccountDomain).CreateNavigator(); var nodes = xmlApp.Select("/qdbapi/table/chdbids/chdbid"); foreach (XPathNavigator node in nodes) { var dbid = node.Value; if (loadTables?.Contains(dbid) ?? false) { try { var qDataTable = TableFactory.CreateInstance(this, dbid); this._qbDataTables.Add(qDataTable.TableId, qDataTable); } catch (InsufficientPermissionsException) { } } } }
private GameMember GetMember(GameParticipant part, ref GameMember me) { GameMember member; var player = part as PlayerParticipant; if (player != null) { PlayerChampionSelectionDTO selection; TradeContractDTO trade; selections.TryGetValue(player.SummonerInternalName, out selection); trades.TryGetValue(player.SummonerInternalName, out trade); bool canTrade = potentialTraders?.Contains(player.SummonerInternalName) ?? false; member = new GameMember(player, selection, trade, canTrade, lastGameDto.PickTurn); var pojo = player as ARAMPlayerParticipant; if (pojo != null) { member.Reroll = new RerollState(pojo.PointSummary); } if (player.SummonerId == session.Me.SummonerId) { me = member; } } else if (part is BotParticipant) { member = new GameMember((BotParticipant)part, lastGameDto.PickTurn); } else if (part is ObfuscatedParticipant) { member = new GameMember((ObfuscatedParticipant)part, lastGameDto.PickTurn); } else { throw new NotImplementedException(part.GetType().FullName); } standardMembers[member.Id] = part; return(member); }
/// <summary> /// An overload to insert all cards in a deck of cards into the cards collection field, /// but omitting the cards in a specified list. /// </summary> /// <param name="except">A collection of cards that should not be added to the cards /// collection field.</param> private void InsertAllCards(List <Card> except) { // Add 52 cards to the deck, with one card for each suit and rank combination. for (int suitVal = 0; suitVal < 4; suitVal++) { for (int rankVal = 1; rankVal < 14; rankVal++) { // Get an instance of the next card to be added to the collection. var card = new Card((Suit)suitVal, (Rank)rankVal); // If the card to be added is in the list of exceptions, then skip it. if (except?.Contains(card) == true) { continue; } cards.Add(card); } } }
public async Task SalvarConfiguracoesColunasAsync(List <string> colunasVisiveis, List <string> colunasChave, List <string> colunasFiltro) { try { var repositorio = new SqlClient.Repositorio(IdServidor); var idConfiguracaoTabela = await repositorio.SelecionarIdConfiguracaoTabelaAsync(Database, Schema, Nome); var idConfiguracaoTabelaColuna = 0; await repositorio.SalvarConfiguracoesTabelaAsync(idConfiguracaoTabela, Database, Schema, Nome); idConfiguracaoTabela = await repositorio.SelecionarIdConfiguracaoTabelaAsync(Database, Schema, Nome); foreach (var coluna in TodasColunas) { var visivel = colunasVisiveis.Contains(coluna.Nome); var filtro = colunasFiltro?.Contains(coluna.Nome) ?? false; var chave = string.Empty; if (colunasChave != null) { foreach (var item in colunasChave) { if (chave == string.Empty) { if (item.Split(":")[0] == coluna.Nome) { chave = item.Split(":")[1]; } } } } idConfiguracaoTabelaColuna = await repositorio.SelecionarIdConfiguracaoTabelaColunaAsync(Database, Schema, Nome, coluna.Nome); await repositorio.SalvarConfiguracaoColunaAsync(idConfiguracaoTabelaColuna, idConfiguracaoTabela, coluna.Nome, visivel, chave, filtro); } } catch (Exception ex) { throw ex; } }
// traversal pattern EXISTS // if any visit returns a true, stop recursion. So if you want to // visit all nodes regardless, use TraverseEachNode(). // public bool VisitEachExists(Func <T, bool> callback, List <Type> excluding = null) { if (excluding?.Contains(GetType()) ?? false) { return(false); } bool exists = callback((T)this); if (!exists) { foreach (var c in children_) { if (c.VisitEachExists(callback, excluding)) { return(true); } } } return(exists); }
private void ConfigInsightBoard(string contextMenuName, string recordIdentification) { IConfigurationUnitStore configStore = ConfigurationUnitStore.DefaultStore; Menu configMenu = configStore.MenuByName(contextMenuName); var skipMenusList = this.FormItem?.Options.ValueOrDefault("SkipMenus"); List <string> skipMenus = skipMenusList as List <string> ?? (skipMenusList as List <object>)?.Cast <string>().ToList(); int count = 0; bool useAllKindOfItems = Convert.ToInt32(this.FormItem?.Options.ValueOrDefault("useAllKindOfItems")) != 0; for (int i = 0; i < configMenu?.NumberOfSubMenus; i++) { Menu submenu = configMenu.SubMenuAtIndex(i); if (submenu == null || skipMenus?.Contains(submenu.UnitName) == true || submenu?.ViewReference?.ViewName == "DebugView") { continue; } if (submenu.ViewReference?.ViewName == "InsightBoardItem") { this.itemControllerArray.Add(new UPInsightBoardItemGroupModelController(submenu, this, count++, this.testViewReference, recordIdentification)); } else { if (useAllKindOfItems) { this.itemControllerArray.Add(new UPInsightBoardItemGroupModelController(submenu, this, count++, this.testViewReference, null)); } else { SimpleIoc.Default.GetInstance <ILogger>().LogWarn($"ViewName '{submenu.ViewReference?.ViewName}' not as insightBoard submenu supported"); } } } this.pending = this.itemControllerArray.Count; }
//ORIGINAL WORKING //public static List<TableDependency> GetParentDependenciesList(string tableSchema, string tableName, List<ForeignKeyConstraint> foreignKeyConstraints, bool recurse, List<ForeignKeyConstraint> processedForeignKeyConstraints = null) //{ // List<TableDependency> tableDependencies = new List<TableDependency>(); // // Get filtered list // List<ForeignKeyConstraint> foreignKeyConstraintsFiltered = foreignKeyConstraints.Where( // fkc => // fkc.TableSchema.ToUpper() == tableSchema.ToUpper() && // fkc.TableName.ToUpper() == tableName.ToUpper()).ToList(); // // Iterate through keys // foreach (ForeignKeyConstraint foreignKeyConstraint in foreignKeyConstraintsFiltered) // { // // Check if current foreign key already processed // if (!(processedForeignKeyConstraints?.Contains(foreignKeyConstraint) ?? false)) // { // tableDependencies.Add(new TableDependency(foreignKeyConstraint)); // // Process all parent foreign keys recursively // if (recurse) // { // if (processedForeignKeyConstraints == null) // { // processedForeignKeyConstraints = new List<ForeignKeyConstraint>(); // } // processedForeignKeyConstraints.Add(foreignKeyConstraint); // List<TableDependency> result = GetParentDependenciesList(foreignKeyConstraint.ReferencedTableSchema, foreignKeyConstraint.ReferencedTableName, foreignKeyConstraints, recurse, processedForeignKeyConstraints); // if (result.Count > 0) // { // tableDependencies.AddRange(result); // } // } // } // } // return tableDependencies; //} public static List <TableDependency> GetChildDependenciesList( string tableSchema, string tableName, List <ForeignKeyConstraint> foreignKeyConstraints, bool recurse, List <TableDependency> processedDependencies = null) { List <TableDependency> tableDependencies = new List <TableDependency>(); // Get filtered list List <ForeignKeyConstraint> foreignKeyConstraintsFiltered = foreignKeyConstraints.Where( fkc => fkc.ReferencedTableSchema.ToUpper() == tableSchema.ToUpper() && fkc.ReferencedTableName.ToUpper() == tableName.ToUpper()).ToList(); foreach (IGrouping <string, ForeignKeyConstraint> foreignKeyGroup in foreignKeyConstraintsFiltered.GroupBy(fkc => fkc.ForeignKeyName)) { TableDependency tableDependency = new TableDependency(foreignKeyGroup.ToList()); // Check if current foreign key already processed if (!(processedDependencies?.Contains(tableDependency) ?? false)) { tableDependencies.Add(tableDependency); // Process all dependencies recursively if (recurse) { if (processedDependencies == null) { processedDependencies = new List <TableDependency>(); } processedDependencies.Add(tableDependency); List <TableDependency> result = GetChildDependenciesList(tableDependency.ChildTableName.Schema, tableDependency.ChildTableName.Name, foreignKeyConstraints, recurse, processedDependencies); if (result.Count > 0) { tableDependencies.AddRange(result); } } } } return(tableDependencies); }
public static void Apply(OpenApiSchema schema, SchemaFilterContext context, string jsonSerializerCase) { if (schema.Enum?.Count > 0) { IList <IOpenApiAny> results = new List <IOpenApiAny>(); var enumValues = Enum.GetValues(context.Type); foreach (var enumValue in enumValues) { var enumValueString = enumValue.ToString().ToCase(jsonSerializerCase); if (Enums?.Contains(enumValueString) == true) { continue; } results.Add(new OpenApiString(enumValueString)); } schema.Type = "string"; schema.Format = null; schema.Enum = results; } }
public static WebElementInfoViewModel ClearAccrodingToBlocked(WebElementInfoViewModel webElementInfo, List <string> blockedElementsBreadStrings, List <string> blockedElementTypes) { var breadStr = webElementInfo.GetTreePath(); if ((blockedElementsBreadStrings?.Contains(breadStr) ?? false) || (blockedElementTypes?.Contains(webElementInfo.ElementType) ?? false)) { return(null); } if (webElementInfo is CombinedWebElementInfoViewModel cwe) { if (cwe.Elements != null) { for (int i = 0; i < cwe.Elements.Count; i++) { var cleared = ClearAccrodingToBlocked(cwe.Elements[i], blockedElementsBreadStrings, blockedElementTypes); if (cleared == null) { cwe.Elements.RemoveAt(i); i--; } } if (cwe.ElementType == WebElementTypes.Directory && (cwe.Elements == null || cwe.Elements.Count() == 0)) { return(null); } } } return(webElementInfo); }
/// <summary> /// Chooses the next action under an epsilon-greedy policy from amongst the available actions (or any actions if availableActions is null) /// </summary> /// <param name="actionRewards">The expected reward for picking a given action.</param> /// <param name="availableActions">The available action to choose from.</param> /// <returns></returns> public int ChooseAction(double[] actionRewards, List <int> availableActions = null) { double maxReward = -1; int greedyAction = 0; for (int i = 0; i < actionRewards.Length; i++) { if (availableActions?.Contains(i) ?? true && actionRewards[i] > maxReward) { maxReward = actionRewards[i]; greedyAction = i; } } //If we're set to explore, pick a random action from amongst the available ones if (_randy.NextDouble() < ExplorationRate) { return(ChooseRandomFrom(availableActions, _randy)); } return(greedyAction); }
public HiddenPluginsDialog(List <string> hiddenPlugins) { InitializeComponent(); foreach (var plugin in PluginManagerExtended.Instance.PluginsExt) { try { var title = plugin.Metadata.Name; var author = plugin.Metadata.Company; var version = plugin.Metadata.Version; var item = new ListViewItem(title); item.SubItems.Add(author); item.SubItems.Add(version); item.Checked = hiddenPlugins?.Contains(title) ?? false; lvPlugins.Items.Add(item); } catch { } } }
public static void PopulateEnumOptions <T>( ItemCollection parent, string bindingPath, object bindingSource, bool sorted = false, List <T> ignoreValues = null) where T : Enum { var values = Enum.GetValues(typeof(T)).Cast <T>(); if (sorted) { values = values.OrderBy(a => a.GetDescription()); } foreach (T value in values) { if (ignoreValues?.Contains(value) == true) { continue; } var headerText = value.GetDescription(); if (value is Dock dock) { headerText = DockToStringConverter.GetString(dock); } var item = new MenuItem { Header = headerText, IsCheckable = true }; SetEnumBinding(item, bindingPath, bindingSource, value); parent.Add(item); } }
private async void JoinRoomAsync(View obj) { var playerName = await _navigationService.Navigate <NameViewModel, string>(); if (string.IsNullOrEmpty(playerName)) { return; } var playerExists = PlayerNames?.Contains(playerName); if (playerExists == false || playerExists == null) { NotificationService.ReportError("Player doesn't exist, create new", "Create", (view => { this._signalrService.JoinGroup(this.RoomName, this.Password, playerName); this._navigationService.Navigate <MainViewModel>(); })); } else { this._signalrService.JoinGroup(this.RoomName, this.Password, playerName); await this._navigationService.Navigate <MainViewModel>(); } }
public List <Tag> SearchTags(string name, List <Tag> excludeList = null) { int maxResults = 10; List <Tag> results = new List <Tag>(); //filter tags based on exclude list List <Tag> filteredTags = _tags.Values.Where(tag => !excludeList?.Contains(tag) ?? true).ToList(); //search for tag with the exact name or with name to lower if (filteredTags.Any(tag => tag.Name == name)) { results.Add(filteredTags.First(tag => tag.Name == name)); } else if (filteredTags.Any(tag => tag.Name.ToLower() == name.ToLower())) { results.Add(filteredTags.First(tag => tag.Name.ToLower() == name.ToLower())); } //search for tags that start with name (don't include tags already in the results list) results.AddRange(filteredTags.Where(tag => !results.Contains(tag) && tag.Name.ToLower().StartsWith(name.ToLower())).ToList()); //return the first 10 results if 10 has already been reached if (results.Count >= maxResults) { return(results.Take(maxResults).ToList()); } //search for tags that contain name (don't include tags already in the results list) results.AddRange(filteredTags.Where(tag => !results.Contains(tag) && tag.Name.ToLower().Contains(name.ToLower()))); //return the first 10 results return(results.Take(maxResults).ToList()); }
public static List <DataRow> GetListOfForeignKeyConstraints(string tableSchema, string tableName, DataTable foreignKeyConstraintsTable, bool recurse, List <DataRow> processedForeignKeyConstraints = null) { List <DataRow> foreignKeysConstraints = new List <DataRow>(); // Get filtered list List <DataRow> foreignKeyConstraintsFiltered = foreignKeyConstraintsTable.AsEnumerable().Where( row => (row["TableSchema"].ToString().ToUpper() == tableSchema.ToUpper()) && (row["TableName"].ToString().ToUpper() == tableName.ToUpper()) ).ToList(); // Iterate through keys foreach (DataRow foreignKeyConstraintRow in foreignKeyConstraintsFiltered) { // Check if current foreign key already processed if (!(processedForeignKeyConstraints?.Contains(foreignKeyConstraintRow) ?? false)) { foreignKeysConstraints.Add(foreignKeyConstraintRow); // Process all parent foreign keys recursively if (recurse) { if (processedForeignKeyConstraints == null) { processedForeignKeyConstraints = new List <DataRow>(); } processedForeignKeyConstraints.Add(foreignKeyConstraintRow); List <DataRow> result = GetListOfForeignKeyConstraints(foreignKeyConstraintRow["ReferencedTableSchema"].ToString(), foreignKeyConstraintRow["ReferencedTableName"].ToString(), foreignKeyConstraintsTable, recurse, processedForeignKeyConstraints); if (result.Count > 0) { foreignKeysConstraints.AddRange(result); } } } } return(foreignKeysConstraints); }
public void Run(Transaction tx, DateTime blockTime, ulong coinbase = 0, List <TransactionOutput> spentTxo = null) { logger.LogDebug($@"Attempt to run TX:{ tx.Id.ToString().Substring(0, 7)}"); // Transaction header validity check. if (tx.Timestamp > blockTime || !(coinbase == 0 ^ tx.InEntries.Count == 0)) { throw new ArgumentException(); } // In-Entry validity check. ulong inSum = coinbase; var redeemed = new List <TransactionOutput>(); var signHash = BlockchainUtil.GetTransactionSignHash(tx.Original); foreach (var inEntry in tx.InEntries) { // Signature check. var verified = EccService.Verify( signHash, inEntry.Signature, inEntry.PublicKey); // UTXO check. The transaction output must not be spent by // previous transactions. var txo = new TransactionOutput { TransactionId = inEntry.TransactionId, OutIndex = inEntry.OutEntryIndex, }; var unspent = !(spentTxo?.Contains(txo) ?? false) && Utxos.TryGetValue(txo, out txo); // Recipient address check. var addr = BlockchainUtil.ToAddress(inEntry.PublicKey); var redeemable = txo.Recipient.Equals( ByteString.CopyFrom(addr)); // Sum all the reedemable. inSum = checked (inSum + txo.Amount); if (!verified || !unspent || !redeemable) { throw new ArgumentException(); } redeemed.Add(txo); } // Out-entry validity check. ulong outSum = 0; ushort outIndex = 0; var generated = new List <TransactionOutput>(); foreach (var outEntry in tx.OutEntries) { if (outEntry.RecipientHash.IsNull() || outEntry.Amount <= 0) { throw new ArgumentException(); } // Sum all the transferred. outSum = checked (outSum + outEntry.Amount); // Create new UTXO entry. generated.Add(new TransactionOutput { TransactionId = tx.Id, OutIndex = outIndex++, Recipient = outEntry.RecipientHash, Amount = outEntry.Amount, }); } // Output exceeds input or coinbase. if (outSum > inSum) { throw new ArgumentException(); } tx.ExecInfo = new TransactionExecInformation { Coinbase = coinbase != 0, RedeemedOutputs = redeemed, GeneratedOutputs = generated, TransactionFee = inSum - outSum, }; }
/// <summary> /// Puts the temporary variable on the free list which is used by the /// <see cref="Temp" /> method to reuse temporary variables. /// </summary> /// <param name="temp">The temporary variable to mark as no longer in use.</param> private void FreeTemp(ParameterExpression temp) { Debug.Assert(_freeTemps?.Contains(temp) != true); (_freeTemps ??= new List <ParameterExpression>()).Add(temp); }