void IInitializable.Initialize() { // parse resource metadata annotation. HashSet<string> metafileExts = new HashSet<string>(); char[] sep = { ';' }; foreach (ChildInfo chInfo in m_schemaLoader.GetRootElements()) { DomNodeType domtype = chInfo.Type; IEnumerable<XmlNode> annotations = domtype.GetTag<IEnumerable<XmlNode>>(); if (annotations == null) continue; foreach (XmlElement annot in annotations) { if (annot.LocalName != "ResourceMetadata") continue; string metaExt = annot.GetAttribute("metadataFileExt").ToLower(); metafileExts.Add(metaExt); string[] resExts = annot.GetAttribute("resourceFileExts").ToLower().Split(sep, StringSplitOptions.RemoveEmptyEntries); foreach (string ext in resExts) { ResourceMetadataInfo metadataInfo = new ResourceMetadataInfo(chInfo, metaExt); m_extMap.Add(ext, metadataInfo); } } } m_metadataFileExts = new string[metafileExts.Count]; metafileExts.CopyTo(m_metadataFileExts); }
public IGeometry Union() { PointLocator locater = new PointLocator(); // use a set to eliminate duplicates, as required for union var exteriorCoords = new HashSet<Coordinate>(); foreach (IPoint point in PointExtracter.GetPoints(_pointGeom)) { Coordinate coord = point.Coordinate; Location loc = locater.Locate(coord, _otherGeom); if (loc == Location.Exterior) { exteriorCoords.Add(coord); } } // if no points are in exterior, return the other geom if (exteriorCoords.Count == 0) { return _otherGeom; } // make a puntal geometry of appropriate size var exteriorCoordsArray = new Coordinate[exteriorCoords.Count]; exteriorCoords.CopyTo(exteriorCoordsArray, 0); Array.Sort(exteriorCoordsArray); ICoordinateSequence coords = _geomFact.CoordinateSequenceFactory.Create(exteriorCoordsArray); IGeometry ptComp = coords.Count == 1 ? (IGeometry)_geomFact.CreatePoint(coords.GetCoordinate(0)) : _geomFact.CreateMultiPoint(coords); // add point component to the other geometry return GeometryCombiner.Combine(ptComp, _otherGeom); }
public static void Init() { if ( !PluginSettings.Instance.PlayerBlockEnforcementEnabled ) return; if (_init) return; _init = true; MyEntities.OnEntityAdd += MyEntities_OnEntityAdd; HashSet<MyEntity> allEntities = new HashSet<MyEntity>(); Wrapper.GameAction( () => allEntities = MyEntities.GetEntities() ); MyEntity[] entitiesCopy = new MyEntity[allEntities.Count]; allEntities.CopyTo( entitiesCopy ); Parallel.ForEach( entitiesCopy, ( entity ) => { var grid = entity as MyCubeGrid; if ( grid == null ) return; InitGrid( grid ); } ); Essentials.Log.Info( "Initialized player block enforcement." ); ProcessEnforcement(); }
protected AuditSaveRequest GetAuditSaveRequest(ISaveRequestHandler handler) { var auditFields = new HashSet<Field>(); var flag = handler.IsCreate ? FieldFlags.Insertable : FieldFlags.Updatable; foreach (var field in handler.Row.GetFields()) if (field.Flags.HasFlag(flag)) auditFields.Add(field); Field[] array = new Field[auditFields.Count]; auditFields.CopyTo(array); var auditRequest = new AuditSaveRequest(handler.Row.Table, (IIdRow)handler.Old, (IIdRow)handler.Row, array); var parentIdRow = handler.Row as IParentIdRow; if (parentIdRow != null) { var parentIdField = (Field)parentIdRow.ParentIdField; if (!parentIdField.ForeignTable.IsTrimmedEmpty()) { auditRequest.ParentTypeId = parentIdField.ForeignTable; auditRequest.OldParentId = handler.IsCreate ? null : parentIdRow.ParentIdField[handler.Old]; auditRequest.NewParentId = parentIdRow.ParentIdField[handler.Row]; } } return auditRequest; }
public static string[] RemoveDuplicates(string[] s) { HashSet<string> set = new HashSet<string>(s); string[] result = new string[set.Count]; set.CopyTo(result); return result; }
public OutputData RenderScene(Scene scene) { ISet<Task<RenderData>> results = new HashSet<Task<RenderData>>(); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { Vector3f rayDirection = renderManager.CalculateEyeRayDirection(x, y); Vector3f rayStart = new Vector3f(x, y, 0.0f); results.Add(taskFactory.StartNew(() => CastEyeRay(new Ray(rayStart, rayDirection), scene))); } } Task<RenderData>[] resultsArray = new Task<RenderData>[results.Count]; results.CopyTo(resultsArray, 0); Task.WaitAll(resultsArray); BasicOutputConverter coverter = new BasicOutputConverter(1, width, height); RenderData[] finalData = new RenderData[resultsArray.Length]; for (int i = 0; i < finalData.Length; i++) { finalData[i] = resultsArray[i].Result; } return coverter.DoConversion(finalData); }
/// <summary> /// Initializes this force-directed layout. Assumes that graph has some /// reasonable initial node positions. /// </summary> /// <param name="graph">The graph to layout.</param> /// <param name="start_node">The node to start layout from.</param> public ForceDirectedLayout(IReadOnlyGraph<FDLNode, FDLEdge> graph, FDLNode start_node) { if (graph == null) throw new ArgumentNullException("graph"); if (start_node == null) throw new ArgumentNullException("start_node"); if (!graph.ContainsNode(start_node)) throw new ArgumentException("start_node must be in this graph"); //initialize nodes array to only the reachable nodes ArrayList n = new ArrayList(graph.NodeCount); Algorithms.Algorithms.BreadthFirstSearch(graph, start_node, null, delegate(FDLNode node){ n.Add(node); }); nodes = new FDLNode[n.Count]; n.CopyTo(nodes); new_positions = new MutablePoint[nodes.Length]; accels = new double[nodes.Length]; //summarize constraints HashSet<FDLEdge> h = new HashSet<FDLEdge>(); for (int i = 0; i < nodes.Length; i++) { foreach (FDLEdge edge in nodes[i].OutEdges) { DefaultEdge reverse = edge.Target.GetEdgeTo(edge.Source); if(h.Contains(edge) || (reverse != null && h.Contains(reverse))) continue; h.Add(edge); } } constraints = new FDLEdge[h.Count]; h.CopyTo(constraints); }
private List<Line> lines = new List<Line>(); // The lines contain info about all blocks from bottom to top. #endregion Fields #region Methods /// <summary> /// Add the chip blocks to grid. /// </summary> /// <param name='toAdd'> /// The chip is will be added. /// </param> public void Add(Chip toAdd) { int lineIndex, blockIndex; Vector3 blockPos; Line tempLine; HashSet<Line> affectedLines=new HashSet<Line>(); foreach(Transform blockTrans in toAdd.blocks){ blockPos=transform.TransformPoint(blockTrans.position); lineIndex=Mathf.RoundToInt(blockPos.y); if(lineIndex>=lines.Count){ for(int i=lineIndex-lines.Count; i>=0; i--){ tempLine=Instantiate(lineEtalon)as Line; tempLine.transform.SetParent(transform); tempLine.transform.rotation=Quaternion.identity; tempLine.transform.localPosition=new Vector3(0f, lines.Count, 0f); lines.Add(tempLine); } } tempLine=lines[lineIndex]; affectedLines.Add(tempLine); blockIndex=Mathf.RoundToInt(blockPos.x); tempLine.blocks[blockIndex]=blockTrans; blockTrans.SetParent(tempLine.transform); } //remove chip toAdd.blocks.Clear(); Destroy(toAdd.gameObject); //check lines for remove Line[] checkList=new Line[affectedLines.Count]; affectedLines.CopyTo(checkList); RemoveFilledLines(checkList); }
public int[] Intersection(int[] nums1, int[] nums2) { int[] intersectArray = new int[0]; if (nums1.Length == 0 || nums2.Length == 0) { return intersectArray; } foreach(int i in nums1) { if (!valueSet.Contains(i)) { valueSet.Add(i); } } HashSet<int> intersectSet = new HashSet<int>(); foreach(int j in nums2) { if (valueSet.Contains(j)) { intersectSet.Add(j); } } intersectArray = new int[intersectSet.Count]; intersectSet.CopyTo(intersectArray); return intersectArray; }
public void Test_CopyTo() { hs = new HashSet<int>(); hs.Add(1); hs.Add(2); hs.Add(3); int[] mass = { 1, 2, 3 }; int[] mass1 = new int[3]; hs.CopyTo(mass1); Assert.That(mass1, Is.EqualTo(mass)); }
public static void CopyTo_Array_Test2() { HashSet<int> hashSet = new HashSet<int>(new int[] { 1, 2, 3, 4, 5, 6, 7 }); int[] array = new int[] { -1, -2, -3, -4, -5, -6, -7, -8, -9 }; hashSet.CopyTo(array); HashSet<int> hashSet2 = new HashSet<int>(array); HashSetTestSupport<int>.VerifyHashSet(hashSet, new int[] { 1, 2, 3, 4, 5, 6, 7 }, EqualityComparer<int>.Default); HashSetTestSupport<int>.VerifyHashSet(hashSet2, new int[] { 1, 2, 3, 4, 5, 6, 7, -8, -9 }, EqualityComparer<int>.Default); }
private uint[] ReadBeats(StoryBeat[] beats) { HashSet<uint> seenIds = new HashSet<uint>(); foreach (StoryBeat beat in beats) foreach (StoryEvent evt in beat.Events) foreach (uint id in evt.Participants) seenIds.Add(id); uint[] result = new uint[seenIds.Count]; seenIds.CopyTo(result); return result; }
/// <summary> /// Generates the sequence of integer numbers. /// </summary> private void Generate() { var seq = new HashSet<int>(); var array = new int[ this.Target ]; while ( seq.Count < this.Target ) { seq.Add( this.rnd.Next( this.Target ) ); } seq.CopyTo( array ); this.sequence = new ReadOnlyCollection<int>( array ); }
public static void CopyTo_Array_Exceptions() { //Test 1: Array is null HashSet<int> hashSet = new HashSet<int>(new int[] { 1, 2, 3, 4, 5, 6, 7 }); int[] array = null; Assert.Throws<ArgumentNullException>(() => hashSet.CopyTo(array)); //"Expected ArgumentNullException" //Test 2: Array is one smaller than set size hashSet = new HashSet<int>(new int[] { 1, 2, 3, 4, 5, 6, 7 }); array = new int[6]; Assert.Throws<ArgumentException>(() => hashSet.CopyTo(array)); //"Expected ArgumentException" }
public void setIntTuplesWithSwapsAndSignChange(IntTuple[] inputIntTuples, IntTupleEqualityComparer comparer) { HashSet<IntTuple> container = new HashSet<IntTuple>(comparer); foreach (var intTuple in inputIntTuples) { container.Add(intTuple); addOppositeElements(container, intTuple); addSwapElements(container); } this.intTuples = new IntTuple[container.Count]; container.CopyTo(this.intTuples); }
public string CreateResourceFilters(Table sel) { HashSet<string> resIds = new HashSet<string>(); int resCol = sel.ColumnDefinitions.IndexOf("ResID"); for (int i = 0; i < sel.Rows; i++) { resIds.Add((string)sel[i, resCol]); } if (resIds.Count == 0) return null; string[] ids = new string[resIds.Count]; resIds.CopyTo(ids); if (ids.Length == 1) return "ResID=" + ids[0]; else return "ResID in (" + string.Join(",", ids) + ")"; }
protected AbstractMatcher(int[] indices) { var indicesSet = new HashSet<int>(indices); _indices = new int[indicesSet.Count]; indicesSet.CopyTo(_indices); Array.Sort(_indices); int hash = GetType().GetHashCode(); for (int i = 0, indicesLength = _indices.Length; i < indicesLength; i++) { hash ^= _indices[i] * 647; } hash ^= _indices.Length * 997; _hash = hash; }
public static bool Overlap(this Collider2D collider, Vector2 point1, Vector2 point2, out Collider2D[] listOverlap) { var res = new HashSet<Collider2D>(); var layer = collider.gameObject.layer; var colliders = Physics2D.OverlapAreaAll(point1, point2); foreach (Collider2D item in colliders) if (!item.isTrigger && !Physics2D.GetIgnoreLayerCollision(layer, item.gameObject.layer)) res.Add(item); listOverlap = new Collider2D[res.Count]; res.CopyTo(listOverlap); return (listOverlap.Length > 0); }
private void Awake() { mesh = GetComponent<MeshFilter>().sharedMesh; HashSet<Vector4> meshPlanes = new HashSet<Vector4>(); for(int i=0 ; i<mesh.triangles.Length ; i+=3) { Plane face = new Plane(GetVertex(i), GetVertex(i + 1), GetVertex(i + 2)); Vector4 planeEq = new Vector4(face.normal.x, face.normal.y, face.normal.z, face.distance); if (!meshPlanes.Contains(planeEq)) { meshPlanes.Add(planeEq); } } initPlanes = new Vector4[meshPlanes.Count]; meshPlanes.CopyTo(initPlanes); }
static int Main(string[] args) { object obj = new object(); HashSet<object> hashset; Object[] oa = new Object[2]; hashset = new HashSet<object>(); hashset.Add(obj); hashset.Remove(obj); //Regression test: make sure these don't throw. foreach (object o in hashset) { } hashset.CopyTo(oa, 0, 2); hashset.RemoveWhere(MyPredicate); return 100; }
public Color[] UniqueColors(int amount) { if (amount > tileColors.Length) { amount = tileColors.Length; Debug.LogWarning("Can't get " + amount + " unique colors when there are only " + tileColors.Length + " colors to choose from!"); } Color[] uniqueColors = new Color[amount]; HashSet<Color> uniqueColorsSet = new HashSet<Color>(); while (uniqueColorsSet.Count != amount) { uniqueColorsSet.Add(RandomColor()); } uniqueColorsSet.CopyTo(uniqueColors); return uniqueColors; }
public static AttributeInfo[] GetCustomAttributes(Assembly assembly, Type attribute) { if (assembly == null) { throw new ArgumentNullException("assembly"); } HashSet<AttributeInfo> attributes = new HashSet<AttributeInfo>(); foreach (Type type in assembly.GetExportedTypes()) { foreach (Attribute attr in type.GetCustomAttributes(attribute, true)) { AttributeInfo attributeInfo = new AttributeInfo(type, attr); attributes.Add(attributeInfo); } } AttributeInfo[] result = new AttributeInfo[attributes.Count]; attributes.CopyTo(result); return result; }
public static void Regression_Dev10_624201() { Predicate<object> predicate = (Object o) => { return false; }; object obj = new object(); HashSet<object> hashset; Object[] oa = new Object[2]; hashset = new HashSet<object>(); hashset.Add(obj); hashset.Remove(obj); //Regression test: make sure these don't throw. foreach (object o in hashset) { } hashset.CopyTo(oa, 0, 2); hashset.RemoveWhere(predicate); // we just want to make sure it doesn't throw. }
public void CopyToTest() { var set = new HashSet<int>(); var limit = rnd.Next(10, 100); for (int i = 0; i < limit; i++) { set.Add(i); } var arr = new int[10+limit]; for (int i = 0; i < 10; i++) { arr[i] = -i-1; } set.CopyTo(arr, 10); for (int i = 10; i < arr.Length; i++) { Assert.AreEqual(arr[i],i-10); } }
public void DistributedCacheEmulator_Increment_WorksMultiThreaded() { var cache = new DistributedCacheEmulator(); cache.Set("MultiThreadedValue", 12345); var values = new HashSet<long>(); Parallel.ForEach(new int[100], x => { var result = cache.Increment("MultiThreadedValue"); lock (values) values.Add(result); }); Assert.Equal(100, values.Count); var sorted = new long[100]; values.CopyTo(sorted); Array.Sort(sorted); for (var i = 0; i < sorted.Length; i++) Assert.Equal(i + 1 + 12345, sorted[i]); }
public void Analize() { Assembly assembly; Type[] types; ISet<CodeDetails> allCodes = new HashSet<CodeDetails>(); assembly = Assembly.LoadFrom(path); types = assembly.GetExportedTypes(); foreach (Type type in types) { if (type.IsClass && !type.IsInterface && !type.IsAbstract && !type.IsGenericType) { if (typeof(ICode).IsAssignableFrom(type)) allCodes.Add(RetriveDetails(type)); } } codes = new CodeDetails[allCodes.Count]; allCodes.CopyTo(codes, 0); }
private static char[] GetInvalidPathChars() { // Union InvalidFileNameChars and InvalidPathChars together // while excluding slash. HashSet<char> charSet = new HashSet<char>(Path.GetInvalidPathChars()); foreach (char c in invalidFileNameChars) { if ('\\' == c || '/' == c || charSet.Contains(c)) { continue; } charSet.Add(c); } invalidPathChars = new char[charSet.Count]; charSet.CopyTo(invalidPathChars); return invalidPathChars; }
public IList<KeyValuePair<string, string>> Map(string fileLine) { IList<KeyValuePair<String, String>> result = new List<KeyValuePair<String, String>>(); string[] splitWords = fileLine.Split(new char[] { '.', '?', '!', ' ', ';', ':', ',' }, StringSplitOptions.RemoveEmptyEntries); HashSet<string> set = new HashSet<string>(splitWords); string[] noDuplicateWords = new string[set.Count]; set.CopyTo(noDuplicateWords); try { foreach (string word in noDuplicateWords) { int wordCount = Regex.Matches(fileLine, word).Count; result.Add(new KeyValuePair<String, String>(word, wordCount.ToString())); } } catch (Exception) { // Do not add line to result } return result; }
public override void Execute() { var regularExpression = new StringBuilder(); // Name the grouping "Parameter", make it start with ":" or "@", then a letter, and followed by up to 29 letters, numbers, or underscores. Finally, look ahead // and make sure the next character is not a letter, number, or underscore. regularExpression.Append(@"(?<Parameter>[:@][a-zA-Z][a-zA-Z0-9_\.]{0,127})(?=[^a-zA-Z0-9_\.])"); // Or, allow the same thing as above accept look ahead and allow the string to end immediately after the parameter. regularExpression.Append(@"|(?<Parameter>[:@][a-zA-Z][a-zA-Z0-9_\.]{0,127})$"); var regex = new Regex(regularExpression.ToString(), RegexOptions.Multiline); var matches = regex.Matches(CommandText); var parameterNameSet = new HashSet<string>(); for (var i = 0; i < matches.Count; i++) { parameterNameSet.Add(matches[i].Groups["Parameter"].Value); } ParameterNames = new string[parameterNameSet.Count]; parameterNameSet.CopyTo(ParameterNames); }
public void CopyTo(T[] array, int arrayIndex) { lock (this) _internalList.CopyTo(array, arrayIndex); }
public static void MakeClassifier(String addressOfTrainingSet) { StreamReader fileReader = new StreamReader(addressOfTrainingSet); attributes = fileReader.ReadLine().Split(new [] { dataSeparator }, StringSplitOptions.None); fileReader.Close(); horizontalLength = attributes.Length; attributesTypes = new String[horizontalLength]; pointsOfDivision = new List <List <Double> >(); attributesValuesNumbers = new List <int>(); // TODO: change marks of attributes types for english equivalents. // User enters types of attributes. for (int i = 0; i < attributesTypes.Length; i++) { do { Console.WriteLine($"Following attribute has been founded: {attributes[i]}. Enter its type: \"K\"" + $" for categorical, \"L\" for number valued or \"D\" for decision attribute." + $"Type \"P\" to skip it in process."); attributesTypes[i] = Console.ReadLine(); } while(!(attributesTypes[i].Equals("K") ^ attributesTypes[i].Equals("L") ^ attributesTypes[i].Equals("P") ^ attributesTypes[i].Equals("D"))); if (attributesTypes[i].Equals("L")) { Console.WriteLine("Values of attribute will be divided into right-closed intervals. Enter " + "division points in ascending order, separating them with \";\"."); String[] sPoints = Console.ReadLine().Split(';'); List <Double> dPoints = new List <Double>(); foreach (String point in sPoints) { try { dPoints.Add(Double.Parse(point)); } catch (FormatException ex) { Console.WriteLine("Something is wrong with division points."); } } attributesValuesNumbers.Add(dPoints.Count() + 1); pointsOfDivision.Add(dPoints); } else { pointsOfDivision.Add(new List <Double>()); attributesValuesNumbers.Add(0); } if (attributesTypes[i].Equals("D")) { decAttPosition = i; } } // Records counting. int verticalLength = HelpTools.CountLines(addressOfTrainingSet); // TODO: separate case when first line isn't an attributes names line. // Records number is 1 less than lines number, because first line contains attributes names. int recordsNumber = verticalLength - 1; Console.WriteLine($"Database contains {recordsNumber} records."); // Create array containing all data from database. String[,] dataBase = HelpTools.DataBaseToArray(addressOfTrainingSet, dataSeparator, false); // First line from the file, with attributes names, was read before. // Create lists of arrays, containing all occurring categorical attributes values. attributesValues = new List <String[]>(); for (int i = 0; i < horizontalLength; i++) { if (attributesTypes[i].Equals("K") || attributesTypes[i].Equals("D")) { HashSet <String> categoricalValuesSet = new HashSet <String>(); for (int t = 0; t < dataBase.GetLength(0); t++) { categoricalValuesSet.Add(dataBase[t, i]); } String[] categoricalValues = new String[categoricalValuesSet.Count]; categoricalValuesSet.CopyTo(categoricalValues); attributesValues.Add(categoricalValues); attributesValuesNumbers.Insert(i, categoricalValues.Length); } else { attributesValues.Add(new String[0]); } } int maxAttributesValuesNumber = attributesValuesNumbers.Max(); // At this point, all needed data to make classifier was gathered. decisionAttributeValues = attributesValues.ElementAt(decAttPosition); double[,,] countMatrix = new double[decisionAttributeValues.Length, horizontalLength, maxAttributesValuesNumber]; double[] decisionAttributesCounters = new double[decisionAttributeValues.Length]; // Counting occurrences of possible combinations. for (int n = 0; n < recordsNumber; n++) { for (int i = 0; i < decisionAttributeValues.Length; i++) { if (decisionAttributeValues[i].Equals(dataBase[n, decAttPosition])) { for (int j = 0; j < horizontalLength; j++) { if (j != decAttPosition) { // For categorical attributes. if (attributesTypes[j].Equals("K")) { for (int k = 0; k < attributesValuesNumbers.ElementAt(j); k++) { if (attributesValues.ElementAt(j)[k].Equals(dataBase[n, j])) { countMatrix[i, j, k]++; } } } // For number valued attributes. if (attributesTypes[j].Equals("L")) { for (int k = pointsOfDivision.ElementAt(j).Count; k > 0; k--) { if (Double.Parse(dataBase[n, j]) >= pointsOfDivision.ElementAt(j).ElementAt(k - 1)) { countMatrix[i, j, k]++; break; } if (k == 1) { countMatrix[i, j, 0]++; } } } } } decisionAttributesCounters[i]++; } } } // Counts probabilities of occurrences decision attributes values. decisionAttributesProbabilities = new double[decisionAttributesCounters.Length]; for (int i = 0; i < decisionAttributesCounters.Length; i++) { decisionAttributesProbabilities[i] = decisionAttributesCounters[i] / recordsNumber; } // Create matrix of conditional probabilities. conditionalProbabilitiesMatrix = new double[decisionAttributeValues.Length, horizontalLength, maxAttributesValuesNumber]; for (int i = 0; i < decisionAttributeValues.Length; i++) { for (int j = 0; j < horizontalLength; j++) { if (j != decAttPosition && !attributesTypes[j].Equals("P")) { double[] zeroCheckArray = new double[attributesValuesNumbers.ElementAt(j)]; for (int r = 0; r < attributesValuesNumbers.ElementAt(j); r++) { zeroCheckArray[r] = countMatrix[i, j, r]; } Array.Sort(zeroCheckArray); // Solves zero problem. if (zeroCheckArray[0] != 0) { for (int k = 0; k < attributesValuesNumbers.ElementAt(j); k++) { conditionalProbabilitiesMatrix[i, j, k] = countMatrix[i, j, k] / decisionAttributesCounters[i]; } } else { // Use Laplacian estimator. for (int k = 0; k < attributesValuesNumbers.ElementAt(j); k++) { conditionalProbabilitiesMatrix[i, j, k] = (countMatrix[i, j, k] + 1) / (decisionAttributesCounters[i] + attributesValuesNumbers.ElementAt(j)); } } } } } }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// protected override bool Setup() { bool result = base.Setup(); OutOfDateSources = Sources; if (result && !SkippedExecution) { // // Retrieve list of sources considered out-of-date due to either command line changes or tracker flagging. // TODO: Switch use of CanonicalTracked* helpers to TrackedFileManager. // CanonicalTrackedOutputFiles trackedOutputFiles = new CanonicalTrackedOutputFiles(this, TLogWriteFiles); TrackedInputFiles = new CanonicalTrackedInputFiles(this, TLogReadFiles, Sources, ExcludedInputPaths, trackedOutputFiles, true, false); //true); ITaskItem [] outOfDateSourcesFromTracking = TrackedInputFiles.ComputeSourcesNeedingCompilation(); // (true); ITaskItem [] outOfDateSourcesFromCommandLine = GetOutOfDateSourcesFromCmdLineChanges(Sources); #if DEBUG Log.LogMessageFromText(string.Format("[{0}] --> No. out-of-date sources (from tracking): {1}", ToolName, outOfDateSourcesFromTracking.Length), MessageImportance.Low); Log.LogMessageFromText(string.Format("[{0}] --> No. out-of-date sources (command line differs): {1}", ToolName, outOfDateSourcesFromCommandLine.Length), MessageImportance.Low); #endif // // Merge out-of-date lists from both sources and assign these for compilation. // HashSet <ITaskItem> mergedOutOfDateSources = new HashSet <ITaskItem> (outOfDateSourcesFromTracking); foreach (ITaskItem item in outOfDateSourcesFromCommandLine) { if (!mergedOutOfDateSources.Contains(item)) { mergedOutOfDateSources.Add(item); } } OutOfDateSources = new ITaskItem [mergedOutOfDateSources.Count]; mergedOutOfDateSources.CopyTo(OutOfDateSources); if ((OutOfDateSources == null) || (OutOfDateSources.Length == 0)) { SkippedExecution = true; } else { // // Remove sources to compile from tracked file list. // TrackedInputFiles.RemoveEntriesForSource(OutOfDateSources); trackedOutputFiles.RemoveEntriesForSource(OutOfDateSources); TrackedInputFiles.SaveTlog(); trackedOutputFiles.SaveTlog(); } } #if DEBUG Log.LogMessageFromText(string.Format("[{0}] --> Skipped execution: {1}", ToolName, SkippedExecution), MessageImportance.Low); for (int i = 0; i < OutOfDateSources.Length; ++i) { Log.LogMessageFromText(string.Format("[{0}] --> Out-of-date Sources: [{1}] {2}", ToolName, i, OutOfDateSources [i].ToString()), MessageImportance.Low); } #endif return(result); }
public void Run(ILogger customLogger = null) { Pipeline p = GetStandardPipeline(); using (LinkContext context = GetDefaultContext(p)) { if (customLogger != null) { context.Logger = customLogger; } I18nAssemblies assemblies = I18nAssemblies.All; var custom_steps = new List <string> (); var excluded_features = new HashSet <string> (StringComparer.Ordinal); var disabled_optimizations = new HashSet <string> (StringComparer.Ordinal); var enabled_optimizations = new HashSet <string> (StringComparer.Ordinal); bool dumpDependencies = false; bool ignoreDescriptors = false; bool removeCAS = true; bool resolver = false; while (HaveMoreTokens()) { string token = GetParam(); if (token.Length < 2) { Usage("Option is too short"); } if (!(token [0] == '-' || token [1] == '/')) { Usage("Expecting an option, got instead: " + token); } if (token [0] == '-' && token [1] == '-') { if (token.Length < 3) { Usage("Option is too short"); } switch (token) { case "--skip-unresolved": bool ignoreUnresolved = bool.Parse(GetParam()); context.IgnoreUnresolved = ignoreUnresolved; context.Resolver.IgnoreUnresolved = ignoreUnresolved; continue; case "--verbose": context.LogMessages = true; continue; case "--dependencies-file": context.Tracer.DependenciesFileName = GetParam(); continue; case "--dump-dependencies": dumpDependencies = true; continue; case "--reduced-tracing": context.EnableReducedTracing = bool.Parse(GetParam()); continue; case "--used-attrs-only": context.KeepUsedAttributeTypesOnly = bool.Parse(GetParam()); continue; case "--strip-security": removeCAS = bool.Parse(GetParam()); continue; case "--strip-resources": context.StripResources = bool.Parse(GetParam()); continue; case "--exclude-feature": var name = GetParam(); foreach (var feature in name.Split(',')) { if (!excluded_features.Contains(feature)) { excluded_features.Add(feature); } } continue; case "--explicit-reflection": context.AddReflectionAnnotations = true; continue; case "--custom-step": custom_steps.Add(GetParam()); continue; case "--keep-facades": context.KeepTypeForwarderOnlyAssemblies = bool.Parse(GetParam()); continue; case "--keep-dep-attributes": context.KeepDependencyAttributes = bool.Parse(GetParam()); continue; case "--ignore-descriptors": ignoreDescriptors = bool.Parse(GetParam()); continue; case "--disable-opt": var opt = GetParam().ToLower(); if (!disabled_optimizations.Contains(opt)) { disabled_optimizations.Add(opt); } continue; case "--enable-opt": opt = GetParam().ToLower(); if (!enabled_optimizations.Contains(opt)) { enabled_optimizations.Add(opt); } continue; case "--new-mvid": if (!bool.Parse(GetParam())) { p.RemoveStep(typeof(RegenerateGuidStep)); } continue; case "--deterministic": context.DeterministicOutput = true; p.RemoveStep(typeof(RegenerateGuidStep)); continue; } switch (token [2]) { case 'v': Version(); break; case 'a': About(); break; default: Usage(null); break; } } // Ensure this does not conflict with '-r' below. if (token == "-reference") { context.Resolver.AddReferenceAssembly(GetParam()); continue; } switch (token [1]) { case 'd': DirectoryInfo info = new DirectoryInfo(GetParam()); context.Resolver.AddSearchDirectory(info.FullName); break; case 'o': context.OutputDirectory = GetParam(); break; case 'c': context.CoreAction = ParseAssemblyAction(GetParam()); break; case 'u': context.UserAction = ParseAssemblyAction(GetParam()); break; case 'p': AssemblyAction action = ParseAssemblyAction(GetParam()); context.Actions [GetParam()] = action; break; case 't': context.KeepTypeForwarderOnlyAssemblies = true; break; case 'x': foreach (string file in GetFiles(GetParam())) { p.PrependStep(new ResolveFromXmlStep(new XPathDocument(file))); } resolver = true; break; case 'r': case 'a': var rootVisibility = (token [1] == 'r') ? ResolveFromAssemblyStep.RootVisibility.PublicAndFamily : ResolveFromAssemblyStep.RootVisibility.Any; foreach (string file in GetFiles(GetParam())) { p.PrependStep(new ResolveFromAssemblyStep(file, rootVisibility)); } resolver = true; break; case 'i': foreach (string file in GetFiles(GetParam())) { p.PrependStep(new ResolveFromXApiStep(new XPathDocument(file))); } resolver = true; break; case 'l': assemblies = ParseI18n(GetParam()); break; case 'm': context.SetParameter(GetParam(), GetParam()); break; case 'b': context.LinkSymbols = bool.Parse(GetParam()); break; case 'g': if (!bool.Parse(GetParam())) { p.RemoveStep(typeof(RegenerateGuidStep)); } break; case 'z': ignoreDescriptors = !bool.Parse(GetParam()); break; case 'v': context.KeepMembersForDebugger = bool.Parse(GetParam()); break; default: Usage("Unknown option: `" + token [1] + "'"); break; } } if (!resolver) { Usage("No resolver was created (use -x, -a or -i)"); } if (ignoreDescriptors) { p.RemoveStep(typeof(BlacklistStep)); } if (dumpDependencies) { context.Tracer.Start(); } foreach (string custom_step in custom_steps) { AddCustomStep(p, custom_step); } if (context.AddReflectionAnnotations) { p.AddStepAfter(typeof(MarkStep), new ReflectionBlockedStep()); } p.AddStepAfter(typeof(LoadReferencesStep), new LoadI18nAssemblies(assemblies)); if (_needAddBypassNGenStep) { p.AddStepAfter(typeof(SweepStep), new AddBypassNGenStep()); } if (assemblies != I18nAssemblies.None) { p.AddStepAfter(typeof(PreserveDependencyLookupStep), new PreserveCalendarsStep(assemblies)); } if (removeCAS) { p.AddStepBefore(typeof(MarkStep), new RemoveSecurityStep()); } if (excluded_features.Count > 0) { p.AddStepBefore(typeof(MarkStep), new RemoveFeaturesStep() { FeatureCOM = excluded_features.Contains("com"), FeatureETW = excluded_features.Contains("etw"), FeatureSRE = excluded_features.Contains("sre"), FeatureGlobalization = excluded_features.Contains("globalization") }); var excluded = new string [excluded_features.Count]; excluded_features.CopyTo(excluded); context.ExcludedFeatures = excluded; } if (disabled_optimizations.Count > 0) { foreach (var item in disabled_optimizations) { switch (item) { case "beforefieldinit": context.DisabledOptimizations |= CodeOptimizations.BeforeFieldInit; break; case "overrideremoval": context.DisabledOptimizations |= CodeOptimizations.OverrideRemoval; break; case "unreachablebodies": context.DisabledOptimizations |= CodeOptimizations.UnreachableBodies; break; case "unusedinterfaces": context.DisabledOptimizations |= CodeOptimizations.UnusedInterfaces; break; } } } if (enabled_optimizations.Count > 0) { foreach (var item in enabled_optimizations) { switch (item) { case "unreachablebodies": context.DisabledOptimizations &= ~CodeOptimizations.UnreachableBodies; break; case "clearinitlocals": context.DisabledOptimizations &= ~CodeOptimizations.ClearInitLocals; break; } } } if (context.IsOptimizationEnabled(CodeOptimizations.ClearInitLocals)) { p.AddStepBefore(typeof(OutputStep), new ClearInitLocalsStep()); } PreProcessPipeline(p); try { p.Process(context); } finally { if (dumpDependencies) { context.Tracer.Finish(); } } } }
private void SearchReturn(Xapian.MSet xm, SearchInfo Searchwords, out AnsInfo ai) { ai = new AnsInfo(); List <SearchResult> XapResList = new List <SearchResult>(); string query = Searchwords.SearchString; query = query.Replace("\\", ""); query = query.Replace("/", ""); int page = Searchwords.page; var segmenter = new JiebaSegmenter(); var segments = segmenter.Cut(query); string querystr = string.Join(" ", segments); //分词 //若返回不为空 if (xm != null) { ai.totalnum = xm.Size(); //结果数目 int pagecount = 0; for (Xapian.MSetIterator iter = xm.Begin(); iter != xm.End(); ++iter) { SearchResult sr = new SearchResult(); ++pagecount; if (pagecount <= ((page - 1) * 10)) //获得分页 { continue; } else { if (XapResList.Count >= 10) //每页10个结果 { break; } Xapian.Document iterdoc = iter.GetDocument(); bool ftpflag = false; //ftp标记,转码用 bool emflag = false; string strcontent = iterdoc.GetData(); //取出正文 string strtitle = iterdoc.GetValue(3); //取出标题 ValueTitle string strahref = iterdoc.GetValue(1); //取出链接 string source = iterdoc.GetValue(0); string strcut = ""; int contentlen = strcontent.Length; //判断正文长度,为下面筛选含有关键词片段做准备 uint docid = iter.GetDocId(); if (source == "4") { sr.allcontent = strcontent; } if (source == "2") { ftpflag = true; strahref = UrlEncode(strahref); //若为ftp链接,需要转码 } string[] strquerycut = querystr.Split(' '); string emlink = ""; List <string> tmp = new List <string>(); foreach (var item in strquerycut) { if (item == "e" || item == "E" || item == "m" || item == "M" || item == "em" || item == "Em" || item == "Em" || item == "EM" || item == "<" || item == ">") { emflag = true; if (emlink != "") { emlink = emlink + "|" + item; } else { emlink = item; } } else { tmp.Add(item); } } HashSet <string> hs = new HashSet <string>(tmp); //此时已经去掉重复的数据保存在hashset中 String[] strunique = new String[hs.Count]; hs.CopyTo(strunique); int cutlen = strunique.Length; int count = 0; if (emlink != "" && cutlen == 0) { foreach (var item in strquerycut) { //消掉*问号空格 if (item == " " || item == "") { continue; } CompareInfo Compare = CultureInfo.InvariantCulture.CompareInfo; int conpos = Compare.IndexOf(strcontent, item, CompareOptions.IgnoreCase); //根据位置标红 //int conpos = strcontent.IndexOf(item); //根据位置标红 if (conpos != -1) { if (contentlen - conpos > 150 && conpos > 50) { //截取150字作为cache strcut = strcontent.Substring(conpos - 50, 200); if (emflag) { strtitle = ReplaceCntent(emlink, strtitle); strcut = ReplaceCntent(emlink, strcut); } strcut = "..." + strcut + "..."; goto Finally; } else if (conpos > 50) { ////截取150字作为cache strcut = strcontent.Substring(conpos - 50, contentlen - conpos + 50); if (emflag) { strtitle = ReplaceCntent(emlink, strtitle); strcut = ReplaceCntent(emlink, strcut); } strcut = "..." + strcut + "..."; goto Finally; } else if (contentlen - conpos > 150) { //截取150字作为cache strcut = strcontent.Substring(0, conpos + 150); if (emflag) { strtitle = ReplaceCntent(emlink, strtitle); strcut = ReplaceCntent(emlink, strcut); } strcut = "..." + strcut + "..."; goto Finally; } else { //strcut = HttpUtility.HtmlEncode(strcut); //不够150的全拿出 strcut = strcontent; if (emflag) { strtitle = ReplaceCntent(emlink, strtitle); strcut = ReplaceCntent(emlink, strcut); } strcut = "..." + strcut + "..."; goto Finally; } } else { CompareInfo Comparetitle = CultureInfo.InvariantCulture.CompareInfo; int conpostitle = Comparetitle.IndexOf(strtitle, item, CompareOptions.IgnoreCase); //根据位置标红 if (conpostitle != -1) { if (contentlen > 200) { strcut = strcontent.Substring(0, 200); if (emflag) { strtitle = ReplaceCntent(emlink, strtitle); strcut = ReplaceCntent(emlink, strcut); } strcut = "..." + strcut + "..."; goto Finally; } else { strcut = strcontent; if (emflag) { strtitle = ReplaceCntent(emlink, strtitle); strcut = ReplaceCntent(emlink, strcut); } strcut = "..." + strcut + "..."; goto Finally; } } else { ++count; } } } } else { //每一个词都查一遍 foreach (var item in strunique) { //消掉*问号空格 if (item == " " || item == "") { continue; } CompareInfo Compare = CultureInfo.InvariantCulture.CompareInfo; int conpos = Compare.IndexOf(strcontent, item, CompareOptions.IgnoreCase); //根据位置标红 //int conpos = strcontent.IndexOf(item); //根据位置标红 if (conpos != -1) { if (contentlen - conpos > 150 && conpos > 50) { //截取150字作为cache strcut = strcontent.Substring(conpos - 50, 200); if (emflag) { strtitle = ReplaceCntent(emlink, strtitle); strcut = ReplaceCntent(emlink, strcut); } //strcut = HttpUtility.HtmlEncode(strcut); for (; count < cutlen; count++) { if (strunique[count] == " " || strunique[count] == "") { continue; } //标红,大小写不敏感,regex替换法,replace大小写敏感 strtitle = Regex.Replace(strtitle, Regex.Escape(strunique[count]), "<em>" + strunique[count] + "</em>", RegexOptions.IgnoreCase); //strtitle = strtitle.Replace(strquerycut[count], "<font color = red>" + strquerycut[count] + "</font>"); //strcut = strcut.Replace(strquerycut[count], "<font color = red>" + strquerycut[count] + "</font>"); strcut = Regex.Replace(strcut, Regex.Escape(strunique[count]), "<em>" + strunique[count] + "</em>", RegexOptions.IgnoreCase); } strcut = "..." + strcut + "..."; goto Finally; } else if (conpos > 50) { ////截取150字作为cache strcut = strcontent.Substring(conpos - 50, contentlen - conpos + 50); if (emflag) { strtitle = ReplaceCntent(emlink, strtitle); strcut = ReplaceCntent(emlink, strcut); } //strcut = HttpUtility.HtmlEncode(strcut); for (; count < cutlen; count++) { if (strunique[count] == " " || strunique[count] == "") { continue; } //标红 strtitle = Regex.Replace(strtitle, Regex.Escape(strunique[count]), "<em>" + strunique[count] + "</em>", RegexOptions.IgnoreCase); //strtitle = strtitle.Replace(strquerycut[count], "<font color = red>" + strquerycut[count] + "</font>"); //strcut = strcut.Replace(strquerycut[count], "<font color = red>" + strquerycut[count] + "</font>"); strcut = Regex.Replace(strcut, Regex.Escape(strunique[count]), "<em>" + strunique[count] + "</em>", RegexOptions.IgnoreCase); } strcut = "..." + strcut + "..."; goto Finally; } else if (contentlen - conpos > 150) { //截取150字作为cache strcut = strcontent.Substring(0, conpos + 150); if (emflag) { strtitle = ReplaceCntent(emlink, strtitle); strcut = ReplaceCntent(emlink, strcut); } //strcut = HttpUtility.HtmlEncode(strcut); for (; count < cutlen; count++) { if (strunique[count] == " " || strunique[count] == "") { continue; } //标红 strtitle = Regex.Replace(strtitle, Regex.Escape(strunique[count]), "<em>" + strunique[count] + "</em>", RegexOptions.IgnoreCase); //strtitle = strtitle.Replace(strquerycut[count], "<font color = red>" + strquerycut[count] + "</font>"); //strcut = strcut.Replace(strquerycut[count], "<font color = red>" + strquerycut[count] + "</font>"); strcut = Regex.Replace(strcut, Regex.Escape(strunique[count]), "<em>" + strunique[count] + "</em>", RegexOptions.IgnoreCase); } strcut = "..." + strcut + "..."; goto Finally; } else { //strcut = HttpUtility.HtmlEncode(strcut); //不够150的全拿出 strcut = strcontent; if (emflag) { strtitle = ReplaceCntent(emlink, strtitle); strcut = ReplaceCntent(emlink, strcut); } for (; count < cutlen; count++) { if (strunique[count] == " " || strunique[count] == "") { continue; } //标红 strtitle = Regex.Replace(strtitle, Regex.Escape(strunique[count]), "<em>" + strunique[count] + "</em>", RegexOptions.IgnoreCase); //strtitle = strtitle.Replace(strquerycut[count], "<font color = red>" + strquerycut[count] + "</font>"); //strcut = strcut.Replace(strquerycut[count], "<font color = red>" + strquerycut[count] + "</font>"); strcut = Regex.Replace(strcut, Regex.Escape(strunique[count]), "<em>" + strunique[count] + "</em>", RegexOptions.IgnoreCase); } strcut = "..." + strcut + "..."; goto Finally; } } else { CompareInfo Comparetitle = CultureInfo.InvariantCulture.CompareInfo; int conpostitle = Comparetitle.IndexOf(strtitle, item, CompareOptions.IgnoreCase); //根据位置标红 if (conpostitle != -1) { if (contentlen > 200) { strcut = strcontent.Substring(0, 200); if (emflag) { strtitle = ReplaceCntent(emlink, strtitle); strcut = ReplaceCntent(emlink, strcut); } //strcut = HttpUtility.HtmlEncode(strcut); for (; count < cutlen; count++) { if (strunique[count] == " " || strunique[count] == "") { continue; } //标红 strtitle = Regex.Replace(strtitle, Regex.Escape(strunique[count]), "<em>" + strunique[count] + "</em>", RegexOptions.IgnoreCase); //strtitle = strtitle.Replace(strquerycut[count], "<font color = red>" + strquerycut[count] + "</font>"); //strcut = strcut.Replace(strquerycut[count], "<font color = red>" + strquerycut[count] + "</font>"); strcut = Regex.Replace(strcut, Regex.Escape(strunique[count]), "<em>" + strunique[count] + "</em>", RegexOptions.IgnoreCase); } strcut = "..." + strcut + "..."; goto Finally; } else { strcut = strcontent; if (emflag) { strtitle = ReplaceCntent(emlink, strtitle); strcut = ReplaceCntent(emlink, strcut); } //strcut = HttpUtility.HtmlEncode(strcut); for (; count < cutlen; count++) { if (strunique[count] == " " || strunique[count] == "") { continue; } //标红 strtitle = Regex.Replace(strtitle, Regex.Escape(strunique[count]), "<em>" + strunique[count] + "</em>", RegexOptions.IgnoreCase); //strtitle = strtitle.Replace(strquerycut[count], "<font color = red>" + strquerycut[count] + "</font>"); //strcut = strcut.Replace(strquerycut[count], "<font color = red>" + strquerycut[count] + "</font>"); strcut = Regex.Replace(strcut, Regex.Escape(strunique[count]), "<em>" + strunique[count] + "</em>", RegexOptions.IgnoreCase); } strcut = "..." + strcut + "..."; goto Finally; } } else { ++count; } } } } //找到合适的内容之后返回结果 Finally: sr.ahref = iterdoc.GetValue(1); if (ftpflag) //判断是否需要转码链接 { sr.ahrefencode = strahref; //ftp则使用转码链接 } else { sr.ahrefencode = sr.ahref; } sr.link = iterdoc.GetValue(2); sr.title = strtitle; sr.snippet = strcut; XapResList.Add(sr); } } ai.retinfo = XapResList; } else { ai.totalnum = 0; ai.retinfo = null; } }
public void CopyTo(T[] array, int arrayIndex) => innerCollection.CopyTo(array, arrayIndex);
public void CopyTo(string[] array, int arrayIndex) { _hashset.CopyTo(array, arrayIndex); }
/** * Returns an array of all the pillars in the manager. */ protected RotatingPillar[] GetPillars() { RotatingPillar[] result = new RotatingPillar[rotatingPillars.Count]; rotatingPillars.CopyTo(result); return(result); }
/// <summary> /// Copies the elements of the hash set to an array, starting at the specified array index. /// </summary> /// <param name="array"> /// The one-dimensional array that is the destination of the elements copied from /// the hash set. The array must have zero-based indexing. /// </param> /// <param name="arrayIndex"> The zero-based index in array at which copying begins. </param> public virtual void CopyTo(T[] array, int arrayIndex) => _set.CopyTo(array, arrayIndex);
/// <inheritdoc cref="ICollection{T}" /> public void CopyTo(TJsonPathExpression[] array, int arrayIndex) { _hashSet.CopyTo(array, arrayIndex); }
public void CopyTo(T[] array, int arrayIndex) { mHashSet.CopyTo(array, arrayIndex); }
public void CopyTo(ICanvasItem[] array, int arrayIndex) => myCollection.CopyTo(array, arrayIndex);
public void CopyTo(T[] array, int arrayIndex) { _set.CopyTo(array, arrayIndex); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add Cors services.AddCors(o => o.AddPolicy(MyAllowSpecificOrigins, builder => { string[] hosts = { "localhost", "127.0.0.1", "www.sergego.com" }; string[] protocols = { "http", "https", Configuration["WSProtocol"] }; var urls = new List <string>(); foreach (var host in hosts) { foreach (var protocol in protocols) { urls.Add(protocol + "://" + host); urls.Add(protocol + "://" + host + ":" + Configuration["WebPort"]); urls.Add(protocol + "://" + host + ":" + Configuration["MessagingPort"]); } } urls.Add(Configuration["DebugClientURL"]); #if DEBUG urls.Add("http://localhost:4200"); #endif urls.Add(Configuration["ExternalClientURL"]); var withoutDuplicates = new HashSet <string>(); foreach (var url in urls) { withoutDuplicates.Add(url); } var array = new string[withoutDuplicates.Count]; withoutDuplicates.CopyTo(array); builder.WithOrigins(array) /* builder.WithOrigins("http://localhost:" + Configuration["WebPort"], * "http://www.sergego.com:" + Configuration["WebPort"], * Configuration["DebugClientURL"], * Configuration["ExternalClientURL"], * "http://localhost:2020", * "http://localhost:4200", * "wss://localhost:" + Configuration["MessagingPort"], * "wss://www.sergego.com:" + Configuration["MessagingPort"], * "http://www.sergego.com", "http://www.sergego.com/fincore") */ // builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials(); })); var jwtSettings = JwtSettings.FromConfiguration(Configuration); services.AddSingleton(jwtSettings); services.AddHttpContextAccessor(); services.Configure <CookiePolicyOptions>(options => { options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddAutoMapper(GetType().Assembly); services.AddAuthorization(options => { options.AddPolicy("Bearer", new AuthorizationPolicyBuilder() .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme) .RequireAuthenticatedUser().Build()); options.AddPolicy("admin", policy => policy.RequireClaim("can_delete", "true")); options.AddPolicy("user", policy => policy.RequireClaim("can_view", "true")); }); services .AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => options.TokenValidationParameters = jwtSettings.TokenValidationParameters); services.AddControllersWithViews().AddNewtonsoftJson(options => { // Return JSON responses in LowerCase? options.SerializerSettings.ContractResolver = new DefaultContractResolver(); // Resolve Looping navigation properties options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; }); var angularFolder = AngularPath(Configuration["AngularDir"]); // In production, the Angular files will be served from this directory services.AddSpaStaticFiles(configuration => { configuration.RootPath = angularFolder; }); services.AddHostedService <MessagingBackgroundService>(); services.AddSingleton <IMessagingService, MessagingService>(); }
public void CopyTo(Header[] array, int arrayIndex) => _headers.CopyTo(array, arrayIndex);
/// <summary> /// Copies items to the specified array. /// </summary> /// <param name="array">The array.</param> /// <param name="arrayIndex">Index of the array.</param> public void CopyTo(AssetItem[] array, int arrayIndex) { registeredItems.CopyTo(array, arrayIndex); }
void ICollection <string> .CopyTo(string[] array, int arrayIndex) => _set.CopyTo(array, arrayIndex);
/// <summary> /// This function is called by ZSCore after each input update. /// </summary> private void OnCoreUpdated(ZSCore sender) { if (sender != _zsCore) { return; } //Update stylus button states. for (int i = 0; i < numButtons; ++i) { _wasStylusButtonPressed [i] = _isStylusButtonPressed [i]; _wasMouseButtonPressed [i] = _isMouseButtonPressed [i]; //Have to combine mouse state down here so asynchronous clients see it at the right time. _isStylusButtonPressed [i] = !_zsCore.IsMouseEmulationEnabled() && _zsCore.IsTrackerTargetButtonPressed(ZSCore.TrackerTargetType.Primary, i); _isMouseButtonPressed [i] = Input.GetMouseButton(i); } bool useMousePointer = false; if (_useTracking && !_zsCore.IsMouseEmulationEnabled()) { Matrix4x4 pose = _zsCore.GetTrackerTargetWorldPose(_targetType); if (pose != _previousStylusPose) { _timeSinceStylusMoved = 0f; } else { _timeSinceStylusMoved += Time.deltaTime; } useMousePointer = _timeSinceStylusMoved > StylusTimeout; if (!useMousePointer) { _previousStylusPose = pose; transform.localScale = ZSStylusSelector.GetScale(pose); transform.rotation = ZSStylusSelector.GetRotation(pose); transform.position = ZSStylusSelector.GetPosition(pose); transform.localScale = _zsCore.GetViewerScale() * Vector3.one; } } //Simulate the stylus based on mouse input. Vector3 dMousePosition = Input.mousePosition - _lastMousePosition; dMousePosition [2] = WheelSensitivity * Input.GetAxis("Mouse ScrollWheel"); if (Input.GetKey(KeyCode.LeftBracket)) { dMousePosition [2] -= WheelSensitivity * Time.deltaTime; } if (Input.GetKey(KeyCode.RightBracket)) { dMousePosition [2] += WheelSensitivity * Time.deltaTime; } Camera mainCamera = (_zsCore.IsStereoEnabled()) ? _centerCamera : _zsCore.CurrentCamera.camera; if (useMousePointer && mainCamera != null && mainCamera.enabled) { if (stylusSimulatorMode == StylusSimulatorMode.Projection || stylusSimulatorMode == StylusSimulatorMode.Position) { //Only update the wheel total if we aren't rotating. Avoids extra Z translation artifact. _mouseWheel += dMousePosition [2]; Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition); Vector3 rayPoint = ray.GetPoint(0.1f + 0.5f * _mouseWheel * mainCamera.transform.localScale.magnitude); transform.position = rayPoint; if (stylusSimulatorMode == StylusSimulatorMode.Projection) { transform.rotation = Quaternion.LookRotation(ray.GetPoint(1.0f) - mainCamera.transform.position, mainCamera.transform.up); } } else if (stylusSimulatorMode == StylusSimulatorMode.Rotation) { Vector3 euler = transform.localRotation.eulerAngles; euler += new Vector3(-0.1f * dMousePosition.y, 0.1f * dMousePosition.x, -1000.0f * dMousePosition.z); var oldHoverPoint = transform.TransformPoint(_localHoverPoint); transform.localRotation = Quaternion.Euler(euler); transform.localPosition += oldHoverPoint - transform.TransformPoint(_localHoverPoint); } } //Make the hovered object the closest one to the tip. if (_useCollision) { _hoverQueue.update(); RaycastHit hit = _hoverQueue.getFirst(); if (hit.collider != null) { HoverPoint = hit.point; HoverObject = (hit.collider.gameObject.layer == uiLayer) ? hit.collider.gameObject : objectResolver(hit.collider.gameObject); } else { ZSLinearShape linearStylus = activeStylus as ZSLinearShape; if (linearStylus != null && linearStylus._tip != null && linearStylus._tip.activeSelf) { HoverPoint = linearStylus._tip.transform.position; } else { HoverPoint = activeStylus.hotSpot; } HoverObject = null; } } else { HoverPoint = transform.TransformPoint(_localHoverPoint); } if (_HoverObject != null) { activeStylus.OnHoverStay(_HoverObject, HoverPoint); } //Update the set of selected objects based on clicking. if (GetButtonDown(SelectButton)) { if (!Input.GetKey(KeyCode.LeftControl)) { selectedObjects.Clear(); } if (_HoverObject != null) { if (_HoverObject.layer == uiLayer) { _wasHoveredObjectSelected = false; } else { _wasHoveredObjectSelected = selectedObjects.Contains(_HoverObject); if (!selectedObjects.Contains(_HoverObject)) { selectedObjects.Add(_HoverObject); } } } _buttonDownPosition = transform.position; } if (GetButtonUp(SelectButton)) { bool wasDrag = (transform.position - _buttonDownPosition).magnitude > minDragDistance; if (_HoverObject != null && _wasHoveredObjectSelected && !wasDrag && Input.GetKey(KeyCode.LeftControl)) { selectedObjects.Remove(_HoverObject); } } // Send messages to objects whose selection state changed. foreach (GameObject selectedObject in _oldSelectedObjects) { if (selectedObject != null && !selectedObjects.Contains(selectedObject)) { activeStylus.OnDeselected(selectedObject); selectedObject.SendMessage("OnDeselected", SendMessageOptions.DontRequireReceiver); } } GameObject[] tmpSelectedObjects = new GameObject[selectedObjects.Count]; selectedObjects.CopyTo(tmpSelectedObjects); // So objects can de-select themselves. foreach (GameObject selectedObject in tmpSelectedObjects) { if (selectedObject != null && !_oldSelectedObjects.Contains(selectedObject)) { selectedObject.SendMessage("OnSelected", SendMessageOptions.DontRequireReceiver); activeStylus.OnSelected(selectedObject, HoverPoint); } } _oldSelectedObjects.Clear(); foreach (GameObject selectedObject in selectedObjects) { if (selectedObject != null) { _oldSelectedObjects.Add(selectedObject); } } _lastMousePosition = Input.mousePosition; activeStylus.Tool.OnStylus(); }
/// <summary> /// Copies the elements of the hash set to an array. /// </summary> /// <param name="array">The one-dimensional array that is the destination of the elements copied from /// the hash set. The array must have zero-based indexing.</param> public virtual void CopyTo(T[] array) => _set.CopyTo(array);
/// <summary>扩展引用程序集,拆分目录</summary> /// <param name="afs"></param> /// <returns></returns> static String[] ExpendAssembly(String[] afs) { var list = new HashSet <String>(StringComparer.OrdinalIgnoreCase); foreach (var item in afs) { if (item.IsNullOrWhiteSpace()) { continue; } if (list.Contains(item)) { continue; } var fi = item.GetFullPath(); if (File.Exists(fi)) { //list.Add(fi); var asm = Assembly.LoadFile(fi); list.Add(asm.Location); } else if (item.EndsWithIgnoreCase(".dll")) { // 尝试从GAC加载 var file = Path.GetDirectoryName(typeof(Object).Assembly.CodeBase).CombinePath(item); if (File.Exists(file)) { list.Add(file); } } // 有可能是目录,目录要遍历文件 else if (item.EndsWith("/") || item.EndsWith("\\") || Directory.Exists(item)) { var fs = Directory.GetFiles(item, "*.dll", SearchOption.TopDirectoryOnly); if (fs.Length > 0) { foreach (var elm in fs) { if (!list.Contains(elm)) { list.Add(elm); } } } } // 加载系统程序集 else { //list.Add(item); try { #pragma warning disable CS0618 // 类型或成员已过时 var asm = Assembly.LoadWithPartialName(item); #pragma warning restore CS0618 // 类型或成员已过时 //Console.WriteLine(asm); list.Add(asm.Location); } catch (Exception ex) { XTrace.WriteException(ex); } } } var arr = new String[list.Count]; list.CopyTo(arr, 0); return(arr); }
/// <summary> /// Loads necesarry resouces for rendering /// </summary> /// <returns>true loading succeeded</returns> static bool LoadResources() { if (!String.IsNullOrWhiteSpace(Options.SystemFont)) { if (!SystemFonts.TryFind(Options.SystemFont, out var family)) { Log.Error("font '" + Options.SystemFont + " not found"); return(false); } SelectedFont = new Font(family, Options.FontSize, Options.StyleOfFont); //Log.Debug("FontInfo: " // +"\n\tAscender\t"+SelectedFont.Ascender // +"\n\tBold\t"+SelectedFont.Bold // +"\n\tDescender\t"+SelectedFont.Descender // +"\n\tEmSize\t"+SelectedFont.EmSize // +"\n\tFamily.Name\t"+SelectedFont.Family.Name // +"\n\tItalic\t"+SelectedFont.Italic // +"\n\tLineGap\t"+SelectedFont.LineGap // +"\n\tLineHeight\t"+SelectedFont.LineHeight // +"\n\tName\t"+SelectedFont.Name // +"\n\tSize\t"+SelectedFont.Size //); } else if (!String.IsNullOrWhiteSpace(Options.FontFile)) { if (!File.Exists(Options.FontFile)) { Log.Error("Cannot find font file '" + Options.FontFile + "'"); return(false); } var col = new FontCollection().Install(Options.FontFile); SelectedFont = col.CreateFont(Options.FontSize, Options.StyleOfFont); } else { Log.Error("no font specified"); return(false); } //Log.Debug("Options.WhichSet = "+Options.WhichSet); if (Options.WhichSet != CharSets.Set.None) { SelectedCharSet = CharSets.Get(Options.WhichSet); } else if (!String.IsNullOrWhiteSpace(Options.CharFile)) { if (!File.Exists(Options.CharFile)) { Log.Error("cannot find file " + Options.CharFile); return(false); } var uniqChars = new HashSet <char>(); const int buffLen = 256; using (var fs = File.Open(Options.CharFile, FileMode.Open, FileAccess.Read, FileShare.Read)) using (var sr = new StreamReader(fs)) { char[] buff = new char[buffLen]; int count = int.MaxValue; while (count >= buffLen) { count = sr.Read(buff, 0, buffLen); uniqChars.UnionWith(buff); } } SelectedCharSet = new char[uniqChars.Count]; uniqChars.CopyTo(SelectedCharSet); } else { Log.Error("char set not specified"); return(false); } if (!String.IsNullOrWhiteSpace(Options.InputName)) { if (!File.Exists(Options.InputName)) { Log.Error("cannot find file " + Options.InputName); return(false); } var data = File.ReadAllBytes(Options.InputName); SourceImage = Image.Load(data); } return(true); }
/// <summary> /// 初始化架构信息 /// </summary> /// <param name="type"></param> /// <param name="schema"></param> public static void InitSchema(Type type, SchemaTable schema) { if (type == null) { throw new ArgumentNullException("type"); } //modify if exits then update. //if (Exits(type)) //{ // return; //} if (type.IsSubclassOf(typeof(LogEntity))) { schema.IsLog = true; _logTables.Enqueue(type.FullName); } //加载成员属性 HashSet <string> keySet = new HashSet <string>(); PropertyInfo[] propertyList = type.GetProperties(BindingFlags.Instance | BindingFlags.Public); SchemaColumn column; int number = 0; foreach (PropertyInfo property in propertyList) { number++; if (!Equals(property.DeclaringType, property.ReflectedType)) { continue; } column = new SchemaColumn(); var entityField = FindAttribute <EntityFieldAttribute>(property.GetCustomAttributes(false)); if (entityField != null) { column.Id = number; column.Name = string.IsNullOrEmpty(entityField.FieldName) ? property.Name : entityField.FieldName; column.IsIdentity = entityField.IsIdentity; column.IsKey = entityField.IsKey; column.ColumnLength = entityField.ColumnLength; column.ColumnScale = entityField.ColumnScale; column.Isnullable = entityField.Isnullable; column.FieldModel = entityField.FieldModel; column.Disable = entityField.Disable; column.MinRange = entityField.MinRange; column.MaxRange = entityField.MaxRange; column.IsJson = entityField.IsJsonSerialize; column.JsonDateTimeFormat = entityField.JsonDateTimeFormat; column.ColumnType = property.PropertyType; column.DbType = entityField.DbType; column.CanRead = property.CanRead; column.CanWrite = property.CanWrite; AddChildType(column); } else { //必须要加EntityField标识 continue; //column.Id = number; //column.Name = property.Name; //column.IsIdentity = false; //column.IsKey = string.Compare(property.Name, "id", true) == 0; //column.FieldModel = FieldModel.All; //column.ColumnType = property.PropertyType; //column.DbType = ColumnDbType.Varchar; } schema.Columns.TryAdd(column.Name, column); if (column.IsKey) { keySet.Add(column.Name); } } schema.Keys = new string[keySet.Count]; keySet.CopyTo(schema.Keys, 0); CheckTableSchema(schema); AddSchema(type, schema); }
/// <summary> /// 初始化架构信息 /// </summary> /// <param name="type"></param> /// <param name="schema"></param> public static void InitSchema(Type type, SchemaTable schema) { var section = GetEntitySection(); if (type == null) { throw new ArgumentNullException("type"); } if (type.IsSubclassOf(typeof(LogEntity)) && string.IsNullOrEmpty(schema.NameFormat)) { schema.NameFormat = section.LogTableNameFormat; } if (!string.IsNullOrEmpty(schema.NameFormat) && !Exits(type)) { _dynamicTables.Enqueue(schema); } //加载成员属性 HashSet <string> keySet = new HashSet <string>(); PropertyInfo[] propertyList = type.GetProperties(BindingFlags.Instance | BindingFlags.Public); SchemaColumn column; int number = 0; foreach (PropertyInfo property in propertyList) { number++; //Ignore parent property bool isExtend = property.GetCustomAttributes <EntityFieldExtendAttribute>(false).Count() > 0; if (!isExtend && property.DeclaringType != property.ReflectedType) { continue; } column = new SchemaColumn(); var entityField = FindAttribute <EntityFieldAttribute>(property.GetCustomAttributes(false)); if (entityField != null) { column.Id = number; column.Name = string.IsNullOrEmpty(entityField.FieldName) ? property.Name : entityField.FieldName; column.IsIdentity = entityField.IsIdentity; column.IdentityNo = entityField.IdentityNo; column.IsKey = entityField.IsKey; column.ColumnLength = entityField.ColumnLength; column.ColumnScale = entityField.ColumnScale; column.Isnullable = entityField.Isnullable; column.FieldModel = entityField.FieldModel; column.Disable = entityField.Disable; column.MinRange = entityField.MinRange; column.MaxRange = entityField.MaxRange; column.IsSerialized = entityField.IsJsonSerialize; column.JsonDateTimeFormat = entityField.JsonDateTimeFormat; column.ColumnType = property.PropertyType; column.DbType = entityField.DbType; column.CanRead = property.CanRead; column.CanWrite = property.CanWrite; AddChildType(column); } else { //必须要加EntityField标识 continue; //column.Id = number; //column.Name = property.Name; //column.IsIdentity = false; //column.IsKey = string.Compare(property.Name, "id", true) == 0; //column.FieldModel = FieldModel.All; //column.ColumnType = property.PropertyType; //column.DbType = ColumnDbType.Varchar; } schema.Columns.TryAdd(column.Name, column); if (column.IsKey) { keySet.Add(column.Name); } } //add modify time field if (section.EnableModifyTimeField && schema.AccessLevel == AccessLevel.ReadWrite) { column = new SchemaColumn(); column.Id = number; column.Name = "TempTimeModify"; column.Isnullable = true; column.FieldModel = FieldModel.All; column.ColumnType = typeof(DateTime); column.DbType = ColumnDbType.DateTime; column.JsonDateTimeFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss"; schema.Columns.TryAdd(column.Name, column); } schema.Keys = new string[keySet.Count]; keySet.CopyTo(schema.Keys, 0); CheckTableSchema(schema); AddSchema(type, schema); }
public static void Initialize() { Dictionary <string, AdjacencyList> towContents = new Dictionary <string, AdjacencyList>(); towContents.Add("TowStart1", new AdjacencyList("TowStart1", new string[] { "TowStart2", "TowEasy1" })); towContents.Add("TowStart2", new AdjacencyList("TowStart2", new string[] { "TowStart1", "TowEasy2" })); towContents.Add("TowEasy1", new AdjacencyList("TowEasy1", new string[] { "TowStart1", "TowEasy3" })); towContents.Add("TowEasy2", new AdjacencyList("TowEasy2", new string[] { "TowStart2", "TowEasy4" })); towContents.Add("TowEasy3", new AdjacencyList("TowEasy3", new string[] { "TowEasy1", "TowMed1", "TowEasy4" })); towContents.Add("TowEasy4", new AdjacencyList("TowEasy4", new string[] { "TowEasy2", "TowMed2", "TowEasy3" })); towContents.Add("TowMed1", new AdjacencyList("TowMed1", new string[] { "TowEasy3", "TowMed3" })); towContents.Add("TowMed2", new AdjacencyList("TowMed2", new string[] { "TowEasy4", "TowMed4" })); towContents.Add("TowMed3", new AdjacencyList("TowMed3", new string[] { "TowMed1", "TowMed5" })); towContents.Add("TowMed4", new AdjacencyList("TowMed4", new string[] { "TowMed2", "TowMed6" })); towContents.Add("TowMed5", new AdjacencyList("TowMed5", new string[] { "TowMed3", "TowDiff1", "TowMed6" })); towContents.Add("TowMed6", new AdjacencyList("TowMed6", new string[] { "TowMed4", "TowDiff2", "TowMed5" })); towContents.Add("TowDiff1", new AdjacencyList("TowDiff1", new string[] { "TowMed5", "TowBoss" })); towContents.Add("TowDiff2", new AdjacencyList("TowDiff2", new string[] { "TowMed6", "TowBoss" })); towContents.Add("TowBoss", new AdjacencyList("TowBoss", new string[] { "TowDiff1", "TowDiff2", "TowFinal" })); towContents.Add("TowFinal", new AdjacencyList("TowFinal", new string[] { "TowBoss" })); Dictionary <string, Event> towEvents = new Dictionary <string, Event>(); TowerGetter.Refresh(); towEvents.Add("TowStart1", TowerGetter.Easy()); towEvents.Add("TowStart2", TowerGetter.Easy()); towEvents.Add("TowEasy1", TowerGetter.Easy()); towEvents.Add("TowEasy2", TowerGetter.Easy()); towEvents.Add("TowEasy3", TowerGetter.Easy()); towEvents.Add("TowEasy4", TowerGetter.Easy()); towEvents.Add("TowMed1", TowerGetter.Medium()); towEvents.Add("TowMed2", TowerGetter.Medium()); towEvents.Add("TowMed3", TowerGetter.Medium()); towEvents.Add("TowMed4", TowerGetter.Medium()); towEvents.Add("TowMed5", TowerGetter.Medium()); towEvents.Add("TowMed6", TowerGetter.Medium()); towEvents.Add("TowDiff1", TowerGetter.Hard()); towEvents.Add("TowDiff2", TowerGetter.Hard()); towEvents.Add("TowBoss", new CentralAIEvent()); towEvents.Add("TowFinal", new Event("A desk with huge stacks of admission letters is before you. Someone is very inspired by this", new LinkedList <TimedMethod>(new TimedMethod[] { new TimedMethod(0, "CauseEvent", new object[] { new SelectMember("Who is inspired?", new TimedMethod[] { new TimedMethod(0, "StatChange", new object[] { "GainDexterity", 2 }), new TimedMethod(0, "StatChange", new object[] { "GainStrength", 2 }), new TimedMethod(0, "CauseEvent", new object[] { new TextEvent("Strength +2, Dex +2") }) }) }) }), null, null, null, "Wow!", null, null, null)); DungeonMap tower = new DungeonMap("TowStart1", towContents, towEvents); Dictionary <string, AdjacencyList> dinContents = new Dictionary <string, AdjacencyList>(); dinContents.Add("DinStart", new AdjacencyList("DinStart", new string[] { "DinEat1", "DinLine1" })); dinContents.Add("DinEat1", new AdjacencyList("DinEat1", new string[] { "DinStart", "DinLine1", "DinEat2", "DinEat3", "DinEat4" })); dinContents.Add("DinEat2", new AdjacencyList("DinEat2", new string[] { "DinEat1", "DinEat3", "DinEat4" })); dinContents.Add("DinEat3", new AdjacencyList("DinEat3", new string[] { "DinHall2", "DinLine2", "DinEat1", "DinEat2", "DinEat4" })); dinContents.Add("DinEat4", new AdjacencyList("DinEat4", new string[] { "DinHall2", "DinEat1", "DinEat2", "DinEat3" })); dinContents.Add("DinLine1", new AdjacencyList("DinLine1", new string[] { "DinStart", "DinEat1", "DinLine2" })); dinContents.Add("DinLine2", new AdjacencyList("DinLine2", new string[] { "DinLine1", "DinEat3", "DinHall1" })); dinContents.Add("DinHall1", new AdjacencyList("DinHall1", new string[] { "DinLine2", "DinKitchen1" })); dinContents.Add("DinHall2", new AdjacencyList("DinHall2", new string[] { "DinEat3", "DinEat4", "DinEat5" })); dinContents.Add("DinEat5", new AdjacencyList("DinEat5", new string[] { "DinHall2", "DinEat6", "DinCut" })); dinContents.Add("DinEat6", new AdjacencyList("DinEat6", new string[] { "DinEat5", "DinCut" })); dinContents.Add("DinKitchen1", new AdjacencyList("DinKitchen1", new string[] { "DinHall1", "DinKitchen2", "DinClean" })); dinContents.Add("DinKitchen2", new AdjacencyList("DinKitchen2", new string[] { "DinKitchen1", "DinClean" })); dinContents.Add("DinClean", new AdjacencyList("DinClean", new string[] { "DinKitchen1", "DinKitchen2", "DinDiff1", "DinDiff2" })); dinContents.Add("DinDiff1", new AdjacencyList("DinDiff1", new string[] { "DinClean", "DinBoss" })); dinContents.Add("DinDiff2", new AdjacencyList("DinDiff2", new string[] { "DinClean", "DinCut", "DinBoss" })); dinContents.Add("DinCut", new AdjacencyList("DinCut", new string[] { "DinEat5", "DinEat6", "DinDiff2" })); dinContents.Add("DinBoss", new AdjacencyList("DinBoss", new string[] { "DinDiff1", "DinDiff2", "DinFinal" })); dinContents.Add("DinFinal", new AdjacencyList("DinFinal", new string[] { "DinBoss" })); Dictionary <string, Event> dinEvents = new Dictionary <string, Event>(); DiningGetter.Refresh(); dinEvents.Add("DinStart", DiningGetter.Hall()); dinEvents.Add("DinEat1", DiningGetter.Eat()); dinEvents.Add("DinEat2", DiningGetter.Eat()); dinEvents.Add("DinEat3", DiningGetter.Eat()); dinEvents.Add("DinEat4", DiningGetter.Eat()); dinEvents.Add("DinLine1", DiningGetter.Line()); dinEvents.Add("DinLine2", DiningGetter.Line()); dinEvents.Add("DinHall1", DiningGetter.Hall()); dinEvents.Add("DinHall2", DiningGetter.Hall()); dinEvents.Add("DinEat5", DiningGetter.Eat()); dinEvents.Add("DinEat6", DiningGetter.Eat()); dinEvents.Add("DinKitchen1", DiningGetter.Kitchen()); dinEvents.Add("DinKitchen2", DiningGetter.Kitchen()); dinEvents.Add("DinClean", DiningGetter.Clean()); dinEvents.Add("DinDiff1", DiningGetter.Hard()); dinEvents.Add("DinDiff2", DiningGetter.Hard()); dinEvents.Add("DinCut", DiningGetter.Cut()); dinEvents.Add("DinBoss", new CultLeaderEvent()); dinEvents.Add("DinFinal", DiningGetter.Final()); DungeonMap dining = new DungeonMap("DinStart", dinContents, dinEvents); Dictionary <string, AdjacencyList> resContents = new Dictionary <string, AdjacencyList>(); resContents.Add("ResStart", new AdjacencyList("ResStart", new string[] { "ResHall1", "ResHall3" })); resContents.Add("ResHall1", new AdjacencyList("ResHall1", new string[] { "ResStart", "ResCut1" })); resContents.Add("ResCut1", new AdjacencyList("ResCut1", new string[] { "ResHall1", "ResHall2" })); resContents.Add("ResHall2", new AdjacencyList("ResHall2", new string[] { "ResCut1", "ResHall7", "ResLab1" })); resContents.Add("ResLab1", new AdjacencyList("ResLab1", new string[] { "ResHall2" })); resContents.Add("ResHall3", new AdjacencyList("ResHall3", new string[] { "ResStart", "ResHall4", "ResHall8" })); resContents.Add("ResHall4", new AdjacencyList("ResHall4", new string[] { "ResHall3", "ResHall5" })); resContents.Add("ResHall5", new AdjacencyList("ResHall5", new string[] { "ResHall4", "ResRew" })); resContents.Add("ResRew", new AdjacencyList("ResRew", new string[] { "ResHall5", "ResHall6" })); resContents.Add("ResHall6", new AdjacencyList("ResHall6", new string[] { "ResRew", "ResHall7" })); resContents.Add("ResHall7", new AdjacencyList("ResHall7", new string[] { "ResHall6", "ResHall2", "ResBoss", "ResLab2" })); resContents.Add("ResLab2", new AdjacencyList("ResLab2", new string[] { "ResHall7" })); resContents.Add("ResHall8", new AdjacencyList("ResHall8", new string[] { "ResHall3", "ResCut2" })); resContents.Add("ResCut2", new AdjacencyList("ResCut2", new string[] { "ResHall8", "ResHall9" })); resContents.Add("ResHall9", new AdjacencyList("ResHall9", new string[] { "ResCut2", "ResBoss" })); resContents.Add("ResBoss", new AdjacencyList("ResBoss", new string[] { "ResHall9", "ResHall7", "ResFinal" })); resContents.Add("ResFinal", new AdjacencyList("ResFinal", new string[] { "ResBoss" })); Dictionary <string, Event> resEvents = new Dictionary <string, Event>(); ResearchGetter.Refresh(); resEvents.Add("ResStart", ResearchGetter.Easy()); resEvents.Add("ResHall1", ResearchGetter.Easy()); resEvents.Add("ResCut1", ResearchGetter.Cut()); resEvents.Add("ResHall2", ResearchGetter.Medium()); resEvents.Add("ResLab1", ResearchGetter.Lab()); resEvents.Add("ResHall3", ResearchGetter.Easy()); resEvents.Add("ResHall4", ResearchGetter.Easy()); resEvents.Add("ResHall5", ResearchGetter.Medium()); resEvents.Add("ResRew", ResearchGetter.Reward()); resEvents.Add("ResHall6", ResearchGetter.Medium()); resEvents.Add("ResHall7", ResearchGetter.Hard()); resEvents.Add("ResLab2", ResearchGetter.Lab()); resEvents.Add("ResHall8", ResearchGetter.Easy()); resEvents.Add("ResCut2", ResearchGetter.Cut()); resEvents.Add("ResHall9", ResearchGetter.Hard()); resEvents.Add("ResBoss", new ExpirimentorEvent()); resEvents.Add("ResFinal", ResearchGetter.Final()); DungeonMap research = new DungeonMap("ResStart", resContents, resEvents); Dictionary <string, AdjacencyList> spoContents = new Dictionary <string, AdjacencyList>(); spoContents.Add("SpoStart", new AdjacencyList("SpoStart", new string[] { "SpoHall1", "SpoHall3" })); spoContents.Add("SpoHall1", new AdjacencyList("SpoHall1", new string[] { "SpoStart", "SpoHall2" })); spoContents.Add("SpoHall2", new AdjacencyList("SpoHall2", new string[] { "SpoHall1", "SpoRoom1" })); spoContents.Add("SpoRoom1", new AdjacencyList("SpoRoom1", new string[] { "SpoHall2", "SpoRoom2", "SpoStand1" })); spoContents.Add("SpoRoom2", new AdjacencyList("SpoRoom2", new string[] { "SpoRoom1", "SpoGate1" })); spoContents.Add("SpoGate1", new AdjacencyList("SpoGate1", new string[] { "SpoRoom2", "SpoField1" })); spoContents.Add("SpoField1", new AdjacencyList("SpoField1", new string[] { "SpoGate1", "SpoStand2", "SpoBoss" })); spoContents.Add("SpoStand1", new AdjacencyList("SpoStand1", new string[] { "SpoRoom1", "SpoStand2" })); spoContents.Add("SpoStand2", new AdjacencyList("SpoStand2", new string[] { "SpoStand1", "SpoStand4", "SpoField1" })); spoContents.Add("SpoHall3", new AdjacencyList("SpoHall3", new string[] { "SpoStart", "SpoHall4" })); spoContents.Add("SpoHall4", new AdjacencyList("SpoHall4", new string[] { "SpoHall3", "SpoRoom3" })); spoContents.Add("SpoRoom3", new AdjacencyList("SpoRoom3", new string[] { "SpoHall4", "SpoRoom4", "SpoStand3" })); spoContents.Add("SpoRoom4", new AdjacencyList("SpoRoom4", new string[] { "SpoRoom3", "SpoGate2" })); spoContents.Add("SpoGate2", new AdjacencyList("SpoGate2", new string[] { "SpoRoom4", "SpoField2" })); spoContents.Add("SpoField2", new AdjacencyList("SpoField2", new string[] { "SpoGate2", "SpoStand4", "SpoBoss" })); spoContents.Add("SpoStand3", new AdjacencyList("SpoStand3", new string[] { "SpoRoom3", "SpoStand4" })); spoContents.Add("SpoStand4", new AdjacencyList("SpoStand4", new string[] { "SpoStand3", "SpoStand2", "SpoField2" })); spoContents.Add("SpoBoss", new AdjacencyList("SpoBoss", new string[] { "SpoField1", "SpoField2", "SpoFinal" })); spoContents.Add("SpoFinal", new AdjacencyList("SpoFinal", new string[] { "SpoBoss" })); Dictionary <string, Event> spoEvents = new Dictionary <string, Event>(); SportsGetter.Refresh(); spoEvents.Add("SpoStart", SportsGetter.Hall()); spoEvents.Add("SpoHall1", SportsGetter.Hall()); spoEvents.Add("SpoHall2", SportsGetter.Hall()); spoEvents.Add("SpoRoom1", SportsGetter.Room()); spoEvents.Add("SpoRoom2", SportsGetter.Room()); spoEvents.Add("SpoGate1", SportsGetter.Gate()); spoEvents.Add("SpoField1", SportsGetter.Field()); spoEvents.Add("SpoStand1", SportsGetter.Stand()); spoEvents.Add("SpoStand2", SportsGetter.Stand()); spoEvents.Add("SpoHall3", SportsGetter.Hall()); spoEvents.Add("SpoHall4", SportsGetter.Hall()); spoEvents.Add("SpoRoom3", SportsGetter.Room()); spoEvents.Add("SpoRoom4", SportsGetter.Room()); spoEvents.Add("SpoGate2", SportsGetter.Gate()); spoEvents.Add("SpoField2", SportsGetter.Field()); spoEvents.Add("SpoStand3", SportsGetter.Stand()); spoEvents.Add("SpoStand4", SportsGetter.Stand()); spoEvents.Add("SpoBoss", new QuarterbackEvent()); spoEvents.Add("SpoFinal", SportsGetter.Final()); DungeonMap sports = new DungeonMap("SpoStart", spoContents, spoEvents); Dictionary <string, AdjacencyList> artContents = new Dictionary <string, AdjacencyList>(); artContents.Add("ArtStart1", new AdjacencyList("ArtStart1", new string[] { "ArtRoom1" })); artContents.Add("ArtStart2", new AdjacencyList("ArtStart2", new string[] { "ArtRoom2" })); artContents.Add("ArtRoom1", new AdjacencyList("ArtRoom1", new string[] { "ArtStart1", "ArtHall1", "ArtHall3" })); artContents.Add("ArtRoom2", new AdjacencyList("ArtRoom2", new string[] { "ArtStart2", "ArtHall1", "ArtHall4" })); artContents.Add("ArtHall1", new AdjacencyList("ArtHall1", new string[] { "ArtRoom1", "ArtRoom2", "ArtHall2" })); artContents.Add("ArtHall2", new AdjacencyList("ArtHall2", new string[] { "ArtHall1", "ArtGallery1" })); artContents.Add("ArtHall3", new AdjacencyList("ArtHall3", new string[] { "ArtRoom1", "ArtStage1" })); artContents.Add("ArtHall4", new AdjacencyList("ArtHall4", new string[] { "ArtRoom2", "ArtStage2" })); artContents.Add("ArtGallery1", new AdjacencyList("ArtGallery1", new string[] { "ArtHall2", "ArtHall5" })); artContents.Add("ArtHall5", new AdjacencyList("ArtHall5", new string[] { "ArtGallery1", "ArtGallery2", "ArtGallery3" })); artContents.Add("ArtStage1", new AdjacencyList("ArtStage1", new string[] { "ArtHall3", "ArtStore1" })); artContents.Add("ArtStage2", new AdjacencyList("ArtStage2", new string[] { "ArtHall4", "ArtStore2" })); artContents.Add("ArtStore1", new AdjacencyList("ArtStore1", new string[] { "ArtStage1", "ArtGallery2" })); artContents.Add("ArtStore2", new AdjacencyList("ArtStore2", new string[] { "ArtStage2", "ArtGallery3" })); artContents.Add("ArtGallery2", new AdjacencyList("ArtGallery2", new string[] { "ArtStore1", "ArtHall5", "ArtRecep" })); artContents.Add("ArtGallery3", new AdjacencyList("ArtGallery3", new string[] { "ArtStore2", "ArtHall5", "ArtRecep" })); artContents.Add("ArtRecep", new AdjacencyList("ArtRecep", new string[] { "ArtGallery2", "ArtGallery3", "ArtBoss" })); artContents.Add("ArtBoss", new AdjacencyList("ArtBoss", new string[] { "ArtRecep", "ArtFinal" })); artContents.Add("ArtFinal", new AdjacencyList("ArtFinal", new string[] { "ArtBoss" })); Dictionary <string, Event> artEvents = new Dictionary <string, Event>(); ArtGetter.Refresh(); artEvents.Add("ArtStart1", ArtGetter.Hall()); artEvents.Add("ArtStart2", ArtGetter.Hall()); artEvents.Add("ArtRoom1", ArtGetter.Room()); artEvents.Add("ArtRoom2", ArtGetter.Room()); artEvents.Add("ArtHall1", ArtGetter.Hall()); artEvents.Add("ArtHall2", ArtGetter.Hall()); artEvents.Add("ArtHall3", ArtGetter.Hall()); artEvents.Add("ArtHall4", ArtGetter.Hall()); artEvents.Add("ArtGallery1", ArtGetter.Gallery()); artEvents.Add("ArtHall5", ArtGetter.Hall()); artEvents.Add("ArtStage1", ArtGetter.Stage()); artEvents.Add("ArtStage2", ArtGetter.Stage()); artEvents.Add("ArtStore1", ArtGetter.Store()); artEvents.Add("ArtStore2", ArtGetter.Store()); artEvents.Add("ArtGallery2", ArtGetter.Gallery()); artEvents.Add("ArtGallery3", ArtGetter.Gallery()); artEvents.Add("ArtRecep", ArtGetter.Recep()); artEvents.Add("ArtBoss", new SymphonyEvent()); artEvents.Add("ArtFinal", ArtGetter.Final()); DungeonMap art = new DungeonMap("ArtStart1", artContents, artEvents); Dictionary <string, AdjacencyList> helContents = new Dictionary <string, AdjacencyList>(); helContents.Add("HelStart", new AdjacencyList("HelStart", new string[] { "HelHall1" })); helContents.Add("HelRoom1", new AdjacencyList("HelRoom1", new string[] { "HelHall1" })); helContents.Add("HelRoom2", new AdjacencyList("HelRoom2", new string[] { "HelHall1" })); helContents.Add("HelRoom3", new AdjacencyList("HelRoom3", new string[] { "HelHall1" })); helContents.Add("HelRoom4", new AdjacencyList("HelRoom4", new string[] { "HelHall2" })); helContents.Add("HelRoom5", new AdjacencyList("HelRoom5", new string[] { "HelHall2" })); helContents.Add("HelRoom6", new AdjacencyList("HelRoom6", new string[] { "HelHall2" })); helContents.Add("HelRoom7", new AdjacencyList("HelRoom7", new string[] { "HelHall3" })); helContents.Add("HelRoom8", new AdjacencyList("HelRoom8", new string[] { "HelHall3" })); helContents.Add("HelRoom9", new AdjacencyList("HelRoom9", new string[] { "HelHall3" })); helContents.Add("HelHall1", new AdjacencyList("HelHall1", new string[] { "HelStart", "HelDesk1", "HelRoom1", "HelRoom2", "HelRoom3" })); helContents.Add("HelHall2", new AdjacencyList("HelHall2", new string[] { "HelDesk1", "HelDesk2", "HelRoom4", "HelRoom5", "HelRoom6" })); helContents.Add("HelHall3", new AdjacencyList("HelHall3", new string[] { "HelDesk2", "HelBoss", "HelRoom7", "HelRoom8", "HelRoom9" })); helContents.Add("HelDesk1", new AdjacencyList("HelDesk1", new string[] { "HelHall1", "HelHall2" })); helContents.Add("HelDesk2", new AdjacencyList("HelDesk2", new string[] { "HelHall2", "HelHall3", "HelStore" })); helContents.Add("HelStore", new AdjacencyList("HelStore", new string[] { "HelDesk2" })); helContents.Add("HelBoss", new AdjacencyList("HelBoss", new string[] { "HelHall3", "HelFinal" })); helContents.Add("HelFinal", new AdjacencyList("HelFinal", new string[] { "HelBoss" })); Dictionary <string, Event> helEvents = new Dictionary <string, Event>(); HealthGetter.Refresh(); helEvents.Add("HelStart", HealthGetter.Hall()); helEvents.Add("HelRoom1", HealthGetter.Room()); helEvents.Add("HelRoom2", HealthGetter.Room()); helEvents.Add("HelRoom3", HealthGetter.Room()); helEvents.Add("HelRoom4", HealthGetter.Room()); helEvents.Add("HelRoom5", HealthGetter.Room()); helEvents.Add("HelRoom6", HealthGetter.Room()); helEvents.Add("HelRoom7", HealthGetter.Room()); helEvents.Add("HelRoom8", HealthGetter.Room()); helEvents.Add("HelRoom9", HealthGetter.Room()); helEvents.Add("HelHall1", HealthGetter.Hall()); helEvents.Add("HelHall2", HealthGetter.Hall()); helEvents.Add("HelHall3", HealthGetter.Hard()); helEvents.Add("HelDesk1", HealthGetter.Desk()); helEvents.Add("HelDesk2", HealthGetter.Desk()); helEvents.Add("HelStore", HealthGetter.Store()); helEvents.Add("HelBoss", new SurgeonEvent()); helEvents.Add("HelFinal", HealthGetter.Final()); DungeonMap health = new DungeonMap("HelStart", helContents, helEvents); Dictionary <string, AdjacencyList> lecContents = new Dictionary <string, AdjacencyList>(); lecContents.Add("LecStart", new AdjacencyList("LecStart", new string[] { "LecHall1" })); lecContents.Add("LecHall1", new AdjacencyList("LecHall1", new string[] { "LecStart", "LecHall2", "LecLH1" })); lecContents.Add("LecHall2", new AdjacencyList("LecHall2", new string[] { "LecHall1", "LecRoom1" })); lecContents.Add("LecHall3", new AdjacencyList("LecHall3", new string[] { "LecRoom1", "LecRoom2", "LecRoom3" })); lecContents.Add("LecHall4", new AdjacencyList("LecHall4", new string[] { "LecRoom3", "LecRoom4", "LecRoom5" })); lecContents.Add("LecHall5", new AdjacencyList("LecHall5", new string[] { "LecLH1", "LecLH2" })); lecContents.Add("LecRoom1", new AdjacencyList("LecRoom1", new string[] { "LecHall2", "LecHall3", "LecOff1" })); lecContents.Add("LecRoom2", new AdjacencyList("LecRoom2", new string[] { "LecHall3", "LecOff1" })); lecContents.Add("LecRoom3", new AdjacencyList("LecRoom3", new string[] { "LecHall3", "LecHall4" })); lecContents.Add("LecRoom4", new AdjacencyList("LecRoom4", new string[] { "LecHall4", "LecOff2" })); lecContents.Add("LecRoom5", new AdjacencyList("LecRoom5", new string[] { "LecHall4", "LecOff2", "LecBoss" })); lecContents.Add("LecOff1", new AdjacencyList("LecOff1", new string[] { "LecRoom1", "LecRoom2" })); lecContents.Add("LecOff2", new AdjacencyList("LecOff2", new string[] { "LecRoom4", "LecRoom5" })); lecContents.Add("LecLH1", new AdjacencyList("LecLH1", new string[] { "LecHall1", "LecHall5" })); lecContents.Add("LecLH2", new AdjacencyList("LecLH2", new string[] { "LecHall5", "LecBoss" })); lecContents.Add("LecBoss", new AdjacencyList("LecBoss", new string[] { "LecRoom5", "LecLH2", "LecFinal" })); lecContents.Add("LecFinal", new AdjacencyList("LecFinal", new string[] { "LecBoss" })); Dictionary <string, Event> lecEvents = new Dictionary <string, Event>(); LectureGetter.Refresh(); lecEvents.Add("LecStart", LectureGetter.Hall()); lecEvents.Add("LecHall1", LectureGetter.Hall()); lecEvents.Add("LecHall2", LectureGetter.Hall()); lecEvents.Add("LecHall3", LectureGetter.Hall()); lecEvents.Add("LecHall4", LectureGetter.Hall()); lecEvents.Add("LecHall5", LectureGetter.Hall()); lecEvents.Add("LecRoom1", LectureGetter.Room()); lecEvents.Add("LecRoom2", LectureGetter.Room()); lecEvents.Add("LecRoom3", LectureGetter.Room()); lecEvents.Add("LecRoom4", LectureGetter.Room()); lecEvents.Add("LecRoom5", LectureGetter.Hard()); lecEvents.Add("LecOff1", LectureGetter.Office()); lecEvents.Add("LecOff2", LectureGetter.Office()); lecEvents.Add("LecLH1", LectureGetter.LH()); lecEvents.Add("LecLH2", LectureGetter.LH()); lecEvents.Add("LecBoss", new TenuredEvent()); lecEvents.Add("LecFinal", LectureGetter.Final()); DungeonMap lecture = new DungeonMap("LecStart", lecContents, lecEvents); data = new Dictionary <string, DungeonMap>(); data.Add("tower", tower); data.Add("dining", dining); data.Add("research", research); data.Add("sports", sports); data.Add("art", art); data.Add("health", health); data.Add("lecture", lecture); Event ceo = new CEOEvent(); Event politician = new PoliticianEvent(); Event general = new GeneralEvent(); Event final = new FinalBossEvent(); HashSet <int> available = new HashSet <int>(new int[] { 0, 1, 2, 3, 4, 5, 6 }); System.Random rng = new System.Random(); int index; int[] mappedIndexes = new int[] { 0, 1, 2, 3, 4, 5, 6 }; index = rng.Next(7); available.Remove(index); SetBoss(index, politician); Areas.bossLocations.Add(index); mappedIndexes[index] = 6; index = rng.Next(6); available.Remove(mappedIndexes[index]); SetBoss(mappedIndexes[index], ceo); Areas.bossLocations.Add(mappedIndexes[index]); mappedIndexes[index] = mappedIndexes[5]; index = rng.Next(5); available.Remove(mappedIndexes[index]); SetBoss(mappedIndexes[index], general); Areas.bossLocations.Add(mappedIndexes[index]); mappedIndexes[index] = mappedIndexes[4]; index = rng.Next(4); available.Remove(mappedIndexes[index]); SetBoss(mappedIndexes[index], final); Areas.bossLocations.Add(mappedIndexes[index]); int[] availableArray = new int[3]; available.CopyTo(availableArray); foreach (int i in availableArray) { Areas.bossLocations.Add(i); } int starting = availableArray[rng.Next(3)]; SetFirst(starting); Areas.SetLocation(starting); }
public void CopyTo(T[] array, int arrayIndex) { Items.CopyTo(array, arrayIndex); }
public void CopyTo(T[] array, int arrayIndex) { m_data.CopyTo(array, arrayIndex); }
public void CopyTo(T[] array, int arrayIndex) { _wrapped.CopyTo(array, arrayIndex); }
public void CopyTo(TypeInfo[] array, int arrayIndex) => controllerTypes.CopyTo(array, arrayIndex);
/// <summary> /// 获取等待更新的属性列表 /// </summary> internal string[] GetWaitUpdateList() { string[] columns = new string[_waitUpdateList.Count]; _waitUpdateList.CopyTo(columns, 0); return(columns); }
/// <summary> /// Runs the learning algorithm. /// </summary> /// /// <param name="token">A token to stop processing when requested.</param> /// <param name="c">The complexity for each sample.</param> protected override void Run(CancellationToken token, double[] c) { // The SMO algorithm chooses to solve the smallest possible optimization problem // at every step. At every step, SMO chooses two Lagrange multipliers to jointly // optimize, finds the optimal values for these multipliers, and updates the SVM // to reflect the new optimal values. // // Reference: http://research.microsoft.com/en-us/um/people/jplatt/smoTR.pdf // The algorithm has been updated to implement the improvements suggested // by Keerthi et al. The code has been based on the pseudo-code available // on the author's technical report. // // Reference: http://www.cs.iastate.edu/~honavar/keerthi-svm.pdf // Initialize variables int samples = Inputs.Length; int dimension = Inputs[0].Length; this.c = c; // Lagrange multipliers Array.Clear(alpha, 0, alpha.Length); if (IsLinear) // Hyperplane weights { Array.Clear(weights, 0, weights.Length); } // Error cache Array.Clear(errors, 0, errors.Length); // Kernel evaluations cache this.kernelCache = new KernelFunctionCache(Kernel, Inputs, cacheSize); // [Keerthi] Initialize b_up to -1 and // i_up to any one index of class 1: this.b_upper = -1; this.i_upper = Outputs.First(x => x > 0); // [Keerthi] Initialize b_low to +1 and // i_low to any one index of class 2: this.b_lower = +1; this.i_lower = Outputs.First(x => x < 0); // [Keerthi] Set error cache for i_low and i_up: this.errors[i_lower] = +1; this.errors[i_upper] = -1; // Prepare indices sets activeExamples.Clear(); nonBoundExamples.Clear(); atBoundsExamples.Clear(); // Algorithm: int numChanged = 0; int wholeSetChecks = 0; bool examineAll = true; bool diverged = false; bool shouldStop = false; while ((numChanged > 0 || examineAll) && !shouldStop) { numChanged = 0; if (examineAll) { // loop I over all training examples for (int i = 0; i < samples; i++) { if (examineExample(i)) { numChanged++; } } wholeSetChecks++; } else { if (strategy == SelectionStrategy.Sequential) { // loop I over examples not at bounds for (int i = 0; i < alpha.Length; i++) { if (alpha[i] != 0 && alpha[i] != c[i]) { if (examineExample(i)) { numChanged++; } if (b_upper > b_lower - 2.0 * tolerance) { numChanged = 0; break; } } } } else // strategy == Strategy.WorstPair { int attempts = 0; do { attempts++; if (!takeStep(i_upper, i_lower)) { break; } if (attempts > samples * maxChecks) { break; } }while ((b_upper <= b_lower - 2.0 * tolerance)); numChanged = 0; } } if (examineAll) { examineAll = false; } else if (numChanged == 0) { examineAll = true; } if (wholeSetChecks > maxChecks) { shouldStop = diverged = true; } if (token.IsCancellationRequested) { shouldStop = true; } } // Store information about bounded examples for (int i = 0; i < alpha.Length; i++) { if (alpha[i] == c[i]) { atBoundsExamples.Add(i); } } if (isCompact) { // Store the hyperplane directly Machine.SupportVectors = null; Machine.Weights = weights; Machine.Threshold = -(b_lower + b_upper) / 2.0; } else { // Store Support Vectors in the SV Machine. Only vectors which have Lagrange multipliers // greater than zero will be stored as only those are actually required during evaluation. int activeCount = activeExamples.Count; int[] idx = new int[activeCount]; activeExamples.CopyTo(idx); Machine.SupportVectors = new double[activeCount][]; Machine.Weights = new double[activeCount]; for (int i = 0; i < idx.Length; i++) { int j = idx[i]; Machine.SupportVectors[i] = Inputs[j]; Machine.Weights[i] = alpha[j] * Outputs[j]; } Machine.Threshold = -(b_lower + b_upper) / 2; } // Clear function cache this.kernelCache.Clear(); this.kernelCache = null; if (diverged) { throw new ConvergenceException("Convergence could not be attained. " + "Please reduce the cost of misclassification errors by reducing " + "the complexity parameter C or try a different kernel function."); } }
protected virtual void Filter(HashSet<Tile> tiles) { Tile[] array = new Tile[tiles.Count]; tiles.CopyTo(array); for (int i = array.Length - 1; i >= 0; --i) if (array[i].unit != null) tiles.Remove(array[i]); }