Пример #1
0
    public static Voronoi Relax(Voronoi voronoi, Vector2 bounds1, Vector2 bounds2, int amount = 100)
    {
        Voronoi newVoronoi;
        HashSet<Vector2> sites = new HashSet<Vector2>();
        Vector2 centroidRemember;

        foreach (KeyValuePair<Vector2, Polygon> poly in voronoi.Polygons)
        {
            centroidRemember = PolygonCentroid(poly.Value);
            if (centroidRemember.x != -Mathf.Infinity && centroidRemember.y != -Mathf.Infinity && centroidRemember.x != Mathf.Infinity && centroidRemember.y != Mathf.Infinity && centroidRemember.x > bounds1.x && centroidRemember.y > bounds1.y && centroidRemember.x < bounds2.x && centroidRemember.y < bounds2.y)
            {
                sites.Add(centroidRemember);
            }
            else
            {
                sites.Add(poly.Value.MidPoint.Point);
            }
        }

        amount--;

        newVoronoi = Delaunay.DeriveVoronoi(sites.ToList(), Delaunay.Triangulate(sites.ToList()));

        if (amount <= 0)
        {
            return newVoronoi;
        }
        else
        {
            return Relax(newVoronoi, bounds1, bounds2, amount);
        }
    }
Пример #2
0
        private static Dictionary<string, string> Translate(HashSet<string> toTranslate, string fromCulture, string toCulture)
        {
            var translated = Translation.TranslationClient.Translator.TranslateBatch(toTranslate.ToList(), fromCulture, toCulture);

            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.AddRange(toTranslate.ToList(), translated);
            return dic;
        }
        public static List<XmlSchema> GetAllSchemas(this XmlSchemaSet schemaSet)
        {
            // The method XmlSchemaSet.Schemas() will only include all schemas
            // directly added to th schema set, it does not contain any schema
            // that is only indirectly included or imported.
            //
            // So the first thing is to recursively process all schemas and add
            // all schemas included or imported.

            var schemas = new HashSet<XmlSchema>();
            foreach (XmlSchema schema in schemaSet.Schemas())
            {
                schemas.Add(schema);
                AddIncludedSchemas(schemas, schema);
            }

            // However, now there are still schemas missing: so-called chameleon
            // schemas. A chameleon schema is a schema that does not declare
            // a target namespace. If such a schema is included into another
            // schema that declares a target namespace the included schema
            // "inherits" that target namespace. System.Xml.Schema accomplishes
            // that by cloning the schema object and updating all the
            // namespaces. The problem is that we don't find such a schema
            // via XmlSchemaSet.Schemas() or schema.Includes. Instead we have
            // to look at every declared entity and search up their parents
            // until we find the declaring schema. This is sad and ineffecient
            // but it seems to be the only possible option.

            var topLevelSchemas = schemas.ToList();
            foreach (var schema in topLevelSchemas)
            {
                var allItems = schema.Elements.Values.Cast<XmlSchemaObject>()
                       .Concat(schema.Attributes.Values.Cast<XmlSchemaObject>())
                       .Concat(schema.Groups.Values.Cast<XmlSchemaObject>())
                       .Concat(schema.AttributeGroups.Values.Cast<XmlSchemaObject>())
                       .Concat(schema.SchemaTypes.Values.Cast<XmlSchemaObject>())
                       .Concat(schema.Notations.Values.Cast<XmlSchemaObject>());

                foreach (var item in allItems)
                {
                    var declaredSchema = item.GetSchema();
                    if (declaredSchema != null)
                        schemas.Add(declaredSchema);
                }
            }

            return schemas.ToList();
        }
Пример #4
0
        public static List<string> ParseAlbum(Uri albumUrl)
        {
            HashSet<string> uniqueImageUrls = new HashSet<string>();
            string xhtml = HttpUtils.RetrieveTextFromHttp(albumUrl);
            Regex regex = new Regex("\"//i.imgur.com/[^\"]+\"");
            MatchCollection matches = regex.Matches(xhtml);
            foreach (Match match in matches)
            {
                // Format URL's
                string url = match.Value;
                url = url.Trim('"');
                url = "http:" + url;

                // Eliminate small thumbnails
                char lastCharBeforeDot = url[url.LastIndexOf('.') - 1];
                if (lastCharBeforeDot == 's')
                {
                    continue;
                }

                // Eliminate badly-formatted images (e.g. from JavaScript)
                if (url.Remove(0, 19).IndexOf('.') < 1)
                {
                    continue;
                }

                uniqueImageUrls.Add(url);
            }
            return uniqueImageUrls.ToList<string>();
        }
        public static List<HandwrittenWord> SymbolsToWords(List<HandwrittenSymbol> symbols)
        {
            int[] symbolWords = new int[symbols.Count]; // int = number of symbols word in words list
            for (int i = 0; i < symbols.Count; i++)
                symbolWords[i] = i;

            for (int i = 0; i < symbols.Count - 1; i++)
                for (int j = i + 1; j < symbols.Count; j++)
                    if (isSameWord(symbols[i].bounds, symbols[j].bounds))
                        symbolWords[j] = symbolWords[i];               //now each int in symbolWords contains correct number of symbols word

            HashSet<int> words = new HashSet<int>();
            foreach (int word in symbolWords)
                words.Add(word);                                     //delete duplicates

            //get rid of this block?
            List<List<int>> numbersOfSymbolsInWords = new List<List<int>>();
            foreach (int word in words)
                numbersOfSymbolsInWords.Add(new List<int>());
            for (int i = 0; i < symbolWords.Length; i++)
                numbersOfSymbolsInWords[words.ToList().IndexOf(symbolWords[i])].Add(i);

            // List<List<int>> to List<HandwrittenWord>
            List<HandwrittenWord> result = new List<HandwrittenWord>();
            for (int i = 0; i < numbersOfSymbolsInWords.Count;i++ )
            {
                result.Add(new HandwrittenWord());
                for(int j=0;j<numbersOfSymbolsInWords[i].Count;j++)
                    result[i].symbols.Add(symbols[numbersOfSymbolsInWords[i][j]]);
            }
            return result;
        }
Пример #6
0
        public static IReadOnlyList <RazorDiagnostic> GetAllDiagnostics(this IntermediateNode node)
        {
            if (node == null)
            {
                throw new ArgumentNullException(nameof(node));
            }

            HashSet <RazorDiagnostic> diagnostics = null;

            AddAllDiagnostics(node);

            return(diagnostics?.ToList() ?? EmptyDiagnostics);

            void AddAllDiagnostics(IntermediateNode n)
            {
                if (n.HasDiagnostics)
                {
                    if (diagnostics == null)
                    {
                        diagnostics = new HashSet <RazorDiagnostic>();
                    }

                    diagnostics.UnionWith(n.Diagnostics);
                }

                for (var i = 0; i < n.Children.Count; i++)
                {
                    AddAllDiagnostics(n.Children[i]);
                }
            }
        }
Пример #7
0
    private static string ParseFiles(IEnumerable<string> filePaths)
    {
        var classLines = new List<string>();
        var usingsSet = new HashSet<string>();

        Func<string, bool> isUsingStmt = (x) => x.StartsWith("using");

        var lines = filePaths.Select(x => File.ReadAllLines(x)).SelectMany(x => x).ToList();

        foreach (var line in filePaths.Select(x => File.ReadAllLines(x)).SelectMany(x => x)) {

            if (isUsingStmt(line)) {
                usingsSet.Add(line);

            } else {

                classLines.Add(line);
            }

        }

        var result = usingsSet.ToList();

        result.AddRange(classLines);

        var builder = new StringBuilder();

        result.ForEach(x => builder.AppendLine(x));

        return builder.ToString();
    }
 private IList<Position> Init(char[,] board)
 {
     ISet<Position> res=new HashSet<Position>();
     // for(int i=0;i<board.GetLength(0);i++)
     // {
     //     for(int j=0;j<board.GetLength(1);j++)
     //     {
     //         if(board[i,j]=='O')
     //             res.Add(new Position(i,j));
     //     }
     // }
     for(int j=0;j<board.GetLength(1);j++)
     {
         if(board[0,j]=='O')
             res.Add(new Position(0,j));
         if(board[board.GetLength(0)-1,j]=='O')
             res.Add(new Position(board.GetLength(0)-1,j));
     }
     for(int i=0;i<board.GetLength(0);i++)
     {
         if(board[i,0]=='O')
             res.Add(new Position(i,0));
         if(board[i,board.GetLength(1)-1]=='O')
             res.Add(new Position(i,board.GetLength(1)-1));
     }
     return res.ToList();
 }
Пример #9
0
        /// <summary>
        /// This method removes duplicates from tile connections. This includes connections
        /// which are a subset of another connection.
        /// </summary>
        /// <param name="tileConnections"></param>
        /// <returns></returns>
        public static List<TileConnection> CleanDuplicatesFromTileCollectionList(List<TileConnection> tileConnections)
        {
            var dupes = new HashSet<TileConnection>();

            //compare every tile connection against every other to find the duplicates. This is slow.
            for (var tci = 0; tci < tileConnections.Count; tci++) {
                var tc = tileConnections[tci];
                for (var tci2 = tci + 1; tci2 < tileConnections.Count; tci2++) {
                    var tc2 = tileConnections[tci2];
                    if (!dupes.Contains(tc2) && tc2.IsDuplicateOrSubsetOf(tc)) {
                        dupes.Add(tc2);

                    } else if (!dupes.Contains(tc) && tc.IsDuplicateOrSubsetOf(tc2)) {
                        //By using else if we ensure that we don't add both tileconnections
                        //if they are exact duplicates
                        dupes.Add(tc);
                    }
                }
            }

            //remove all the duplicates
            dupes.ToList().ForEach( dup => {
                tileConnections.Remove(dup);
            });

            return tileConnections;
        }
Пример #10
0
 public override IEnumerable<string> GetNamespacesToAdd(IConnectionInfo cxInfo)
 {
     var set = new HashSet<string>(base.GetNamespacesToAdd(cxInfo));
     var settings = GetCxSettings(cxInfo);
     set.UnionWith(settings.NamespacesToAdd);
     return set.ToList();
 }
Пример #11
0
        public string[][] FindLadders(string start, string end, string[] dict)
        {
            HashSet<string> dictionary = new HashSet<string>(dict);
            HashSet<string> currentStarts = new HashSet<string>() { start };

            List<string[]> results = new List<string[]>();
            Dictionary<string, List<string>> backtrackMap = new Dictionary<string, List<string>>();

            while (currentStarts.Count > 0)
            {
                currentStarts.ToList().ForEach(x => dictionary.Remove(x));
                HashSet<string> nextStarts = new HashSet<string>();

                foreach (string word in currentStarts)
                {
                    if (word == end)
                    {
                        AddPathToResults(backtrackMap, start, end, results);
                    }
                    GetAllValidNextWords(word, dictionary, nextStarts, backtrackMap);
                }

                currentStarts = nextStarts;
            }

            return results.ToArray();
        }
Пример #12
0
    public static List<int> GenerateRandom(int count, int min = 27560000, int max = 27569999)
    {
        if (max <= min || count < 0 ||
                (count > max - min && max - min > 0))
        {
            throw new ArgumentOutOfRangeException("Range or count " + count + " is illegal");
        }

        HashSet<int> candidates = new HashSet<int>();

        for (int top = max - count; top < max; top++)
        {
            if (!candidates.Add(random.Next(min, top + 1)))
            {
                candidates.Add(top);
            }
        }

        List<int> result = candidates.ToList();

        for (int i = result.Count - 1; i > 0; i--)
        {
            int k = random.Next(i + 1);
            int tmp = result[k];
            result[k] = result[i];
            result[i] = tmp;
        }
        return result;
    }
        public UpshotControllerDescription(HttpControllerDescriptor controllerDescriptor)
        {
            HashSet<Type> entityTypes = new HashSet<Type>();

            _upshotControllerType = controllerDescriptor.ControllerType;

            IEnumerable<MethodInfo> enumerable =
            from p in _upshotControllerType.GetMethods(BindingFlags.Instance | BindingFlags.Public)
            where p.DeclaringType != typeof(UpshotController) && p.DeclaringType != typeof(object) && !p.IsSpecialName
            select p;
            foreach (MethodInfo current in enumerable)
            {
                if (current.GetCustomAttributes(typeof(NonActionAttribute), false).Length <= 0 && (!current.IsVirtual || !(current.GetBaseDefinition().DeclaringType == typeof(UpshotController))))
                {
                    if (current.ReturnType != typeof(void))
                    {
                        Type type = TypeUtility.UnwrapTaskInnerType(current.ReturnType);
                        Type elementType = TypeUtility.GetElementType(type);
                        if (LookUpIsEntityType(elementType))
                        {
                            if (!entityTypes.Contains(elementType))
                            {
                                entityTypes.Add(elementType);
                            }
                        }
                    }
                }
            }
            _entityTypes = new ReadOnlyCollection<Type>(entityTypes.ToList());
        }
Пример #14
0
        public int LadderLength(string start, string end, string[] dict)
        {
            int result = 0;

            HashSet<string> hashSet = new HashSet<string>(dict);
            HashSet<string> currentStarts = new HashSet<string>() { start }; // change to List will slow down perf

            while (currentStarts.Count > 0)
            {
                currentStarts.ToList().ForEach(x => hashSet.Remove(x));

                result++;

                HashSet<string> nextStarts = new HashSet<string>();
                foreach (string word in currentStarts)
                {
                    if (word == end)
                    {
                        return result;
                    }
                    GetAllValidMoves(word, hashSet, nextStarts);
                }

                currentStarts = nextStarts;
            }
            return 0;
        }
Пример #15
0
        public IList<int> GrayCode(int n)
        {
            //List<int> re = new List<int>();
            HashSet<int> re = new HashSet<int>();

            re.Add(0);
            while(true)
            {
                var val = re.Last();
                int i = 0;
                while(i < n)
                {
                    int nextval = val ^ (1 << i);
                    if (!re.Contains(nextval))
                    {
                        re.Add(nextval);
                        break;
                    }
                    i++;                 
                }
                if (i == n)
                    break;
            }
            
            return re.ToList();
        }
        public void Can_Execute_Multiple_Times(int iterations)
        {
            var expectedMaxBuildNumber = iterations;

            // Using a set to store each generated build number instead of a list in order to detect duplicates.
            // If an attempt is made to store a duplicate build number in the HashSet instance, an exception will be thrown and the test will fail.
            var set = new HashSet<int>();

            var stopwatch = Stopwatch.StartNew();

            for (var i = 0; i < iterations; ++i)
            {
                var buildNumber = Can_Execute_Test();
                set.Add(buildNumber);
                Thread.Sleep(1); // <-- Used to smooth out race conditions regarding the Date property whereby fast machines can get the date out of order.
            }

            stopwatch.Stop();

            Console.WriteLine("Completed 100 iterations in {0} milliseconds.", stopwatch.ElapsedMilliseconds);

            var list = set.ToList();
            list.ForEach(bn => Console.WriteLine("Build Number: {0}", bn));

            // Assert for the whole set.
            int maxBuildNumber;

            using (var db = new BuildVersioningDataContext(GetConfiguredConnectionString()))
            {
                maxBuildNumber = db.VersionHistoryItems.Max(vhi => vhi.BuildNumber);
            }

            // If there are any duplicates, the max expected build number could not be generated.
            maxBuildNumber.ShouldEqual(expectedMaxBuildNumber);
        }
        public static void PrintAllTestFailures()
        {
            var directories = GetBuildDirectories();

            var tests = new HashSet<AggregateTestResult>();

            var totalBuilds = 0;
            var days = 1;

            foreach (var dir in directories.Where(x=>Directory.GetCreationTime(x) > DateTime.Now.AddDays(-1 * days)))
            {
                totalBuilds++;
                var files = Directory.GetFiles(dir, "junitResult.xml");
                if (files.Any())
                {
                    var fileName = files[0];
                    var iterator = GetTestCasesWithErrors(fileName);

                    while (iterator.MoveNext())
                    {
                        var failingTest = GetFailingTestName(iterator);

                        var testResult = GetTestResult(failingTest, tests);

                        UpdateResults(failingTest, dir, tests, testResult);
                    }
                }
            }
            foreach (var failingTest in tests.ToList().OrderBy(x=>x.FailureCount).Reverse())
            {
                Console.WriteLine(failingTest);
            }
            Console.WriteLine("Tests performed during last: " + days + " days");
            Console.WriteLine("Total Builds performed during test run: " + totalBuilds);
        }
Пример #18
0
 public void Test_set()
 {
     Assert.AreEqual(new Argument("N"), new Argument("N"));
     var l = new List<Pattern> {new Argument("N"), new Argument("N")};
     var s = new HashSet<Pattern>(l);
     Assert.AreEqual(new Pattern[] {new Argument("N"),}, s.ToList());
 }
Пример #19
0
        private static void Main()
        {
            var input = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
            var n = input[0];
            var coord0 = new Coord(input[1], input[2]);
            var rgcoord = new HashSet<Coord>();
            for (var i = 0; i < n; i++)
            {
                input = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
                rgcoord.Add(new Coord(input[0], input[1]));
            }

            var d = 0;
            while (rgcoord.Any())
            {
                d++;
                var coord = rgcoord.First();
                var vX = coord.x - coord0.x;
                var vY = coord.y - coord0.y;

                foreach (var coordT in rgcoord.ToList())
                {
                    if (vY*(coordT.x - coord0.x) == vX*(coordT.y - coord0.y))
                        rgcoord.Remove(coordT);
                }
            }

            Console.WriteLine(d);
        }
Пример #20
0
		public static List<Device> GetRemoteForZone(Device parentPanel, Zone zone)
		{
			var devices = new HashSet<Device>();
			foreach (var device in GetDevicesInLogic(zone))
			{
				foreach (var clause in device.ZoneLogic.Clauses)
				{
					var allZonesAreRemote = true;
					foreach (var clauseZone in clause.Zones)
					{
						if (clauseZone.DevicesInZone.FirstOrDefault().ParentPanel.UID == device.ParentPanel.UID)
							allZonesAreRemote = false;
					}

					if (clause.Operation.Value == ZoneLogicOperation.Any || allZonesAreRemote)
					{
						foreach (var clauseZone in clause.Zones)
						{
							if (clauseZone.UID == zone.UID)
							{
								if (device.ParentPanel.UID != parentPanel.UID)
								{
									devices.Add(device);
								}
							}
						}
					}
				}
			}
			return devices.ToList();
		}
Пример #21
0
 public void UndoRedo(Board board)
 {
     HashSet<int> layersToRecheck = new HashSet<int>();
     foreach (UndoRedoAction action in Actions)
         action.UndoRedo(layersToRecheck);
     layersToRecheck.ToList().ForEach(x => board.Layers[x].RecheckTileSet());
 }
Пример #22
0
        public List<string> GenerateLicenseKeys(string rsaXmlString, LicenseBase scutexLicense, LicenseGenerationOptions generationOptions, int count)
        {
            HashSet<string> licenses = new HashSet<string>();
            int doupCount = 0;

            while (licenses.Count < count)
            {
                string key = GenerateLicenseKey(rsaXmlString, scutexLicense, generationOptions);

                if (licenses.Contains(key) == false)
                {
                    licenses.Add(key);
                    //Debug.WriteLine(string.Format("{0} of {1} keys generated", licenses.Count, count));
                }
                else
                {
                    doupCount++;
                    Debug.WriteLine(string.Format("Duplicate key was generated {0}", key));
                }
            }

            if (doupCount > 0)
                Debug.WriteLine(string.Format("{0} duplicate keys were generated at a {1}% chance", doupCount, doupCount * 100m / count));

            return licenses.ToList();
        }
        public async Task<SignatureHelp> GetSignatureHelp(Request request)
        {
            var invocations = new List<InvocationContext>();
            foreach (var document in _workspace.GetDocuments(request.FileName))
            {
                var invocation = await GetInvocation(document, request);
                if (invocation != null)
                {
                    invocations.Add(invocation);
                }
            }

            if (invocations.Count == 0)
            {
                return null;
            }

            var response = new SignatureHelp();

            // define active parameter by position
            foreach (var comma in invocations.First().ArgumentList.Arguments.GetSeparators())
            {
                if (comma.Span.Start > invocations.First().Position)
                {
                    break;
                }
                response.ActiveParameter += 1;
            }

            // process all signatures, define active signature by types
            var signaturesSet = new HashSet<SignatureHelpItem>();
            var bestScore = int.MinValue;
            SignatureHelpItem bestScoredItem = null;

            foreach (var invocation in invocations)
            {
                var types = invocation.ArgumentList.Arguments
                    .Select(argument => invocation.SemanticModel.GetTypeInfo(argument.Expression));

                foreach (var methodOverload in GetMethodOverloads(invocation.SemanticModel, invocation.Receiver))
                {
                    var signature = BuildSignature(methodOverload);
                    signaturesSet.Add(signature);

                    var score = InvocationScore(methodOverload, types);
                    if (score > bestScore)
                    {
                        bestScore = score;
                        bestScoredItem = signature;
                    }
                }
            }

            var signaturesList = signaturesSet.ToList();
            response.Signatures = signaturesList;
            response.ActiveSignature = signaturesList.IndexOf(bestScoredItem);

            return response;
        }
Пример #24
0
		/// <summary>
		/// Initializes a new instance of the <see cref="MyMediaLite.Data.RatingScale"/> class,
		/// given a list of byte values
		/// </summary>
		/// <param name='rating_values'>the ratings dataset</param>
		public RatingScale (IList<byte> rating_values)
		{
			var levels = new HashSet<float>();
			foreach (float val in rating_values)
				levels.Add((float) val);

			Init(levels.ToList());
		}
Пример #25
0
 public override IEnumerable<string> GetAssembliesToAdd(IConnectionInfo cxInfo)
 {
     var set = new HashSet<string>(base.GetAssembliesToAdd(cxInfo));
     var settings = GetCxSettings(cxInfo);
     var paths = CxSettingsPathsHelper.Current.GetAssemblyLocations(settings);
     set.UnionWith(paths);
     return set.ToList();
 }
        private List<string> CreateHistory(HashSet<Domain.PartnerModule.History> histories)
        { 
            List<string> to = new List<string>();

            histories.ToList().ForEach(h => to.Add(h.Url));

            return to;
        }
        /// <summary>
        /// Starts the search for TV shows recursively starting from the specified path.
        /// </summary>
        /// <param name="path">The paths where to start the search.</param>
        /// <returns>
        /// The list of discovered TV shows.
        /// </returns>
        public List<string> DiscoverFromPath(string path)
        {
            _results = new HashSet<string>();

            ScanDirectoryForFile(path);

            return _results.ToList();
        }
Пример #28
0
        public static string TrackTableBuilder(IList<IJukeboxTrack> tracks, TrackTableKind kind)
        {
            var table = new StringBuilder();

            var lettersHash = new HashSet<string>(tracks.Select(x => x.ArtistsAndName.Substring(0, 1)));
            var letters = lettersHash.ToList();
            letters.Sort((x, y) => string.Compare(x, y));

            var alternateRow = false;
            foreach (var letter in letters)
            {
                var currentLetterTracks = tracks.Where(x => x.ArtistsAndName.StartsWith(letter));

                table.Append("<h3>" + letter.ToUpper() + "</h3>");
                table.Append("<table class=\"" + GetTableCssClass(kind) + "\">");

                if (alternateRow)
                {
                    table.Append("<tr class=\"alternatedRow\">");
                    alternateRow = false;
                }
                else
                {
                    table.Append("<tr>");
                    alternateRow = true;
                }

                var columnsAdded = 0;
                foreach (var track in currentLetterTracks)
                {
                    if (columnsAdded == 3)
                    {
                        table.Append("</tr>");

                        if (alternateRow)
                        {
                            table.Append("<tr class=\"alternatedRow\">");
                            alternateRow = false;
                        }
                        else
                        {
                            table.Append("<tr>");
                            alternateRow = true;
                        }

                        columnsAdded = 0;
                    }

                    table.Append(AddNewColumns(track, track.Equals(currentLetterTracks.Last()), columnsAdded, kind));

                    columnsAdded++;
                }

                table.Append("</tr></table>");
            }

            return table.ToString();
        }
Пример #29
0
		public static List<XStateClass> StateBitsToStateClasses(List<GKStateBit> stateBits)
		{
			var stateClasses = new HashSet<XStateClass>();
			foreach (var stateBit in stateBits)
			{
				switch (stateBit)
				{
					case GKStateBit.Fire2:
						stateClasses.Add(XStateClass.Fire2);
						break;
					case GKStateBit.Fire1:
						stateClasses.Add(XStateClass.Fire1);
						break;
					case GKStateBit.Attention:
						stateClasses.Add(XStateClass.Attention);
						break;
					case GKStateBit.Failure:
						stateClasses.Add(XStateClass.Failure);
						break;
					case GKStateBit.Ignore:
						stateClasses.Add(XStateClass.Ignore);
						break;
					case GKStateBit.On:
						stateClasses.Add(XStateClass.On);
						break;
					case GKStateBit.Off:
						stateClasses.Add(XStateClass.Off);
						break;
					case GKStateBit.TurningOn:
						stateClasses.Add(XStateClass.TurningOn);
						break;
					case GKStateBit.TurningOff:
						stateClasses.Add(XStateClass.TurningOff);
						break;
					case GKStateBit.Test:
						stateClasses.Add(XStateClass.Test);
						break;
				}
			}

			if (!stateBits.Contains(GKStateBit.Norm))
			{
				stateClasses.Add(XStateClass.AutoOff);
			}

			if (stateBits.Contains(GKStateBit.Ignore))
			{
				stateClasses.Remove(XStateClass.AutoOff);
			}

			if (stateClasses.Count == 0)
			{
				stateClasses.Add(XStateClass.Norm);
			}
			var result = stateClasses.ToList();
			result.OrderBy(x => x);
			return result;
		}
Пример #30
0
 /// <summary>
 ///     获得喂食任务获得所选猪舍
 /// </summary>
 /// <param name="taskPigsties">任务_猪栏集合</param>
 /// <returns>猪舍id号集合</returns>
 public List<long> GetPigHouseIds(List<task_pigsty> taskPigsties)
 {
     var pigHouseIds = new HashSet<long>();
     foreach (task_pigsty feedTaskPigsty in taskPigsties)
     {
         pigHouseIds.Add(feedTaskPigsty.pigsty.PigHouseId);
     }
     return pigHouseIds.ToList();
 }
Пример #31
0
        public CipherData(CipherResponse response, string userId = null, HashSet <string> collectionIds = null)
        {
            Id                  = response.Id;
            OrganizationId      = response.OrganizationId;
            FolderId            = response.FolderId;
            UserId              = userId;
            Edit                = response.Edit;
            ViewPassword        = response.ViewPassword;
            OrganizationUseTotp = response.OrganizationUseTotp;
            Favorite            = response.Favorite;
            RevisionDate        = response.RevisionDate;
            Type                = response.Type;
            Name                = response.Name;
            Notes               = response.Notes;
            CollectionIds       = collectionIds?.ToList() ?? response.CollectionIds;
            Reprompt            = response.Reprompt;

            try // Added to address Issue (https://github.com/bitwarden/mobile/issues/1006)
            {
                switch (Type)
                {
                case Enums.CipherType.Login:
                    Login = new LoginData(response.Login);
                    break;

                case Enums.CipherType.SecureNote:
                    SecureNote = new SecureNoteData(response.SecureNote);
                    break;

                case Enums.CipherType.Card:
                    Card = new CardData(response.Card);
                    break;

                case Enums.CipherType.Identity:
                    Identity = new IdentityData(response.Identity);
                    break;

                default:
                    break;
                }
            }
            catch
            {
                System.Diagnostics.Trace.WriteLine(new StringBuilder()
                                                   .Append("BitWarden CipherData constructor failed to initialize CyperType '")
                                                   .Append(Type)
                                                   .Append("'; id = {")
                                                   .Append(Id)
                                                   .AppendLine("}")
                                                   .ToString(), "BitWarden CipherData constructor");
            }

            Fields          = response.Fields?.Select(f => new FieldData(f)).ToList();
            Attachments     = response.Attachments?.Select(a => new AttachmentData(a)).ToList();
            PasswordHistory = response.PasswordHistory?.Select(ph => new PasswordHistoryData(ph)).ToList();
            DeletedDate     = response.DeletedDate;
        }
Пример #32
0
 public StreamFilterData Serialize()
 {
     return(new StreamFilterData
     {
         ClassName = className,
         MethodName = methodName,
         Items = items?.ToList()
     });
 }
 public List<Point> GetBasePoints()
 {
     var set = new HashSet<Point>();
     foreach (var point in _parent)
     {
         set.Add(FindBasePoint(point));
     }
     return set.ToList();
 }
Пример #34
0
        public CipherData(CipherResponse response, string userId = null, HashSet <string> collectionIds = null)
        {
            Id                  = response.Id;
            OrganizationId      = response.OrganizationId;
            FolderId            = response.FolderId;
            UserId              = userId;
            Edit                = response.Edit;
            ViewPassword        = response.ViewPassword;
            OrganizationUseTotp = response.OrganizationUseTotp;
            Favorite            = response.Favorite;
            RevisionDate        = response.RevisionDate;
            Type                = response.Type;
            Name                = response.Name;
            Notes               = response.Notes;
            CollectionIds       = collectionIds?.ToList() ?? response.CollectionIds;

            switch (Type)
            {
            case Enums.CipherType.Login:
                Login = new LoginData(response.Login);
                break;

            case Enums.CipherType.SecureNote:
                SecureNote = new SecureNoteData(response.SecureNote);
                break;

            case Enums.CipherType.Card:
                Card = new CardData(response.Card);
                break;

            case Enums.CipherType.Identity:
                Identity = new IdentityData(response.Identity);
                break;

            default:
                break;
            }

            Fields          = response.Fields?.Select(f => new FieldData(f)).ToList();
            Attachments     = response.Attachments?.Select(a => new AttachmentData(a)).ToList();
            PasswordHistory = response.PasswordHistory?.Select(ph => new PasswordHistoryData(ph)).ToList();
            DeletedDate     = response.DeletedDate;
        }
Пример #35
0
        public virtual SarifLog ConstructSarifLog(
            IList <Result> results,
            HashSet <Artifact> artifacts,
            HashSet <ReportingDescriptor> rules)
        {
            if (results is null)
            {
                throw new ArgumentNullException(nameof(results));
            }

            if (artifacts is null)
            {
                throw new ArgumentNullException(nameof(artifacts));
            }

            if (rules is null)
            {
                throw new ArgumentNullException(nameof(rules));
            }

            return(new SarifLog()
            {
                Version = SarifVersion.Current,
                SchemaUri = new Uri(ToolInformation.SARIFSchemaUri),
                Runs = new List <Run>()
                {
                    new Run()
                    {
                        Tool = new Tool()
                        {
                            Driver = new ToolComponent()
                            {
                                Name = ToolInformation.ToolName,
                                InformationUri = new Uri(ToolInformation.ToolUri),
                                Rules = rules?.ToList()
                            }
                        },
                        Artifacts = artifacts?.ToList(),
                        Results = results?.ToList()
                    }
                }
            });
        }
Пример #36
0
        /// Try to avoid calling this directly
        /// Use the Sound.playing property instead
        public void PlayOrPause(bool play, bool pauseOthers, KAudio.AudioType type = KAudio.AudioType.None)
        {
            if (pauseOthers)
            {
                if (play)
                {
                    //interruptedSounds = new HashSet<Sound>(audioManager.sounds.Where(snd => snd.Playing &&
                    //                                                                        snd != this));
                }
                interruptedSounds?.ToList().ForEach(sound => sound.PlayOrPause(!play, false));
            }

            if (source != null)
            {
                if (play && !source.isPlaying)
                {
                    source?.PlayDelayed(DelayTime);
                }
                else
                {
                    //source?.Pause();
                }
            }
        }
Пример #37
0
    public static void Cook(ProjectParams Params)
    {
        if ((!Params.Cook && !(Params.CookOnTheFly && !Params.SkipServer)) || Params.SkipCook)
        {
            return;
        }
        Params.ValidateAndLog();

        Log("********** COOK COMMAND STARTED **********");

        string UE4EditorExe = HostPlatform.Current.GetUE4ExePath(Params.UE4Exe);

        if (!FileExists(UE4EditorExe))
        {
            throw new AutomationException("Missing " + UE4EditorExe + " executable. Needs to be built first.");
        }

        if (Params.CookOnTheFly && !Params.SkipServer)
        {
            if (Params.HasDLCName)
            {
                throw new AutomationException("Cook on the fly doesn't support cooking dlc");
            }
            if (Params.ClientTargetPlatforms.Count > 0)
            {
                var LogFolderOutsideOfSandbox = GetLogFolderOutsideOfSandbox();
                if (!GlobalCommandLine.Installed)
                {
                    // In the installed runs, this is the same folder as CmdEnv.LogFolder so delete only in not-installed
                    DeleteDirectory(LogFolderOutsideOfSandbox);
                    CreateDirectory(LogFolderOutsideOfSandbox);
                }

                String COTFCommandLine = Params.RunCommandline;
                if (Params.IterativeCooking)
                {
                    COTFCommandLine += " -iterate -iteratehash";
                }
                if (Params.UseDebugParamForEditorExe)
                {
                    COTFCommandLine += " -debug";
                }

                var      ServerLogFile      = CombinePaths(LogFolderOutsideOfSandbox, "Server.log");
                Platform ClientPlatformInst = Params.ClientTargetPlatformInstances[0];
                string   TargetCook         = ClientPlatformInst.GetCookPlatform(false, false);       // cook on he fly doesn't support server cook platform...
                ServerProcess = RunCookOnTheFlyServer(Params.RawProjectPath, Params.NoClient ? "" : ServerLogFile, TargetCook, COTFCommandLine);

                if (ServerProcess != null)
                {
                    Log("Waiting a few seconds for the server to start...");
                    Thread.Sleep(5000);
                }
            }
            else
            {
                throw new AutomationException("Failed to run, client target platform not specified");
            }
        }
        else
        {
            var PlatformsToCook = new HashSet <string>();
            if (!Params.NoClient)
            {
                foreach (var ClientPlatform in Params.ClientTargetPlatforms)
                {
                    // Use the data platform, sometimes we will copy another platform's data
                    var    DataPlatformDesc = Params.GetCookedDataPlatformForClientTarget(ClientPlatform);
                    string PlatformToCook   = Platform.Platforms[DataPlatformDesc].GetCookPlatform(false, Params.Client);
                    PlatformsToCook.Add(PlatformToCook);
                }
            }
            if (Params.DedicatedServer)
            {
                foreach (var ServerPlatform in Params.ServerTargetPlatforms)
                {
                    // Use the data platform, sometimes we will copy another platform's data
                    var    DataPlatformDesc = Params.GetCookedDataPlatformForServerTarget(ServerPlatform);
                    string PlatformToCook   = Platform.Platforms[DataPlatformDesc].GetCookPlatform(true, false);
                    PlatformsToCook.Add(PlatformToCook);
                }
            }

            if (Params.Clean.HasValue && Params.Clean.Value && !Params.IterativeCooking)
            {
                Log("Cleaning cooked data.");
                CleanupCookedData(PlatformsToCook.ToList(), Params);
            }

            // cook the set of maps, or the run map, or nothing
            string[] Maps = null;
            if (Params.HasMapsToCook)
            {
                Maps = Params.MapsToCook.ToArray();
                foreach (var M in Maps)
                {
                    Log("HasMapsToCook " + M.ToString());
                }
                foreach (var M in Params.MapsToCook)
                {
                    Log("Params.HasMapsToCook " + M.ToString());
                }
            }

            string[] Dirs = null;
            if (Params.HasDirectoriesToCook)
            {
                Dirs = Params.DirectoriesToCook.ToArray();
            }

            string InternationalizationPreset = null;
            if (Params.HasInternationalizationPreset)
            {
                InternationalizationPreset = Params.InternationalizationPreset;
            }

            string[] CulturesToCook = null;
            if (Params.HasCulturesToCook)
            {
                CulturesToCook = Params.CulturesToCook.ToArray();
            }

            try
            {
                var CommandletParams = IsBuildMachine ? "-buildmachine -fileopenlog" : "-fileopenlog";
                if (Params.UnversionedCookedContent)
                {
                    CommandletParams += " -unversioned";
                }
                if (Params.FastCook)
                {
                    CommandletParams += " -FastCook";
                }
                if (Params.UseDebugParamForEditorExe)
                {
                    CommandletParams += " -debug";
                }
                if (Params.Manifests)
                {
                    CommandletParams += " -manifests";
                }
                if (Params.IterativeCooking)
                {
                    CommandletParams += " -iterate -iterateshash";
                }
                if (Params.IterateSharedCookedBuild)
                {
                    SharedCookedBuild.CopySharedCookedBuild(Params);
                    CommandletParams += " -iteratesharedcookedbuild";
                }

                if (Params.CookMapsOnly)
                {
                    CommandletParams += " -mapsonly";
                }
                if (Params.CookAll)
                {
                    CommandletParams += " -cookall";
                }
                if (Params.HasCreateReleaseVersion)
                {
                    CommandletParams += " -createreleaseversion=" + Params.CreateReleaseVersion;
                }
                if (Params.SkipCookingEditorContent)
                {
                    CommandletParams += " -skipeditorcontent";
                }
                if (Params.NumCookersToSpawn != 0)
                {
                    CommandletParams += " -numcookerstospawn=" + Params.NumCookersToSpawn;
                }
                if (Params.CookPartialGC)
                {
                    CommandletParams += " -partialgc";
                }
                if (Params.HasMapIniSectionsToCook)
                {
                    string MapIniSections = CombineCommandletParams(Params.MapIniSectionsToCook.ToArray());

                    CommandletParams += " -MapIniSection=" + MapIniSections;
                }
                if (Params.HasDLCName)
                {
                    CommandletParams += " -dlcname=" + Params.DLCFile.GetFileNameWithoutExtension();
                    if (!Params.DLCIncludeEngineContent)
                    {
                        CommandletParams += " -errorOnEngineContentUse";
                    }
                }
                if (!String.IsNullOrEmpty(Params.CookOutputDir))
                {
                    CommandletParams += " -outputdir=" + CommandUtils.MakePathSafeToUseWithCommandLine(Params.CookOutputDir);
                }
                // don't include the based on release version unless we are cooking dlc or creating a new release version
                // in this case the based on release version is used in packaging
                if (Params.HasBasedOnReleaseVersion && (Params.HasDLCName || Params.HasCreateReleaseVersion))
                {
                    CommandletParams += " -basedonreleaseversion=" + Params.BasedOnReleaseVersion;
                }
                // if we are not going to pak but we specified compressed then compress in the cooker ;)
                // otherwise compress the pak files
                if (!Params.Pak && !Params.SkipPak && Params.Compressed)
                {
                    CommandletParams += " -compressed";
                }

                if (Params.HasAdditionalCookerOptions)
                {
                    string FormatedAdditionalCookerParams = Params.AdditionalCookerOptions.TrimStart(new char[] { '\"', ' ' }).TrimEnd(new char[] { '\"', ' ' });
                    CommandletParams += " ";
                    CommandletParams += FormatedAdditionalCookerParams;
                }

                if (!Params.NoClient)
                {
                    var MapsList = Maps == null ? new List <string>() :  Maps.ToList();
                    foreach (var ClientPlatform in Params.ClientTargetPlatforms)
                    {
                        var DataPlatformDesc = Params.GetCookedDataPlatformForClientTarget(ClientPlatform);
                        CommandletParams += (Platform.Platforms[DataPlatformDesc].GetCookExtraCommandLine(Params));
                        MapsList.AddRange((Platform.Platforms[ClientPlatform].GetCookExtraMaps()));
                    }
                    Maps = MapsList.ToArray();
                }

                // Config overrides (-ini)
                foreach (string ConfigOverrideParam in Params.ConfigOverrideParams)
                {
                    CommandletParams += " -";
                    CommandletParams += ConfigOverrideParam;
                }

                CookCommandlet(Params.RawProjectPath, Params.UE4Exe, Maps, Dirs, InternationalizationPreset, CulturesToCook, CombineCommandletParams(PlatformsToCook.ToArray()), CommandletParams);

                SharedCookedBuild.WaitForCopy();
            }
            catch (Exception Ex)
            {
                if (Params.IgnoreCookErrors)
                {
                    LogWarning("Ignoring cook failure.");
                }
                else
                {
                    // Delete cooked data (if any) as it may be incomplete / corrupted.
                    Log("Cook failed. Deleting cooked data.");
                    CleanupCookedData(PlatformsToCook.ToList(), Params);
                    throw new AutomationException(ExitCode.Error_UnknownCookFailure, Ex, "Cook failed.");
                }
            }

            if (Params.HasDiffCookedContentPath)
            {
                try
                {
                    DiffCookedContent(Params);
                }
                catch (Exception Ex)
                {
                    // Delete cooked data (if any) as it may be incomplete / corrupted.
                    Log("Cook failed. Deleting cooked data.");
                    CleanupCookedData(PlatformsToCook.ToList(), Params);
                    throw new AutomationException(ExitCode.Error_UnknownCookFailure, Ex, "Cook failed.");
                }
            }
        }


        Log("********** COOK COMMAND COMPLETED **********");
    }
Пример #38
0
        static void Main(string[] args)
        {
            long graphsize = 0;

            if (args.Length >= 1 && args[0].StartsWith("-s"))
            {
                GraphSlave slave = new GraphSlave();
                slave.Start(true);
            }
            if (args.Length >= 1 && args[0].StartsWith("-p"))
            {
                GraphProxy proxy = new GraphProxy();
                proxy.Start(true);
            }

            if (args.Length >= 1 && args[0].StartsWith("-g"))
            {
                TrinityConfig.CurrentRunningMode = RunningMode.Client;
                for (int i = 1; i <= 5000; i++)
                {
                    Global.CloudStorage.SaveNode(i, id: i, neighbors: new List <long>(), name: Convert.ToString(i), label: Convert.ToString(i % 10), flag: 0);
                }
                Global.CloudStorage.BeginToGraphSlave(0, new BeginSignalWriter(signal: 1));
                HashSet <long> a = new HashSet <long>();
                HashSet <long> b = new HashSet <long>();
                HashSet <long> c = new HashSet <long>();
                HashSet <long> d = new HashSet <long>();
                HashSet <long> e = new HashSet <long>();

                a.Add(5002);
                a.Add(5005);
                Global.CloudStorage.SaveNode(5001, id: 5001, neighbors: a.ToList(), name: "5001", label: "1", flag: 0);

                b.Add(5001);
                b.Add(5003);
                Global.CloudStorage.SaveNode(5002, id: 5002, neighbors: b.ToList(), name: "5002", label: "2", flag: 0);

                c.Add(5002);
                c.Add(5004);
                c.Add(5005);
                Global.CloudStorage.SaveNode(5003, id: 5003, neighbors: c.ToList(), name: "5003", label: "3", flag: 0);

                d.Add(5005);
                d.Add(5003);
                Global.CloudStorage.SaveNode(5004, id: 5004, neighbors: d.ToList(), name: "5004", label: "4", flag: 0);

                e.Add(5001);
                e.Add(5003);
                e.Add(5004);
                Global.CloudStorage.SaveNode(5005, id: 5005, neighbors: e.ToList(), name: "5005", label: "5", flag: 0);


                Global.CloudStorage.SaveNode(10000, id: graphsize, neighbors: new List <long>(), name: Convert.ToString(graphsize), label: Convert.ToString(graphsize % 10), flag: 0);
            }
            if (args.Length >= 1 && args[0].StartsWith("-c"))
            {
                TrinityConfig.CurrentRunningMode = RunningMode.Client;
                //var tmpsize = Global.CloudStorage.LoadNode(10000);

                //graphsize = tmpsize.id;
                //Console.WriteLine("graphsize: {0}", graphsize);
                //NodeSet[] Q = new NodeSet[2];
                //Q[0].set = new List<long>();
                //Q[1].set = new List<long>();

                //Q[0].headid = 5005;
                //Q[0].set.Add(5001);
                //Q[0].set.Add(5003);
                //Q[0].set.Add(5004);

                //Q[1].headid = 5004;
                //Q[1].set.Add(5003);
                //Q[1].set.Add(5001);

                //NodeSet tmp = new NodeSet();
                //tmp = Q[0];
                //ResultReader r = Global.CloudStorage.QueryToGraphProxy(0, new NodeSetWriter(tmp.headid, tmp.headname, tmp.headlabel, tmp.set.ToList()));
                //r.set.ForEach((tmp1) =>
                //{
                //    Console.WriteLine(tmp1.headid);
                //    tmp1.set.ForEach((tmp2) =>
                //    {
                //        Console.Write("{0} ", tmp2);
                //    }
                //    );
                //    Console.WriteLine();
                //    //String s = Console.ReadLine();
                //}
                //    );
                Global.CloudStorage.BeginProxyToGraphProxy(0, new BeginSignalWriter(1));
                Console.ReadLine();
            }
        }
Пример #39
0
        private async Task <ILookup <Guid, IEnrichedContentEntity> > GetReferencesAsync(Context context, HashSet <Guid> ids)
        {
            if (ids.Count == 0)
            {
                return(EmptyContents);
            }

            var references = await ContentQuery.QueryAsync(context.Clone().WithoutContentEnrichment(true), ids.ToList());

            return(references.ToLookup(x => x.Id));
        }
Пример #40
0
        private void _UpdateModsList(bool repo_updated, IEnumerable <ModChange> mc)
        {
            log.Info("Updating the mod list");

            ResetProgress();
            tabController.RenameTab("WaitTabPage", "Loading modules");
            ShowWaitDialog(false);
            tabController.SetTabLock(true);
            Util.Invoke(this, SwitchEnabledState);
            ClearLog();

            AddLogMessage("Loading registry...");
            KspVersionCriteria versionCriteria = CurrentInstance.VersionCriteria();
            IRegistryQuerier   registry        = RegistryManager.Instance(CurrentInstance).registry;

            AddLogMessage("Loading installed modules...");
            var gui_mods = new HashSet <GUIMod>();

            gui_mods.UnionWith(
                registry.InstalledModules
                .Select(instMod => new GUIMod(instMod, registry, versionCriteria))
                );
            AddLogMessage("Loading available modules...");
            gui_mods.UnionWith(
                registry.Available(versionCriteria)
                .Select(m => new GUIMod(m, registry, versionCriteria))
                );
            AddLogMessage("Loading incompatible modules...");
            gui_mods.UnionWith(
                registry.Incompatible(versionCriteria)
                .Select(m => new GUIMod(m, registry, versionCriteria, true))
                );

            if (mc != null)
            {
                AddLogMessage("Restoring change set...");
                foreach (ModChange change in mc)
                {
                    // Propagate IsInstallChecked and IsUpgradeChecked to the next generation
                    gui_mods.FirstOrDefault(
                        mod => mod.Identifier == change.Mod.Identifier
                        )?.SetRequestedChange(change.ChangeType);
                }
            }

            AddLogMessage("Preserving new flags...");
            var old_modules = mainModList.Modules.ToDictionary(m => m, m => m.IsIncompatible);

            if (repo_updated)
            {
                foreach (GUIMod gm in gui_mods)
                {
                    bool oldIncompat;
                    if (old_modules.TryGetValue(gm, out oldIncompat))
                    {
                        // Found it; check if newly compatible
                        if (!gm.IsIncompatible && oldIncompat)
                        {
                            gm.IsNew = true;
                        }
                    }
                    else
                    {
                        // Newly indexed, show regardless of compatibility
                        gm.IsNew = true;
                    }
                }
            }
            else
            {
                //Copy the new mod flag from the old list.
                var old_new_mods = new HashSet <GUIMod>(old_modules.Keys.Where(m => m.IsNew));
                foreach (var gui_mod in gui_mods.Where(m => old_new_mods.Contains(m)))
                {
                    gui_mod.IsNew = true;
                }
            }

            AddLogMessage("Populating mod list...");
            // Update our mod listing
            mainModList.ConstructModList(gui_mods.ToList(), mc, configuration.HideEpochs, configuration.HideV);
            mainModList.Modules = new ReadOnlyCollection <GUIMod>(
                mainModList.full_list_of_mod_rows.Values.Select(row => row.Tag as GUIMod).ToList());

            AddLogMessage("Updating filters...");

            var has_any_updates = gui_mods.Any(mod => mod.HasUpdate);

            //TODO Consider using smart enumeration pattern so stuff like this is easier
            Util.Invoke(menuStrip2, () =>
            {
                FilterToolButton.DropDownItems[0].Text = String.Format("Compatible ({0})",
                                                                       mainModList.CountModsByFilter(GUIModFilter.Compatible));
                FilterToolButton.DropDownItems[1].Text = String.Format("Installed ({0})",
                                                                       mainModList.CountModsByFilter(GUIModFilter.Installed));
                FilterToolButton.DropDownItems[2].Text = String.Format("Upgradeable ({0})",
                                                                       mainModList.CountModsByFilter(GUIModFilter.InstalledUpdateAvailable));
                FilterToolButton.DropDownItems[3].Text = String.Format("Cached ({0})",
                                                                       mainModList.CountModsByFilter(GUIModFilter.Cached));
                FilterToolButton.DropDownItems[4].Text = String.Format("Newly compatible ({0})",
                                                                       mainModList.CountModsByFilter(GUIModFilter.NewInRepository));
                FilterToolButton.DropDownItems[5].Text = String.Format("Not installed ({0})",
                                                                       mainModList.CountModsByFilter(GUIModFilter.NotInstalled));
                FilterToolButton.DropDownItems[6].Text = String.Format("Incompatible ({0})",
                                                                       mainModList.CountModsByFilter(GUIModFilter.Incompatible));
                FilterToolButton.DropDownItems[7].Text = String.Format("All ({0})",
                                                                       mainModList.CountModsByFilter(GUIModFilter.All));

                UpdateAllToolButton.Enabled = has_any_updates;
            });

            UpdateFilters(this);

            AddLogMessage("Updating tray...");
            UpdateTrayInfo();

            HideWaitDialog(true);
            tabController.HideTab("WaitTabPage");
            tabController.SetTabLock(false);
            Util.Invoke(this, SwitchEnabledState);
            Util.Invoke(this, () => Main.Instance.ModList.Focus());
        }
Пример #41
0
 public List <string> GetDirectoryList()
 {
     return(m_directoryList.ToList());
 }
 public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
 {
     PopulateTypeList(context);
     return(new StandardValuesCollection(_typeList.ToList()));
 }
Пример #43
0
        public static void RunPatch(IPatcherState <ISkyrimMod, ISkyrimModGetter> state)
        {
            List <IngrCombination>          combinations = new List <IngrCombination>();
            IEnumerable <IIngredientGetter> ingredients  = state.LoadOrder.PriorityOrder.OnlyEnabled().Ingredient().WinningOverrides();

            ingredients = from ingrs in ingredients where !SkipPlugins.Contains(ingrs.FormKey.ModKey.Name.ToLower()) select ingrs;
            ingredients = from ingrs in ingredients where (!SkipIngrs.Intersect(ingrs.Name?.ToString()?.Split() !).Any() || SkipIngrs.Contains(ingrs.Name?.ToString())) select ingrs;
            ingredients = from ingrs in ingredients where !String.IsNullOrEmpty(ingrs.Name?.String) select ingrs;
            IEnumerator <IIngredientGetter> enumerator = ingredients.GetEnumerator();
            int i       = 0;
            int percent = (int)(ingredients.Count() * outputPercentage);

            while (enumerator.MoveNext())
            {
                sw.Start();
                if (i % percent == 0)
                {
                    Console.WriteLine(i + " out of " + ingredients.Count() + " ingredients processed.");
                }
                List <IIngredientGetter> remainingingr    = ingredients.Skip(i).ToList();
                IIngredientGetter[]      potionRecipeList = getIngredientsMatchingOneIngredient(enumerator.Current, remainingingr);
                if (String.IsNullOrEmpty(enumerator.Current.Name?.String))
                {
                    i++;
                    continue;
                }
                foreach (IIngredientGetter ingr in potionRecipeList)
                {
                    IEnumerable <IEffectGetter> ActiveEffects = ingr.Effects.Intersect(enumerator.Current.Effects).ToArray();
                    ActiveEffects = ActiveEffects.Distinct();
                    IEffectGetter[] ActiveEffectsA = ActiveEffects.ToArray();
                    if (ActiveEffectsA.Length < 1)
                    {
                        continue;
                    }
                    String potionString = "<font face='$HandwrittenFont'><font size='26'>";
                    potionString += "-<b>" + (enumerator.Current.Name + "<br><b>-<b>" + ingr.Name + "</b>");
                    List <String?> mgeflist  = new List <String?>();
                    List <String?> mgeflists = new List <String?>();
                    foreach (IEffectGetter effect in ActiveEffectsA)
                    {
                        state.LinkCache.TryResolve <IMagicEffectGetter>(effect.BaseEffect.FormKey, out var mgeffect);
                        mgeflist.Add(mgeffect?.Name?.String);
                        mgeflists.AddRange(mgeffect?.Name?.String?.Split() !);
                    }
                    String prefix = "Potion";
                    int    type   = 0;
                    if (!mgeflists.Intersect(potionWords.ToList()).Any() && mgeflists.Intersect(poisonWords.ToList()).Any())
                    {
                        prefix = "Poison";
                        type   = 1;
                        if (mgeflist.Count() <= poisonSkipThreshold)
                        {
                            continue;
                        }
                        poisonRecipeCount++;
                    }
                    else if (mgeflists.Intersect(potionWords.ToList()).Any() && mgeflists.Intersect(poisonWords.ToList()).Any())
                    {
                        prefix = "Impure Potion";
                        type   = 2;
                        if (mgeflist.Count() <= impureSkipThreshold)
                        {
                            continue;
                        }
                        impurepotionRecipeCount++;
                    }
                    else
                    {
                        if (mgeflist.Count() <= potionSkipThreshold)
                        {
                            continue;
                        }
                        potionRecipeCount++;
                    }
                    potionString += ("</font><font face='$HandwrittenFont'><font size='18'><br> to make " + prefix + " of ");
                    String potionName = "Recipe: ";
                    for (int k = 0; k < mgeflist.Count(); k++)
                    {
                        if (k > 0)
                        {
                            potionName   += " and ";
                            potionString += ("<br>");
                        }
                        potionName   += mgeflist[k];
                        potionString += (mgeflist[k]);
                    }
                    String sstring = "";

                    if (mgeflist.Count() > 1)
                    {
                        sstring = "s";
                    }

                    potionString += ("<br></font><font size='14'> Contains " + mgeflist.Count() + " Effect" + sstring);
                    potionString += "<\\font>";
                    IIngredientGetter[] ingrss = { enumerator.Current, ingr };
                    combinations.Add(new IngrCombination(potionName, ingrss, mgeflist?.ToArray() !, potionString, type));
                }
                int j = i + 1;
                IEnumerator <IIngredientGetter> enumerator2 = remainingingr.GetEnumerator();
                while (enumerator2.MoveNext())
                {
                    if (enumerator2.Current.Name?.Equals(enumerator.Current.Name) ?? true || String.IsNullOrEmpty(enumerator2.Current.Name?.String) || !enumerator.Current.Effects.Intersect(enumerator2.Current.Effects).Any())
                    {
                        j++;
                        continue;
                    }
                    List <IIngredientGetter> remainingingr2    = ingredients.Skip(j).ToList();
                    IIngredientGetter[]      potionRecipeList2 = getIngredientsMatchingTwoIngredients(enumerator.Current, enumerator2.Current, remainingingr2);
                    foreach (IIngredientGetter ingr in potionRecipeList2)
                    {
                        IEnumerable <IEffectGetter> ActiveEffects  = ingr.Effects.Intersect(enumerator.Current.Effects);
                        IEnumerable <IEffectGetter> ActiveEffects2 = ingr.Effects.Intersect(enumerator2.Current.Effects);
                        IEnumerable <IEffectGetter> ActiveEffects3 = enumerator.Current.Effects.Intersect(enumerator2.Current.Effects);
                        ActiveEffects.ToList().AddRange(ActiveEffects2);
                        ActiveEffects.ToList().AddRange(ActiveEffects3);
                        ActiveEffects = ActiveEffects.Distinct();
                        IEffectGetter[] ActiveEffectsA = ActiveEffects.ToArray();
                        if (ActiveEffectsA.Length < 1)
                        {
                            continue;
                        }
                        String potionString = "<font face='$HandwrittenFont'><font size='26'>";
                        potionString += "-<b>" + (enumerator.Current.Name + "<br></b>-<b>" + enumerator2.Current.Name + "<br></b>-<b>" + ingr.Name + "</b>");
                        List <String?> mgeflist  = new List <String?>();
                        List <String?> mgeflists = new List <String?>();
                        foreach (IEffectGetter effect in ActiveEffects)
                        {
                            state.LinkCache.TryResolve <IMagicEffectGetter>(effect.BaseEffect.FormKey, out var mgeffect);
                            mgeflist.Add(mgeffect?.Name?.String);
                            mgeflists.AddRange(mgeffect?.Name?.String?.Split() !);
                        }
                        String prefix = "Potion";
                        int    type   = 0;
                        if (!mgeflists.Intersect(potionWords.ToList()).Any() && mgeflists.Intersect(poisonWords.ToList()).Any())
                        {
                            prefix = "Poison";
                            type   = 1;
                            if (mgeflist.Count() <= poisonSkipThreshold)
                            {
                                continue;
                            }
                            poisonRecipeCount++;
                        }
                        else if (mgeflist.Intersect(potionWords.ToList()).Any() && mgeflists.Intersect(poisonWords.ToList()).Any())
                        {
                            prefix = "Impure Potion";
                            type   = 2;
                            if (mgeflists.Count() <= impureSkipThreshold)
                            {
                                continue;
                            }
                            impurepotionRecipeCount++;
                        }
                        else
                        {
                            if (mgeflist.Count() <= potionSkipThreshold)
                            {
                                continue;
                            }
                            potionRecipeCount++;
                        }
                        potionString += ("</font><font face='$HandwrittenFont'><font size='18'><br> to make " + prefix + " of: <br></font><font face='$HandwrittenFont'><font size='26'>");
                        String potionName = "Recipe: ";
                        for (int k = 0; k < mgeflist.Count(); k++)
                        {
                            if (k > 0)
                            {
                                potionName   += " and ";
                                potionString += ("<br>");
                            }
                            potionName   += mgeflist[k];
                            potionString += (mgeflist[k]);
                        }
                        String sstring = "";

                        if (mgeflist.Count() > 1)
                        {
                            sstring = "s";
                        }
                        potionString += ("<br></font><font size='14'> Contains " + mgeflist.Count() + " Effect" + sstring);
                        potionString += "<\\font>";
                        IIngredientGetter[] ingrss = { enumerator.Current, enumerator2.Current, ingr };
                        combinations.Add(new IngrCombination(potionName, ingrss, mgeflist?.ToArray() !, potionString, type));
                    }
                    j++;
                }
                i++;
                if (i % percent == 0)
                {
                    sw.Stop();
                    Console.WriteLine("time elapsed:  " + sw.Elapsed.TotalSeconds + " seconds");
                    sw.Reset();
                }
            }
            Console.WriteLine("Creating Leveled lists...");
            IEnumerable <IBookGetter> books = from book in state.LoadOrder.PriorityOrder.Book().WinningOverrides() where book.FormKey.Equals(new FormKey(new ModKey("Skyrim", ModType.Master), 0x0F5CB1)) select book;
            IBookGetter noteTemplate        = books.ToList()[0];

            Console.WriteLine("Creating " + combinations.Count() + " recipes.");
            percent = (int)(combinations.Count() * outputPercentage);
            i       = 0;
            /* Main leveled list that gets added to recipe drop */
            LeveledItem      mainpotionRecipeLVLI      = state.PatchMod.LeveledItems.AddNew();
            LeveledItemEntry mainpotionRecipeLVLIentry = new LeveledItemEntry();

            mainpotionRecipeLVLI.Entries = new Noggog.ExtendedList <LeveledItemEntry>();
            LeveledItemEntryData mainpotionRecipeLVLIentrydata = new LeveledItemEntryData();
            GlobalInt            mainpotionGlobal = new GlobalInt(state.PatchMod.GetNextFormKey(), SkyrimRelease.SkyrimSE);

            mainpotionGlobal.Data = new Random().Next(minChance, maxChance);
            state.PatchMod.Globals.Set(mainpotionGlobal);
            mainpotionRecipeLVLI.Global   = mainpotionGlobal;
            mainpotionRecipeLVLI.EditorID = "mainpotionRecipeList";
            /* Must split sub leveled lists because it can only hold 128 items */
            uint potionRecipeListCount       = (potionRecipeCount / 128) + 1;
            uint poisonRecipeListCount       = (poisonRecipeCount / 128) + 1;
            uint impurepotionRecipeListCount = (impurepotionRecipeCount / 128) + 1;

            LeveledItem[] potionRecipeLVLIs           = new LeveledItem[potionRecipeListCount];
            uint          masterpotionRecipeListCount = ((potionRecipeListCount + poisonRecipeListCount + impurepotionRecipeListCount) / 128) + 1;

            LeveledItem[]          masterpotionRecipeLVLIs           = new LeveledItem[masterpotionRecipeListCount];
            LeveledItemEntry[]     masterpotionRecipeLVLIentries     = new LeveledItemEntry[masterpotionRecipeListCount];
            LeveledItemEntryData[] masterpotionRecipeLVLIentriesdata = new LeveledItemEntryData[masterpotionRecipeListCount];
            GlobalInt[]            masterpotionGlobals         = new GlobalInt[masterpotionRecipeListCount];
            LeveledItemEntry[]     potionRecipeLVLIentries     = new LeveledItemEntry[potionRecipeListCount];
            LeveledItemEntryData[] potionRecipeLVLIentriesdata = new LeveledItemEntryData[potionRecipeListCount];
            GlobalInt[]            potionGlobals = new GlobalInt[potionRecipeListCount];
            for (int k = 0; k < masterpotionRecipeListCount; k++)
            {
                masterpotionRecipeLVLIentries[k]     = new LeveledItemEntry();
                masterpotionRecipeLVLIentriesdata[k] = new LeveledItemEntryData();
                masterpotionRecipeLVLIs[k]           = state.PatchMod.LeveledItems.AddNew();
                masterpotionRecipeLVLIs[k].Entries   = new Noggog.ExtendedList <LeveledItemEntry>();
                masterpotionGlobals[k]      = new GlobalInt(state.PatchMod.GetNextFormKey(), SkyrimRelease.SkyrimSE);
                masterpotionGlobals[k].Data = new Random().Next(5, 25);
                state.PatchMod.Globals.Set(masterpotionGlobals[k]);
                masterpotionRecipeLVLIs[k].Global              = masterpotionGlobals[k];
                masterpotionRecipeLVLIs[k].EditorID            = "masterpotionRecipeList" + k;
                masterpotionRecipeLVLIentriesdata[k].Reference = masterpotionRecipeLVLIs[k].FormKey;
                masterpotionRecipeLVLIentriesdata[k].Level     = 1;
                masterpotionRecipeLVLIentriesdata[k].Count     = 1;
            }
            for (int l = 0; l < potionRecipeListCount; l++)
            {
                potionRecipeLVLIentries[l]     = new LeveledItemEntry();
                potionRecipeLVLIentriesdata[l] = new LeveledItemEntryData();
                potionRecipeLVLIs[l]           = state.PatchMod.LeveledItems.AddNew();
                potionRecipeLVLIs[l].Entries   = new Noggog.ExtendedList <LeveledItemEntry>();
                potionGlobals[l]      = new GlobalInt(state.PatchMod.GetNextFormKey(), SkyrimRelease.SkyrimSE);
                potionGlobals[l].Data = new Random().Next(5, 25);
                state.PatchMod.Globals.Set(potionGlobals[l]);
                potionRecipeLVLIs[i].Global              = potionGlobals[l];
                potionRecipeLVLIs[l].EditorID            = "potionRecipeList" + l;
                potionRecipeLVLIentriesdata[l].Reference = potionRecipeLVLIs[l].FormKey;
                potionRecipeLVLIentriesdata[l].Level     = 1;
                potionRecipeLVLIentriesdata[l].Count     = 1;
            }
            LeveledItem[]          poisonRecipeLVLIs           = new LeveledItem[poisonRecipeListCount];
            LeveledItemEntry[]     poisonRecipeLVLIentries     = new LeveledItemEntry[poisonRecipeListCount];
            LeveledItemEntryData[] poisonRecipeLVLIentriesdata = new LeveledItemEntryData[poisonRecipeListCount];
            GlobalInt[]            poisonGlobals = new GlobalInt[poisonRecipeListCount];
            for (int l = 0; l < poisonRecipeListCount; l++)
            {
                poisonRecipeLVLIentries[l]     = new LeveledItemEntry();
                poisonRecipeLVLIentriesdata[l] = new LeveledItemEntryData();
                poisonRecipeLVLIs[l]           = state.PatchMod.LeveledItems.AddNew();
                poisonRecipeLVLIs[l].Entries   = new Noggog.ExtendedList <LeveledItemEntry>();
                poisonGlobals[l]      = new GlobalInt(state.PatchMod.GetNextFormKey(), SkyrimRelease.SkyrimSE);
                poisonGlobals[l].Data = new Random().Next(5, 25);
                state.PatchMod.Globals.Set(poisonGlobals[l]);
                poisonRecipeLVLIs[i].Global              = poisonGlobals[l];
                poisonRecipeLVLIs[l].EditorID            = "poisonRecipeList" + l;
                poisonRecipeLVLIentriesdata[l].Reference = poisonRecipeLVLIs[l].FormKey;
                poisonRecipeLVLIentriesdata[l].Level     = 1;
                poisonRecipeLVLIentriesdata[l].Count     = 1;
            }
            LeveledItem[]          impurepotionRecipeLVLIs           = new LeveledItem[impurepotionRecipeListCount];
            LeveledItemEntry[]     impurepotionRecipeLVLIentries     = new LeveledItemEntry[impurepotionRecipeListCount];
            LeveledItemEntryData[] impurepotionRecipeLVLIentriesdata = new LeveledItemEntryData[impurepotionRecipeListCount];
            GlobalInt[]            impurepotionGlobals = new GlobalInt[impurepotionRecipeListCount];
            for (int l = 0; l < impurepotionRecipeListCount; l++)
            {
                impurepotionRecipeLVLIentries[l]     = new LeveledItemEntry();
                impurepotionRecipeLVLIentriesdata[l] = new LeveledItemEntryData();
                impurepotionRecipeLVLIs[l]           = state.PatchMod.LeveledItems.AddNew();
                impurepotionRecipeLVLIs[l].Entries   = new Noggog.ExtendedList <LeveledItemEntry>();
                impurepotionGlobals[l]      = new GlobalInt(state.PatchMod.GetNextFormKey(), SkyrimRelease.SkyrimSE);
                impurepotionGlobals[l].Data = new Random().Next(5, 25);
                state.PatchMod.Globals.Set(impurepotionGlobals[l]);
                impurepotionRecipeLVLIs[i].Global              = impurepotionGlobals[l];
                impurepotionRecipeLVLIs[l].EditorID            = "impurepotionRecipeList" + l;
                impurepotionRecipeLVLIentriesdata[l].Reference = impurepotionRecipeLVLIs[l].FormKey;
                impurepotionRecipeLVLIentriesdata[l].Level     = 1;
                impurepotionRecipeLVLIentriesdata[l].Count     = 1;
            }
            Console.WriteLine("Splitting potions into lists (" + potionRecipeListCount + " " + poisonRecipeListCount + " " + impurepotionRecipeListCount + ")");
            uint potionIndex = 0, poisonIndex = 0, impurepotionIndex = 0;

            IEffectGetter[]          effectCache       = getAllEffects(ingredients).ToArray();
            Dictionary <String, int> nameCache         = new Dictionary <String, int>();

            foreach (IngrCombination ic in combinations)
            {
                if (i % percent == 0)
                {
                    Console.WriteLine(i + " out of " + combinations.Count() + " recipes created.");
                }
                IBook newRecipe = noteTemplate.DeepCopy();
                newRecipe.FormKey     = state.PatchMod.GetNextFormKey();
                newRecipe.Description = ic.RecipeName;
                newRecipe.Name        = ic.RecipeName;
                newRecipe.BookText    = ic.PotionString;
                newRecipe.Weight      = recipeWeight;
                String?name = "recipeof";
                foreach (String?s in ic.MyEffects !)
                {
                    name += s;
                }
                name = name.Replace(" ", String.Empty);
                int nameIndex = 0;
                if (nameCache.TryGetValue(name, out nameIndex))
                {
                    nameCache[name] = nameIndex + 1;
                    name            = name + nameCache[name];
                }
                else
                {
                    nameCache.Add(name, 0);
                    name = name + "0";
                }
                newRecipe.EditorID = name;
                state.PatchMod.Books.Set((Book)newRecipe);
                LeveledItemEntry     lie  = new LeveledItemEntry();
                LeveledItemEntryData data = new LeveledItemEntryData();
                data.Level     = 1;
                data.Count     = 1;
                data.Reference = new FormLink <IItemGetter>(newRecipe.FormKey);
                lie.Data       = data;
                switch (ic.Type)
                {
                case 0:
                    potionRecipeLVLIentriesdata[potionIndex / 128].Reference = potionRecipeLVLIs[potionIndex / 128].FormKey;
                    potionRecipeLVLIentries[potionIndex / 128].Data          = potionRecipeLVLIentriesdata[potionIndex / 128];
                    potionRecipeLVLIs[potionIndex / 128].Entries?.Add(lie);
                    potionIndex++;
                    break;

                case 1:
                    poisonRecipeLVLIentriesdata[poisonIndex / 128].Reference = poisonRecipeLVLIs[poisonIndex / 128].FormKey;
                    poisonRecipeLVLIentries[poisonIndex / 128].Data          = poisonRecipeLVLIentriesdata[poisonIndex / 128];
                    poisonRecipeLVLIs[poisonIndex / 128].Entries?.Add(lie);
                    poisonIndex++;
                    break;

                case 2:
                    impurepotionRecipeLVLIentriesdata[impurepotionIndex / 128].Reference = impurepotionRecipeLVLIs[impurepotionIndex / 128].FormKey;
                    impurepotionRecipeLVLIentries[impurepotionIndex / 128].Data          = impurepotionRecipeLVLIentriesdata[impurepotionIndex / 128];
                    impurepotionRecipeLVLIs[impurepotionIndex / 128].Entries?.Add(lie);
                    impurepotionIndex++;
                    break;
                }
                i++;
            }

            Console.WriteLine("Linking recipes to potion leveled list");
            IEnumerable <ILeveledItemGetter> lvlilists = from list in state.LoadOrder.PriorityOrder.OnlyEnabled().LeveledItem().WinningOverrides() where list.EditorID?.Equals("LItemPotionAll") ?? true select list;
            ILeveledItemGetter allList                 = lvlilists.ToList()[0];
            LeveledItem        modifiedList            = state.PatchMod.LeveledItems.GetOrAddAsOverride(allList);

            potionIndex       = 0;
            poisonIndex       = 0;
            impurepotionIndex = 0;
            for (int l = 0; l < masterpotionRecipeListCount; l++)
            {
                masterpotionRecipeLVLIentriesdata[l].Reference = masterpotionRecipeLVLIs[l].FormKey;
                masterpotionRecipeLVLIentries[l].Data          = masterpotionRecipeLVLIentriesdata[l];
                for (int k = 0; k < 128; k++)
                {
                    if (potionIndex < potionRecipeLVLIentries.Count())
                    {
                        masterpotionRecipeLVLIs[l].Entries?.Add(potionRecipeLVLIentries[potionIndex++]);
                    }
                    else if (poisonIndex < poisonRecipeLVLIentries.Count())
                    {
                        masterpotionRecipeLVLIs[l].Entries?.Add(poisonRecipeLVLIentries[poisonIndex++]);
                    }
                    else if (impurepotionIndex < impurepotionRecipeLVLIentries.Count())
                    {
                        masterpotionRecipeLVLIs[l].Entries?.Add(impurepotionRecipeLVLIentries[impurepotionIndex++]);
                    }
                    else
                    {
                        break;
                    }
                }
                mainpotionRecipeLVLI.Entries?.Add(masterpotionRecipeLVLIentries[l]);
            }
            foreach (LeveledItem li in potionRecipeLVLIs)
            {
                state.PatchMod.LeveledItems.Set(li);
            }
            foreach (LeveledItem li in poisonRecipeLVLIs)
            {
                state.PatchMod.LeveledItems.Set(li);
            }
            foreach (LeveledItem li in impurepotionRecipeLVLIs)
            {
                state.PatchMod.LeveledItems.Set(li);
            }
            foreach (LeveledItem li in masterpotionRecipeLVLIs)
            {
                state.PatchMod.LeveledItems.Set(li);
            }

            mainpotionRecipeLVLIentrydata.Reference = mainpotionRecipeLVLI.FormKey;
            mainpotionRecipeLVLIentry.Data          = mainpotionRecipeLVLIentrydata;
            mainpotionRecipeLVLIentrydata.Count     = 1;
            mainpotionRecipeLVLIentrydata.Level     = 1;
            modifiedList.Entries?.Add(mainpotionRecipeLVLIentry);
            state.PatchMod.LeveledItems.Set(mainpotionRecipeLVLI);
            Console.WriteLine("Adding recipes to defined containers");
            IEnumerable <IContainerGetter> chests   = from list in state.LoadOrder.PriorityOrder.OnlyEnabled().Container().WinningOverrides() where containerEditorIDs?.ToList().Contains(list.EditorID !) ?? true select list;
            ContainerEntry potionListContainerEntry = new ContainerEntry();
            ContainerItem  potionListContainerItem  = new ContainerItem();

            potionListContainerItem.Item  = mainpotionRecipeLVLI.FormKey;
            potionListContainerItem.Count = 1;
            potionListContainerEntry.Item = potionListContainerItem;
            foreach (IContainerGetter chest in chests)
            {
                Container rChest = state.PatchMod.Containers.GetOrAddAsOverride(chest);
                rChest.Items?.Add(potionListContainerEntry);
            }
        }
Пример #44
0
 public static List <Type> AvailableTypesByStaticCache()
 {
     return(AvailableTypesInner.ToList());
 }
Пример #45
0
    public static void Cook(ProjectParams Params)
    {
        if ((!Params.Cook && !(Params.CookOnTheFly && !Params.SkipServer)) || Params.SkipCook)
        {
            return;
        }
        Params.ValidateAndLog();

        Log("********** COOK COMMAND STARTED **********");

        string UE4EditorExe = HostPlatform.Current.GetUE4ExePath(Params.UE4Exe);

        if (!FileExists(UE4EditorExe))
        {
            throw new AutomationException("Missing " + UE4EditorExe + " executable. Needs to be built first.");
        }

        if (Params.CookOnTheFly && !Params.SkipServer)
        {
            if (Params.HasDLCName)
            {
                throw new AutomationException("Cook on the fly doesn't support cooking dlc");
            }
            if (Params.ClientTargetPlatforms.Count > 0)
            {
                var LogFolderOutsideOfSandbox = GetLogFolderOutsideOfSandbox();
                if (!GlobalCommandLine.Installed)
                {
                    // In the installed runs, this is the same folder as CmdEnv.LogFolder so delete only in not-installed
                    DeleteDirectory(LogFolderOutsideOfSandbox);
                    CreateDirectory(LogFolderOutsideOfSandbox);
                }
                var      ServerLogFile      = CombinePaths(LogFolderOutsideOfSandbox, "Server.log");
                Platform ClientPlatformInst = Params.ClientTargetPlatformInstances[0];
                string   TargetCook         = ClientPlatformInst.GetCookPlatform(false, Params.HasDedicatedServerAndClient, Params.CookFlavor);
                ServerProcess = RunCookOnTheFlyServer(Params.RawProjectPath, Params.NoClient ? "" : ServerLogFile, TargetCook, Params.RunCommandline);

                if (ServerProcess != null)
                {
                    Log("Waiting a few seconds for the server to start...");
                    Thread.Sleep(5000);
                }
            }
            else
            {
                throw new AutomationException("Failed to run, client target platform not specified");
            }
        }
        else
        {
            var PlatformsToCook = new HashSet <string>();

            if (!Params.NoClient)
            {
                foreach (var ClientPlatform in Params.ClientTargetPlatforms)
                {
                    // Use the data platform, sometimes we will copy another platform's data
                    var DataPlatform = Params.GetCookedDataPlatformForClientTarget(ClientPlatform);
                    PlatformsToCook.Add(Params.GetTargetPlatformInstance(DataPlatform).GetCookPlatform(false, Params.HasDedicatedServerAndClient, Params.CookFlavor));
                }
            }
            if (Params.DedicatedServer)
            {
                foreach (var ServerPlatform in Params.ServerTargetPlatforms)
                {
                    // Use the data platform, sometimes we will copy another platform's data
                    var DataPlatform = Params.GetCookedDataPlatformForServerTarget(ServerPlatform);
                    PlatformsToCook.Add(Params.GetTargetPlatformInstance(DataPlatform).GetCookPlatform(true, false, Params.CookFlavor));
                }
            }

            if (Params.Clean.HasValue && Params.Clean.Value && !Params.IterativeCooking)
            {
                Log("Cleaning cooked data.");
                CleanupCookedData(PlatformsToCook.ToList(), Params);
            }

            // cook the set of maps, or the run map, or nothing
            string[] Maps = null;
            if (Params.HasMapsToCook)
            {
                Maps = Params.MapsToCook.ToArray();
                foreach (var M in Maps)
                {
                    Log("HasMapsToCook " + M.ToString());
                }
                foreach (var M in Params.MapsToCook)
                {
                    Log("Params.HasMapsToCook " + M.ToString());
                }
            }

            string[] Dirs = null;
            if (Params.HasDirectoriesToCook)
            {
                Dirs = Params.DirectoriesToCook.ToArray();
            }

            string InternationalizationPreset = null;
            if (Params.HasInternationalizationPreset)
            {
                InternationalizationPreset = Params.InternationalizationPreset;
            }

            string[] Cultures = null;
            if (Params.HasCulturesToCook)
            {
                Cultures = Params.CulturesToCook.ToArray();
            }

            try
            {
                var CommandletParams = "-buildmachine -fileopenlog";
                if (Params.UnversionedCookedContent)
                {
                    CommandletParams += " -unversioned";
                }
                if (Params.UseDebugParamForEditorExe)
                {
                    CommandletParams += " -debug";
                }
                if (Params.Manifests)
                {
                    CommandletParams += " -manifests";
                }
                if (Params.IterativeCooking)
                {
                    CommandletParams += " -iterate";
                }
                if (Params.CookMapsOnly)
                {
                    CommandletParams += " -mapsonly";
                }
                if (Params.NewCook)
                {
                    CommandletParams += " -newcook";
                }
                if (Params.OldCook)
                {
                    CommandletParams += " -oldcook";
                }
                if (Params.CookAll)
                {
                    CommandletParams += " -cookall";
                }
                if (Params.CookMapsOnly)
                {
                    CommandletParams += " -mapsonly";
                }
                if (Params.HasCreateReleaseVersion)
                {
                    CommandletParams += " -createreleaseversion=" + Params.CreateReleaseVersion;
                }
                if (Params.HasBasedOnReleaseVersion)
                {
                    CommandletParams += " -basedonreleaseversion=" + Params.BasedOnReleaseVersion;
                }
                if (Params.HasDLCName)
                {
                    CommandletParams += " -dlcname=" + Params.DLCName;
                }
                // if we are not going to pak but we specified compressed then compress in the cooker ;)
                // otherwise compress the pak files
                if (!Params.Pak && !Params.SkipPak && Params.Compressed)
                {
                    CommandletParams += " -compressed";
                }
                if (Params.HasAdditionalCookerOptions)
                {
                    string FormatedAdditionalCookerParams = Params.AdditionalCookerOptions.TrimStart(new char[] { '\"', ' ' }).TrimEnd(new char[] { '\"', ' ' });
                    CommandletParams += FormatedAdditionalCookerParams;
                }
                CookCommandlet(Params.RawProjectPath, Params.UE4Exe, Maps, Dirs, InternationalizationPreset, Cultures, CombineCommandletParams(PlatformsToCook.ToArray()), CommandletParams);
            }
            catch (Exception Ex)
            {
                // Delete cooked data (if any) as it may be incomplete / corrupted.
                Log("Cook failed. Deleting cooked data.");
                CleanupCookedData(PlatformsToCook.ToList(), Params);
                AutomationTool.ErrorReporter.Error("Cook failed.", (int)AutomationTool.ErrorCodes.Error_UnknownCookFailure);
                throw Ex;
            }
        }

        Log("********** COOK COMMAND COMPLETED **********");
    }
Пример #46
0
    public override void Render(TimeSpan delta)
    {
        this.Clear();
        int x = 5;
        int y = 5;

        this.Print(x, y, hint, Color.White, Color.Black);
        y++;
        if (Choices.Count > 0)
        {
            string UP   = ((char)24).ToString();
            string LEFT = ((char)27).ToString();
            this.Print(x, y, "    ", foreground: Color.White, background: Color.Black);
            if (CanScrollUp)
            {
                this.Print(x, y, UP, Color.White, Color.Black);
                if (CanPageUp)
                {
                    this.Print(x + 2, y, LEFT, Color.White, Color.Black);
                }
                this.Print(x + 4, y, startIndex.ToString(), Color.White, Color.Black);
            }
            else
            {
                this.Print(x, y, "-", Color.White, Color.Black);
            }
            y++;

            List <ListChoice <T> > list = Choices.ToList();
            for (int i = startIndex; i < startIndex + 26; i++)
            {
                if (i < Choices.Count)
                {
                    char binding = (char)('a' + (i - startIndex));
                    this.Print(x, y, "" + binding, Color.LimeGreen, Color.Black);
                    this.Print(x + 1, y, " ", Color.Black, Color.Black);
                    this.Print(x + 2, y, list[i].GetSymbolCenter().ToColoredString());
                    this.Print(x + 3, y, " ", Color.Black, Color.Black);
                    this.Print(x + 4, y, list[i].GetName());
                }
                else
                {
                    this.Print(x, y, ".", Color.Gray, Color.Black);
                }
                y++;
            }

            string DOWN  = ((char)25).ToString();
            string RIGHT = ((char)26).ToString();
            this.Print(x, y, "    ", foreground: Color.White, background: Color.Black);
            if (CanScrollDown)
            {
                this.Print(x, y, DOWN, Color.White, Color.Black);
                if (CanPageDown)
                {
                    this.Print(x + 2, y, RIGHT, Color.White, Color.Black);
                }
                this.Print(x + 4, y, ((Choices.Count - 26) - startIndex).ToString(), Color.White, Color.Black);
            }
            else
            {
                this.Print(x, y, "-", Color.White, Color.Black);
            }

            y++;
        }
        else
        {
            this.Print(x, y, "There is nothing here.", Color.Red, Color.Black);
        }

        base.Render(delta);
    }
Пример #47
0
		// Draw event
		// Subtractions within location vectors are to set the origin to the center of the sprite
		public void DrawMarkers(SpriteBatch b)
		{
			if (Config.ShowFarmBuildings && FarmBuildings != null)
			{
				var sortedBuildings = ModMain.FarmBuildings.ToList();
				sortedBuildings.Sort((x, y) => x.Value.Value.Y.CompareTo(y.Value.Value.Y));

				foreach (KeyValuePair<string, KeyValuePair<string, Vector2>> building in sortedBuildings)
				{
					if (ModConstants.FarmBuildingRects.TryGetValue(building.Value.Key, out Rectangle buildingRect))
						b.Draw(BuildingMarkers,
							new Vector2(building.Value.Value.X - buildingRect.Width / 2,
								building.Value.Value.Y - buildingRect.Height / 2), new Rectangle?(buildingRect), Color.White, 0f,
							Vector2.Zero, 3f, SpriteEffects.None, 1f);
				}
			}

			// Traveling Merchant
			if (Config.ShowTravelingMerchant && SecondaryNpcs["Merchant"])
			{
				Vector2 merchantLoc = ModMain.LocationToMap("Forest", 28, 11);
				b.Draw(Game1.mouseCursors, new Vector2(merchantLoc.X - 16, merchantLoc.Y - 15),
					new Rectangle?(new Rectangle(191, 1410, 22, 21)), Color.White, 0f, Vector2.Zero, 1.3f, SpriteEffects.None,
					1f);
			}

			// Farmers
			if (Context.IsMultiplayer)
			{
				foreach (Farmer farmer in Game1.getOnlineFarmers())
				{
					// Temporary solution to handle desync of farmhand location/tile position when changing location
					if (FarmerMarkers.TryGetValue(farmer.UniqueMultiplayerID, out FarmerMarker farMarker))
						if (farMarker.DrawDelay == 0)
							farmer.FarmerRenderer.drawMiniPortrat(b,
								new Vector2(farMarker.Location.X - 16, farMarker.Location.Y - 15), 0.00011f, 2f, 1, farmer);
				}
			}
			else
			{
				Vector2 playerLoc = ModMain.GetMapPosition(Game1.player.currentLocation, Game1.player.getTileX(),
					Game1.player.getTileY());
				Game1.player.FarmerRenderer.drawMiniPortrat(b, new Vector2(playerLoc.X - 16, playerLoc.Y - 15), 0.00011f, 2f, 1,
					Game1.player);
			}

			// NPCs
			// Sort by drawing order
			var sortedMarkers = NpcMarkers.ToList();
			sortedMarkers.Sort((x, y) => x.Layer.CompareTo(y.Layer));

			foreach (NpcMarker npcMarker in sortedMarkers)
			{
				// Skip if no specified location
				if (npcMarker.Location == Rectangle.Empty || npcMarker.Marker == null ||
				    !MarkerCropOffsets.ContainsKey(npcMarker.Npc.Name))
				{
					continue;
				}

				// Tint/dim hidden markers
				if (npcMarker.IsHidden)
				{
					b.Draw(npcMarker.Marker, npcMarker.Location,
						new Rectangle?(new Rectangle(0, MarkerCropOffsets[npcMarker.Npc.Name], 16, 15)), Color.DimGray * 0.7f);
					if (npcMarker.IsBirthday)
          {
						// Gift icon
						b.Draw(Game1.mouseCursors, new Vector2(npcMarker.Location.X + 20, npcMarker.Location.Y),
							new Rectangle?(new Rectangle(147, 412, 10, 11)), Color.DimGray * 0.7f, 0f, Vector2.Zero, 1.8f,
							SpriteEffects.None, 0f);
					}
					if (npcMarker.HasQuest)
					{
						// Quest icon
						b.Draw(Game1.mouseCursors, new Vector2(npcMarker.Location.X + 22, npcMarker.Location.Y - 3),
							new Rectangle?(new Rectangle(403, 496, 5, 14)), Color.DimGray * 0.7f, 0f, Vector2.Zero, 1.8f,
							SpriteEffects.None, 0f);
					}
				}
				else
				{
					b.Draw(npcMarker.Marker, npcMarker.Location,
						new Rectangle?(new Rectangle(0, MarkerCropOffsets[npcMarker.Npc.Name], 16, 15)), Color.White);
					if (npcMarker.IsBirthday)
					{
						// Gift icon
            b.Draw(Game1.mouseCursors, new Vector2(npcMarker.Location.X + 20, npcMarker.Location.Y),
							new Rectangle?(new Rectangle(147, 412, 10, 11)), Color.White, 0f, Vector2.Zero, 1.8f, SpriteEffects.None,
							0f);
					}
					if (npcMarker.HasQuest)
					{
						// Quest icon
            b.Draw(Game1.mouseCursors, new Vector2(npcMarker.Location.X + 22, npcMarker.Location.Y - 3),
							new Rectangle?(new Rectangle(403, 496, 5, 14)), Color.White, 0f, Vector2.Zero, 1.8f, SpriteEffects.None,
							0f);
					}
				}
			}
		}
Пример #48
0
        /// <summary>
        /// Applies universe selection the the data feed and algorithm
        /// </summary>
        /// <param name="universe">The universe to perform selection on</param>
        /// <param name="dateTimeUtc">The current date time in utc</param>
        /// <param name="universeData">The data provided to perform selection with</param>
        public SecurityChanges  ApplyUniverseSelection(Universe universe, DateTime dateTimeUtc, BaseDataCollection universeData)
        {
            var algorithmEndDateUtc = _algorithm.EndDate.ConvertToUtc(_algorithm.TimeZone);

            if (dateTimeUtc > algorithmEndDateUtc)
            {
                return(SecurityChanges.None);
            }

            IEnumerable <Symbol> selectSymbolsResult;

            // check if this universe must be filtered with fine fundamental data
            var fineFiltered = universe as FineFundamentalFilteredUniverse;

            if (fineFiltered != null)
            {
                // perform initial filtering and limit the result
                selectSymbolsResult = universe.SelectSymbols(dateTimeUtc, universeData);

                if (!ReferenceEquals(selectSymbolsResult, Universe.Unchanged))
                {
                    // prepare a BaseDataCollection of FineFundamental instances
                    var fineCollection = new BaseDataCollection();
                    var dataProvider   = new DefaultDataProvider();

                    // use all available threads, the entire system is waiting for this to complete
                    var options = new ParallelOptions {
                        MaxDegreeOfParallelism = Environment.ProcessorCount
                    };
                    Parallel.ForEach(selectSymbolsResult, options, symbol =>
                    {
                        var config = FineFundamentalUniverse.CreateConfiguration(symbol);

                        var exchangeHours    = _marketHoursDatabase.GetEntry(symbol.ID.Market, symbol, symbol.ID.SecurityType).ExchangeHours;
                        var symbolProperties = _symbolPropertiesDatabase.GetSymbolProperties(symbol.ID.Market, symbol, symbol.ID.SecurityType, CashBook.AccountCurrency);
                        var quoteCash        = _algorithm.Portfolio.CashBook[symbolProperties.QuoteCurrency];

                        var security = new Equity(symbol, exchangeHours, quoteCash, symbolProperties);

                        var localStartTime = dateTimeUtc.ConvertFromUtc(exchangeHours.TimeZone).AddDays(-1);
                        var factory        = new FineFundamentalSubscriptionEnumeratorFactory(_algorithm.LiveMode, x => new[] { localStartTime });
                        var request        = new SubscriptionRequest(true, universe, security, new SubscriptionDataConfig(config), localStartTime, localStartTime);
                        using (var enumerator = factory.CreateEnumerator(request, dataProvider))
                        {
                            if (enumerator.MoveNext())
                            {
                                lock (fineCollection.Data)
                                {
                                    fineCollection.Data.Add(enumerator.Current);
                                }
                            }
                        }
                    });

                    // WARNING -- HACK ATTACK -- WARNING
                    // Fine universes are considered special due to their chaining behavior.
                    // As such, we need a means of piping the fine data read in here back to the data feed
                    // so that it can be properly emitted via a TimeSlice.Create call. There isn't a mechanism
                    // in place for this function to return such data. The following lines are tightly coupled
                    // to the universeData dictionaries in SubscriptionSynchronizer and LiveTradingDataFeed and
                    // rely on reference semantics to work.

                    // Coarse raw data has SID collision on: CRHCY R735QTJ8XC9X
                    var coarseData = universeData.Data.OfType <CoarseFundamental>()
                                     .DistinctBy(c => c.Symbol)
                                     .ToDictionary(c => c.Symbol);

                    universeData.Data = new List <BaseData>();
                    foreach (var fine in fineCollection.Data.OfType <FineFundamental>())
                    {
                        var fundamentals = new Fundamentals
                        {
                            Symbol              = fine.Symbol,
                            Time                = fine.Time,
                            EndTime             = fine.EndTime,
                            DataType            = fine.DataType,
                            CompanyReference    = fine.CompanyReference,
                            EarningReports      = fine.EarningReports,
                            EarningRatios       = fine.EarningRatios,
                            FinancialStatements = fine.FinancialStatements,
                            OperationRatios     = fine.OperationRatios,
                            SecurityReference   = fine.SecurityReference,
                            ValuationRatios     = fine.ValuationRatios
                        };

                        CoarseFundamental coarse;
                        if (coarseData.TryGetValue(fine.Symbol, out coarse))
                        {
                            // the only time the coarse data won't exist is if the selection function
                            // doesn't use the data provided, and instead returns a constant list of
                            // symbols -- coupled with a potential hole in the data
                            fundamentals.Value              = coarse.Value;
                            fundamentals.Market             = coarse.Market;
                            fundamentals.Volume             = coarse.Volume;
                            fundamentals.DollarVolume       = coarse.DollarVolume;
                            fundamentals.HasFundamentalData = coarse.HasFundamentalData;

                            // set the fine fundamental price property to yesterday's closing price
                            fine.Value = coarse.Value;
                        }

                        universeData.Data.Add(fundamentals);
                    }

                    // END -- HACK ATTACK -- END

                    // perform the fine fundamental universe selection
                    selectSymbolsResult = fineFiltered.FineFundamentalUniverse.PerformSelection(dateTimeUtc, fineCollection);
                }
            }
            else
            {
                // perform initial filtering and limit the result
                selectSymbolsResult = universe.PerformSelection(dateTimeUtc, universeData);
            }

            // check for no changes first
            if (ReferenceEquals(selectSymbolsResult, Universe.Unchanged))
            {
                return(SecurityChanges.None);
            }

            // materialize the enumerable into a set for processing
            var selections = selectSymbolsResult.ToHashSet();

            var additions = new List <Security>();
            var removals  = new List <Security>();

            // remove previously deselected members which were kept in the universe because of holdings or open orders
            foreach (var member in _pendingRemovals.ToList())
            {
                if (IsSafeToRemove(member))
                {
                    RemoveSecurityFromUniverse(universe, member, removals, dateTimeUtc, algorithmEndDateUtc);

                    _pendingRemovals.Remove(member);
                }
            }

            // determine which data subscriptions need to be removed from this universe
            foreach (var member in universe.Members.Values)
            {
                // if we've selected this subscription again, keep it
                if (selections.Contains(member.Symbol))
                {
                    continue;
                }

                // don't remove if the universe wants to keep him in
                if (!universe.CanRemoveMember(dateTimeUtc, member))
                {
                    continue;
                }

                // remove the member - this marks this member as not being
                // selected by the universe, but it may remain in the universe
                // until open orders are closed and the security is liquidated
                removals.Add(member);

                if (IsSafeToRemove(member))
                {
                    RemoveSecurityFromUniverse(universe, member, removals, dateTimeUtc, algorithmEndDateUtc);
                }
                else
                {
                    _pendingRemovals.Add(member);
                }
            }

            var keys = _pendingSecurityAdditions.Keys;

            if (keys.Any() && keys.Single() != dateTimeUtc)
            {
                // if the frontier moved forward then we've added these securities to the algorithm
                _pendingSecurityAdditions.Clear();
            }

            Dictionary <Symbol, Security> pendingAdditions;

            if (!_pendingSecurityAdditions.TryGetValue(dateTimeUtc, out pendingAdditions))
            {
                // keep track of created securities so we don't create the same security twice, leads to bad things :)
                pendingAdditions = new Dictionary <Symbol, Security>();
                _pendingSecurityAdditions[dateTimeUtc] = pendingAdditions;
            }

            // find new selections and add them to the algorithm
            foreach (var symbol in selections)
            {
                // create the new security, the algorithm thread will add this at the appropriate time
                Security security;
                if (!pendingAdditions.TryGetValue(symbol, out security) && !_algorithm.Securities.TryGetValue(symbol, out security))
                {
                    security = universe.CreateSecurity(symbol, _algorithm, _marketHoursDatabase, _symbolPropertiesDatabase);
                    pendingAdditions.Add(symbol, security);
                }

                var addedSubscription = false;

                foreach (var request in universe.GetSubscriptionRequests(security, dateTimeUtc, algorithmEndDateUtc))
                {
                    // add the new subscriptions to the data feed
                    _dataFeed.AddSubscription(request);

                    // only update our security changes if we actually added data
                    if (!request.IsUniverseSubscription)
                    {
                        addedSubscription = true;
                    }
                }

                if (addedSubscription)
                {
                    var addedMember = universe.AddMember(dateTimeUtc, security);

                    if (addedMember)
                    {
                        additions.Add(security);
                    }
                }
            }

            // return None if there's no changes, otherwise return what we've modified
            var securityChanges = additions.Count + removals.Count != 0
                ? new SecurityChanges(additions, removals)
                : SecurityChanges.None;

            // Add currency data feeds that weren't explicitly added in Initialize
            if (additions.Count > 0)
            {
                var addedSecurities = _algorithm.Portfolio.CashBook.EnsureCurrencyDataFeeds(_algorithm.Securities, _algorithm.SubscriptionManager, _marketHoursDatabase, _symbolPropertiesDatabase, _algorithm.BrokerageModel.DefaultMarkets, securityChanges);
                foreach (var security in addedSecurities)
                {
                    // assume currency feeds are always one subscription per, these are typically quote subscriptions
                    _dataFeed.AddSubscription(new SubscriptionRequest(false, universe, security, new SubscriptionDataConfig(security.Subscriptions.First()), dateTimeUtc, algorithmEndDateUtc));
                }
            }

            if (securityChanges != SecurityChanges.None)
            {
                Log.Debug("UniverseSelection.ApplyUniverseSelection(): " + dateTimeUtc + ": " + securityChanges);
            }

            return(securityChanges);
        }
Пример #49
0
        internal string ToDot()
        {
            var retval = "";

            var highestRank = 0;
            var rankDict    = new Dictionary <int, List <INode> >();

            foreach (var node in Nodes)
            {
                if (node.Rank > highestRank)
                {
                    highestRank = node.Rank;
                }
                List <INode> list;
                if (!rankDict.TryGetValue(node.Rank, out list))
                {
                    list = new List <INode>();
                    rankDict[node.Rank] = list;
                }
                list.Add(node);
            }

            retval += "digraph G {\n";

            //retval += "splines = true;\n";
            //retval += "sep = \"+25,25\";\n";
            //retval += "overlap=scalexy\n";
            retval += "nodesep=0.6;\n";
            retval += "ranksep = \"0.6 equally\"\n";

            //retval += "rankdir=\"LR\"\n";
            retval += string.Join("->", Enumerable.Range(0, highestRank + 1).Select((i) => string.Format("x{0}", i))) + "[style=invis]\n";
            retval += string.Join("\n", Enumerable.Range(0, highestRank + 1).Select((i) => string.Format("x{0} [style=invis]", i))) + "\n";
            retval += "x00 [style=invis]\n";

            // retval += string.Format("{{rank = source; \"{0}\" x0}}\n", _root.Name);
            retval += string.Format("{{rank = source; x00}}\n");
            retval += string.Format("x00 -> \"{0}\"\n", _root.Name);

            foreach (var pair in rankDict)
            {
                var rank      = pair.Key;
                var list      = pair.Value;
                var nodeNames = string.Join(" ", list.Select((n) => "\"" + n.Name + "\""));
                retval += string.Format("{{rank = same; {0} x{1}}}\n", nodeNames, rank);
            }

            // retval += Key();

            // retval += "graph [ordering=out];\n";
            var nodes = Nodes.ToList();

            nodes.Sort((a, b) => {
                if (a.StartPosition < b.StartPosition)
                {
                    return(-1);
                }
                else if (a.StartPosition > b.StartPosition)
                {
                    return(1);
                }
                else if (a.EndPosition < b.EndPosition)
                {
                    return(-1);
                }
                else if (a.EndPosition > b.EndPosition)
                {
                    return(1);
                }
                else
                {
                    return(0);
                }
            });
            foreach (var node in nodes)
            {
                retval += string.Format("\"{0}\" [{4} shape={2} style=filled fillcolor={3} label=\"{1}\" {5}];\n", node.Name, node.Label, node.Shape, node.Color, node.Ordering, node.Other);
            }
            foreach (var edge in Edges)
            {
                retval += string.Format("\"{0}\" -> \"{1}\" [label=\"{2}\"]\n", edge.Left.Name, edge.Right.Name, edge.Label?.ToStringNoWeight());
            }
            retval += "}\n";
            return(retval);
        }
        /// <summary>
        /// Finds and returns paths to Git installations in common locations.
        /// </summary>
        /// <param name="hints">(optional) List of paths the caller believes Git can be found.</param>
        /// <param name="paths">
        /// All discovered paths to the root of Git installations, ordered by 'priority' with first
        /// being the best installation to use when shelling out to Git.exe.
        /// </param>
        /// <returns><see langword="True"/> if Git was detected; <see langword="false"/> otherwise.</returns>
        public static bool FindGitInstallations(out List <GitInstallation> installations)
        {
            const string GitAppName    = @"Git";
            const string GitSubkeyName = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Git_is1";
            const string GitValueName  = "InstallLocation";

            installations = null;

            var programFiles32Path = String.Empty;
            var programFiles64Path = String.Empty;
            var appDataRoamingPath = String.Empty;
            var appDataLocalPath   = String.Empty;
            var programDataPath    = String.Empty;
            var reg32HklmPath      = String.Empty;
            var reg64HklmPath      = String.Empty;
            var reg32HkcuPath      = String.Empty;
            var reg64HkcuPath      = String.Empty;
            var shellPathValue     = String.Empty;

            RegistryKey reg32HklmKey = null;
            RegistryKey reg64HklmKey = null;
            RegistryKey reg32HkcuKey = null;
            RegistryKey reg64HkcuKey = null;

            if ((reg32HklmKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32)) != null)
            {
                if ((reg32HklmKey = reg32HklmKey.OpenSubKey(GitSubkeyName)) != null)
                {
                    reg32HklmPath = reg32HklmKey.GetValue(GitValueName, reg32HklmPath) as String;
                }
            }

            if ((reg32HkcuKey = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry32)) != null)
            {
                if ((reg32HkcuKey = reg32HkcuKey.OpenSubKey(GitSubkeyName)) != null)
                {
                    reg32HkcuPath = reg32HkcuKey.GetValue(GitValueName, reg32HkcuPath) as String;
                }
            }

            if ((programFiles32Path = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)) != null)
            {
                programFiles32Path = Path.Combine(programFiles32Path, GitAppName);
            }

            if (Environment.Is64BitOperatingSystem)
            {
                if ((reg64HklmKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64)) != null)
                {
                    if ((reg64HklmKey = reg64HklmKey.OpenSubKey(GitSubkeyName)) != null)
                    {
                        reg64HklmPath = reg64HklmKey.GetValue(GitValueName, reg64HklmPath) as String;
                    }
                }

                if ((reg64HkcuKey = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64)) != null)
                {
                    if ((reg64HkcuKey = reg64HkcuKey.OpenSubKey(GitSubkeyName)) != null)
                    {
                        reg64HkcuPath = reg64HkcuKey.GetValue(GitValueName, reg64HkcuPath) as String;
                    }
                }

                // since .NET returns %ProgramFiles% as %ProgramFilesX86% when the app is 32-bit
                // manual manipulation of the path is required

                if ((programFiles64Path = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)) != null)
                {
                    programFiles64Path = programFiles64Path.Substring(0, programFiles64Path.Length - 6);
                    programFiles64Path = Path.Combine(programFiles64Path, GitAppName);
                }
            }

            if ((appDataRoamingPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)) != null)
            {
                appDataRoamingPath = Path.Combine(appDataRoamingPath, GitAppName);
            }

            if ((appDataLocalPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)) != null)
            {
                appDataLocalPath = Path.Combine(appDataLocalPath, GitAppName);
            }

            if ((programDataPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)) != null)
            {
                programDataPath = Path.Combine(programDataPath, GitAppName);
            }

            List <GitInstallation> candidates = new List <GitInstallation>();

            // add candidate locations in order of preference
            if (Where.FindApp(GitAppName, out shellPathValue))
            {
                // `Where.App` returns the path to the executable, truncate to the installation root
                if (shellPathValue.EndsWith(GitInstallation.AllVersionCmdPath, StringComparison.InvariantCultureIgnoreCase))
                {
                    shellPathValue = shellPathValue.Substring(0, shellPathValue.Length - GitInstallation.AllVersionCmdPath.Length);
                }

                candidates.Add(new GitInstallation(shellPathValue, KnownGitDistribution.GitForWindows64v2));
                candidates.Add(new GitInstallation(shellPathValue, KnownGitDistribution.GitForWindows32v2));
                candidates.Add(new GitInstallation(shellPathValue, KnownGitDistribution.GitForWindows32v1));
            }

            if (!String.IsNullOrEmpty(reg64HklmPath))
            {
                candidates.Add(new GitInstallation(reg64HklmPath, KnownGitDistribution.GitForWindows64v2));
            }
            if (!String.IsNullOrEmpty(programFiles32Path))
            {
                candidates.Add(new GitInstallation(programFiles64Path, KnownGitDistribution.GitForWindows64v2));
            }
            if (!String.IsNullOrEmpty(reg64HkcuPath))
            {
                candidates.Add(new GitInstallation(reg64HkcuPath, KnownGitDistribution.GitForWindows64v2));
            }
            if (!String.IsNullOrEmpty(reg32HklmPath))
            {
                candidates.Add(new GitInstallation(reg32HklmPath, KnownGitDistribution.GitForWindows32v2));
                candidates.Add(new GitInstallation(reg32HklmPath, KnownGitDistribution.GitForWindows32v1));
            }
            if (!String.IsNullOrEmpty(programFiles32Path))
            {
                candidates.Add(new GitInstallation(programFiles32Path, KnownGitDistribution.GitForWindows32v2));
                candidates.Add(new GitInstallation(programFiles32Path, KnownGitDistribution.GitForWindows32v1));
            }
            if (!String.IsNullOrEmpty(reg32HkcuPath))
            {
                candidates.Add(new GitInstallation(reg32HkcuPath, KnownGitDistribution.GitForWindows32v2));
                candidates.Add(new GitInstallation(reg32HkcuPath, KnownGitDistribution.GitForWindows32v1));
            }
            if (!String.IsNullOrEmpty(programDataPath))
            {
                candidates.Add(new GitInstallation(programDataPath, KnownGitDistribution.GitForWindows64v2));
                candidates.Add(new GitInstallation(programDataPath, KnownGitDistribution.GitForWindows32v2));
                candidates.Add(new GitInstallation(programDataPath, KnownGitDistribution.GitForWindows32v1));
            }
            if (!String.IsNullOrEmpty(appDataLocalPath))
            {
                candidates.Add(new GitInstallation(appDataLocalPath, KnownGitDistribution.GitForWindows64v2));
                candidates.Add(new GitInstallation(appDataLocalPath, KnownGitDistribution.GitForWindows32v2));
                candidates.Add(new GitInstallation(appDataLocalPath, KnownGitDistribution.GitForWindows32v1));
            }
            if (!String.IsNullOrEmpty(appDataRoamingPath))
            {
                candidates.Add(new GitInstallation(appDataRoamingPath, KnownGitDistribution.GitForWindows64v2));
                candidates.Add(new GitInstallation(appDataRoamingPath, KnownGitDistribution.GitForWindows32v2));
                candidates.Add(new GitInstallation(appDataRoamingPath, KnownGitDistribution.GitForWindows32v1));
            }

            HashSet <GitInstallation> pathSet = new HashSet <GitInstallation>();

            foreach (var candidate in candidates)
            {
                if (GitInstallation.IsValid(candidate))
                {
                    pathSet.Add(candidate);
                }
            }

            installations = pathSet.ToList();

            Git.Trace.WriteLine($"found {installations.Count} Git installation(s).");

            return(installations.Count > 0);
        }
Пример #51
0
        /// <summary>
        /// Start assumes that it cannot be followed by another Start() without having a Shutdown() first
        /// </summary>
        public override void Start()
        {
            if (_endpointManager == null)
            {
                _log.Info("Starting remoting");
                _endpointManager =
                System.SystemActorOf(RARP.For(System).ConfigureDispatcher(
                    Props.Create(() => new EndpointManager(System.Settings.Config, _log)).WithDeploy(Deploy.Local)),
                    EndpointManagerName);

                try
                {
                    var addressPromise = new TaskCompletionSource<IList<ProtocolTransportAddressPair>>();

                    // tells the EndpointManager to start all transports and bind them to listenable addresses, and then set the results
                    // of this promise to include them.
                    _endpointManager.Tell(new EndpointManager.Listen(addressPromise)); 

                    addressPromise.Task.Wait(Provider.RemoteSettings.StartupTimeout);
                    var akkaProtocolTransports = addressPromise.Task.Result;
                    if(akkaProtocolTransports.Count==0)
                        throw new ConfigurationException(@"No transports enabled under ""akka.remote.enabled-transports""");
                    _addresses = new HashSet<Address>(akkaProtocolTransports.Select(a => a.Address));

                    IEnumerable<IGrouping<string, ProtocolTransportAddressPair>> tmp =
                        akkaProtocolTransports.GroupBy(t => t.ProtocolTransport.SchemeIdentifier);
                    _transportMapping = new Dictionary<string, HashSet<ProtocolTransportAddressPair>>();
                    foreach (var g in tmp)
                    {
                        var set = new HashSet<ProtocolTransportAddressPair>(g);
                        _transportMapping.Add(g.Key, set);
                    }

                    _defaultAddress = akkaProtocolTransports.Head().Address;
                    _addresses = new HashSet<Address>(akkaProtocolTransports.Select(x => x.Address));

                    _log.Info("Remoting started; listening on addresses : [{0}]", string.Join(",", _addresses.Select(x => x.ToString())));

                    _endpointManager.Tell(new EndpointManager.StartupFinished());
                    _eventPublisher.NotifyListeners(new RemotingListenEvent(_addresses.ToList()));

                }
                catch (TaskCanceledException ex)
                {
                    NotifyError("Startup was cancelled due to timeout", ex);
                    throw;
                }
                catch (TimeoutException ex)
                {
                    NotifyError("Startup timed out", ex);
                    throw;
                }
                catch (Exception ex)
                {
                    NotifyError("Startup failed", ex);
                    throw;
                }
            }
            else
            {
                _log.Warning("Remoting was already started. Ignoring start attempt.");
            }
        }
Пример #52
0
        private bool InstallList(HashSet <string> toInstall, RelationshipResolverOptions options,
                                 NetAsyncDownloader downloader)
        {
            if (toInstall.Any())
            {
                // actual magic happens here, we run the installer with our mod list
                ModuleInstaller.GetInstance(manager.CurrentInstance, GUI.user).onReportModInstalled = OnModInstalled;
                cancelCallback = downloader.CancelDownload;
                try
                {
                    ModuleInstaller.GetInstance(manager.CurrentInstance, GUI.user)
                    .InstallList(toInstall.ToList(), options, downloader);
                }
                catch (ModuleNotFoundKraken ex)
                {
                    GUI.user.RaiseMessage("Module {0} required, but not listed in index, or not available for your version of KSP", ex.module);
                    return(false);
                }
                catch (BadMetadataKraken ex)
                {
                    GUI.user.RaiseMessage("Bad metadata detected for module {0}: {1}", ex.module, ex.Message);
                    return(false);
                }
                catch (FileExistsKraken ex)
                {
                    if (ex.owning_module != null)
                    {
                        GUI.user.RaiseMessage(
                            "\nOh no! We tried to overwrite a file owned by another mod!\n" +
                            "Please try a `ckan update` and try again.\n\n" +
                            "If this problem re-occurs, then it maybe a packaging bug.\n" +
                            "Please report it at:\n\n" +
                            "https://github.com/KSP-CKAN/CKAN-meta/issues/new\n\n" +
                            "Please including the following information in your report:\n\n" +
                            "File           : {0}\n" +
                            "Installing Mod : {1}\n" +
                            "Owning Mod     : {2}\n" +
                            "CKAN Version   : {3}\n",
                            ex.filename, ex.installing_module, ex.owning_module,
                            Meta.Version()
                            );
                    }
                    else
                    {
                        GUI.user.RaiseMessage(
                            "\n\nOh no!\n\n" +
                            "It looks like you're trying to install a mod which is already installed,\n" +
                            "or which conflicts with another mod which is already installed.\n\n" +
                            "As a safety feature, the CKAN will *never* overwrite or alter a file\n" +
                            "that it did not install itself.\n\n" +
                            "If you wish to install {0} via the CKAN,\n" +
                            "then please manually uninstall the mod which owns:\n\n" +
                            "{1}\n\n" + "and try again.\n",
                            ex.installing_module, ex.filename
                            );
                    }

                    GUI.user.RaiseMessage("Your GameData has been returned to its original state.\n");
                    return(false);
                }
                catch (InconsistentKraken ex)
                {
                    // The prettiest Kraken formats itself for us.
                    GUI.user.RaiseMessage(ex.InconsistenciesPretty);
                    return(false);
                }
                catch (CancelledActionKraken)
                {
                    return(false);
                }
                catch (MissingCertificateKraken kraken)
                {
                    // Another very pretty kraken.
                    GUI.user.RaiseMessage(kraken.ToString());
                    return(false);
                }
                catch (DownloadErrorsKraken)
                {
                    // User notified in InstallList
                    return(false);
                }
            }

            return(true);
        }
Пример #53
0
        /// <summary>
        /// Saves the user preferences and updates the resource list and locations based on the filter
        /// </summary>
        private void ApplyFilter()
        {
            var group   = this.GetSelectedGroup();
            int groupId = 0;

            if (group != null)
            {
                groupId = group.Id;
            }

            int scheduleId             = rblSchedule.SelectedValue.AsInteger();
            var allSelectedLocationIds = new HashSet <int>(hfAllSelectedLocationIds.Value.SplitDelimitedValues().AsIntegerList());

            foreach (var displayedLocationItem in cblGroupLocations.Items.OfType <ListItem>())
            {
                var locationId = displayedLocationItem.Value.AsInteger();
                if (displayedLocationItem.Selected)
                {
                    allSelectedLocationIds.Add(locationId);
                }
                else
                {
                    allSelectedLocationIds.Remove(locationId);
                }
            }

            hfAllSelectedLocationIds.Value = allSelectedLocationIds.ToList().AsDelimited(",");

            this.SetBlockUserPreference(UserPreferenceKey.SelectedGroupId, groupId.ToString());
            this.SetBlockUserPreference(UserPreferenceKey.SelectedDate, ddlWeek.SelectedValue);
            this.SetBlockUserPreference(UserPreferenceKey.SelectedGroupLocationIds, allSelectedLocationIds.ToList().AsDelimited(","));
            this.SetBlockUserPreference(UserPreferenceKey.SelectedScheduleId, rblSchedule.SelectedValue);

            if (group != null && group.SchedulingMustMeetRequirements)
            {
                bgResourceListSource.Visible = false;
                bgResourceListSource.SetValue(( int )SchedulerResourceListSourceType.Group);
                pnlAddPerson.Visible = false;
                ppAddPerson.Visible  = false;
            }
            else
            {
                bgResourceListSource.Visible = true;
                pnlAddPerson.Visible         = true;
                ppAddPerson.Visible          = true;
            }

            var resourceListSourceType = bgResourceListSource.SelectedValueAsEnumOrNull <SchedulerResourceListSourceType>();

            this.SetBlockUserPreference(UserPreferenceKey.SelectedResourceListSourceType, resourceListSourceType.ToString());

            var groupMemberFilterType = rblGroupMemberFilter.SelectedValueAsEnumOrNull <SchedulerResourceGroupMemberFilterType>();

            this.SetBlockUserPreference(UserPreferenceKey.GroupMemberFilterType, groupMemberFilterType.ToString());

            this.SetBlockUserPreference(UserPreferenceKey.AlternateGroupId, gpResourceListAlternateGroup.SelectedValue);
            this.SetBlockUserPreference(UserPreferenceKey.DataViewId, dvpResourceListDataView.SelectedValue);

            pnlResourceFilterGroup.Visible          = resourceListSourceType == SchedulerResourceListSourceType.Group;
            pnlResourceFilterAlternateGroup.Visible = resourceListSourceType == SchedulerResourceListSourceType.AlternateGroup;
            pnlResourceFilterDataView.Visible       = resourceListSourceType == SchedulerResourceListSourceType.DataView;

            bool filterIsValid = groupId > 0 && scheduleId > 0 && cblGroupLocations.SelectedValues.Any();

            pnlScheduler.Visible              = filterIsValid;
            nbFilterInstructions.Visible      = !filterIsValid;
            pnlGroupScheduleLocations.Visible = groupId > 0;

            if (filterIsValid)
            {
                InitResourceList();
                BindAttendanceOccurrences();
            }

            // Create URL for selected settings
            var pageReference = CurrentPageReference;

            foreach (var setting in GetBlockUserPreferences())
            {
                pageReference.Parameters.AddOrReplace(setting.Key, setting.Value);
            }

            Uri uri = new Uri(Request.Url.ToString());

            btnCopyToClipboard.Attributes["data-clipboard-text"] = uri.GetLeftPart(UriPartial.Authority) + pageReference.BuildUrl();
            btnCopyToClipboard.Disabled = false;
        }
Пример #54
0
    private static string ApplyPlayersTo(string text)
    {
        HashSet <Player> alreadyIncludedPlayers = new HashSet <Player>();

        if (text.IndexOf("<p>", StringComparison.OrdinalIgnoreCase) >= 0)
        {
            Regex rgx = new Regex("<p>", RegexOptions.IgnoreCase);
            do
            {
                Player currentPlayer = GameManager.instance.dataManager.GetCurrentPlayer();
                text = rgx.Replace(text, currentPlayer.name, 1);
                alreadyIncludedPlayers.Add(currentPlayer);
            } while (text.IndexOf("<p>", StringComparison.OrdinalIgnoreCase) >= 0);
        }

        if (text.IndexOf("<pr>", StringComparison.OrdinalIgnoreCase) >= 0)
        {
            Regex rgx = new Regex("<pr>", RegexOptions.IgnoreCase);
            do
            {
                Player randPlayer = GameManager.instance.dataManager.GetRandomEnabledPlayer(alreadyIncludedPlayers.ToList());
                text = rgx.Replace(text, randPlayer.name, 1);
                alreadyIncludedPlayers.Add(randPlayer);
            } while (text.IndexOf("<pr>", StringComparison.OrdinalIgnoreCase) >= 0);
        }

        return(text);
    }
Пример #55
0
        public List <Data> DependencyData(Data data, bool onlyIndependent = true)
        {
            HashSet <Data> dependencies = DependencyDataHash(data, onlyIndependent);

            return(dependencies.ToList());
        }
Пример #56
0
        private void LoadFromKey(RegistryKey key)
        {
            HashSet <Guid> categories = new HashSet <Guid>();
            object         name       = key.GetValue(null);

            Name = null;
            if (name != null)
            {
                string s = name.ToString().Trim();

                if (s.Length > 0)
                {
                    Name = name.ToString();
                }
            }

            bool fake_name = false;

            if (Name == null)
            {
                fake_name = true;
                Name      = Clsid.FormatGuidDefault();
            }

            Dictionary <COMServerType, COMCLSIDServerEntry> servers = new Dictionary <COMServerType, COMCLSIDServerEntry>();
            COMCLSIDServerEntry inproc_server = ReadServerKey(servers, key, COMServerType.InProcServer32);

            ReadServerKey(servers, key, COMServerType.LocalServer32);
            ReadServerKey(servers, key, COMServerType.InProcHandler32);
            Servers = new ReadOnlyDictionary <COMServerType, COMCLSIDServerEntry>(servers);

            if (fake_name && inproc_server != null && inproc_server.HasDotNet)
            {
                Name = string.Format("{0}, {1}", inproc_server.DotNet.ClassName, inproc_server.DotNet.AssemblyName);
            }

            AppID = COMUtilities.ReadGuid(key, null, "AppID");
            if (AppID == Guid.Empty)
            {
                AppID = COMUtilities.ReadGuid(Registry.ClassesRoot,
                                              string.Format(@"AppID\{0}", COMUtilities.GetFileName(DefaultServer)), "AppID");
            }

            if (AppID != Guid.Empty && !servers.ContainsKey(COMServerType.LocalServer32))
            {
                servers.Add(COMServerType.LocalServer32, new COMCLSIDServerEntry(COMServerType.LocalServer32, "<APPID HOSTED>"));
            }

            TypeLib = COMUtilities.ReadGuid(key, "TypeLib", null);
            if (key.HasSubkey("Control"))
            {
                categories.Add(COMCategory.CATID_Control);
            }

            if (key.HasSubkey("Insertable"))
            {
                categories.Add(COMCategory.CATID_Insertable);
            }

            if (key.HasSubkey("DocObject"))
            {
                categories.Add(COMCategory.CATID_Document);
            }

            using (RegistryKey catkey = key.OpenSubKey("Implemented Categories"))
            {
                if (catkey != null)
                {
                    string[] subKeys = catkey.GetSubKeyNames();
                    foreach (string s in subKeys)
                    {
                        if (Guid.TryParse(s, out Guid g))
                        {
                            categories.Add(g);
                        }
                    }
                }
            }

            Categories = categories.ToList().AsReadOnly();
            TreatAs    = COMUtilities.ReadGuid(key, "TreatAs", null);

            using (RegistryKey elev_key = key.OpenSubKey("Elevation"),
                   vso_key = key.OpenSubKey("VirtualServerObjects"))
            {
                if (elev_key != null)
                {
                    using (var base_key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine,
                                                                  Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Default))
                    {
                        int auto_approval = COMUtilities.ReadInt(base_key,
                                                                 @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\UAC\COMAutoApprovalList", Clsid.ToString("B"));
                        Elevation = new COMCLSIDElevationEntry(elev_key, vso_key, auto_approval != 0);
                    }
                }
            }

            ActivatableFromApp = _app_activatable.Contains(Clsid);
            using (RegistryKey trustkey = Registry.LocalMachine.OpenSubKey(@"Software\Classes\Unmarshalers\System\" + Clsid.ToString("B")))
            {
                TrustedMarshaller = trustkey != null ? true : categories.Contains(COMCategory.CATID_TrustedMarshaler);
            }

            Source = key.GetSource();
        }
Пример #57
0
        static BurstLoader()
        {
            // This can be setup to get more diagnostics
            var debuggingStr = Environment.GetEnvironmentVariable("UNITY_BURST_DEBUG");

            IsDebugging = debuggingStr != null;
            if (IsDebugging)
            {
                UnityEngine.Debug.LogWarning("[com.unity.burst] Extra debugging is turned on.");
                int debuggingLevel;
                int.TryParse(debuggingStr, out debuggingLevel);
                if (debuggingLevel <= 0)
                {
                    debuggingLevel = 1;
                }
                DebuggingLevel = debuggingLevel;
            }

            // Try to load the runtime through an environment variable
            RuntimePath = Environment.GetEnvironmentVariable("UNITY_BURST_RUNTIME_PATH");

            // Otherwise try to load it from the package itself
            if (!Directory.Exists(RuntimePath))
            {
                RuntimePath = Path.GetFullPath("Packages/com.unity.burst/.Runtime");
            }

            if (IsDebugging)
            {
                UnityEngine.Debug.LogWarning($"[com.unity.burst] Runtime directory set to {RuntimePath}");
            }

            BurstEditorOptions.EnsureSynchronized();

            BurstCompilerService.Initialize(RuntimePath, TryGetOptionsFromMember);

            EditorApplication.quitting += BurstCompiler.Shutdown;

            CompilationPipeline.assemblyCompilationStarted  += OnAssemblyCompilationStarted;
            CompilationPipeline.assemblyCompilationFinished += OnAssemblyCompilationFinished;
            EditorApplication.playModeStateChanged          += EditorApplicationOnPlayModeStateChanged;

            // Workaround to update the list of assembly folders as soon as possible
            // in order for the JitCompilerService to not fail with AssemblyResolveExceptions.
            try
            {
                var assemblyList    = BurstReflection.GetAssemblyList(AssembliesType.Editor);
                var assemblyFolders = new HashSet <string>();
                foreach (var assembly in assemblyList)
                {
                    try
                    {
                        var fullPath       = Path.GetFullPath(assembly.Location);
                        var assemblyFolder = Path.GetDirectoryName(fullPath);
                        if (!string.IsNullOrEmpty(assemblyFolder))
                        {
                            assemblyFolders.Add(assemblyFolder);
                        }
                    }
                    catch
                    {
                        // ignore
                    }
                }

                // Notify the compiler
                var assemblyFolderList = assemblyFolders.ToList();
                if (IsDebugging)
                {
                    UnityEngine.Debug.Log($"Burst - Change of list of assembly folders:\n{string.Join("\n", assemblyFolderList)}");
                }
                BurstCompiler.UpdateAssemblerFolders(assemblyFolderList);
            }
            catch
            {
                // ignore
            }

            // Notify the compiler about a domain reload
            if (IsDebugging)
            {
                UnityEngine.Debug.Log("Burst - Domain Reload");
            }

            // Notify the JitCompilerService about a domain reload
            BurstCompiler.DomainReload();

            // Make sure that the X86 CSR function pointers are compiled
            Intrinsics.X86.CompileManagedCsrAccessors();
        }
Пример #58
0
 public StatusLayer(HashSet <StatusEffect> statusList)
 {
     this.statusList = statusList?.ToList() ?? new List <StatusEffect>();
 }
Пример #59
0
        public static void KeepAlive()
        {
            string ver = Version.FileVersion;

            Connect();
            while (Running)
            {
                if ((DateTime.Now - StartupTime).Hours > 10)
                {
                    IsShuttingDown = true;
                }

                var infoGathered = false;

                if (Games == null || (IsShuttingDown && Games.Count == 0))
                {
                    Thread.Sleep(5000);
                    //Running = false;
                    Environment.Exit(0);
                    return;
                }
                //monitor the tcp connection to keep it open
                try
                {
                    if (Games == null)
                    {
                        //uhhhhhhhhh  ok.....
                        continue;
                    }
                    var games = Games.ToList();

                    var info = new NodeInfo
                    {
                        Games                 = new HashSet <GameInfo>(),
                        ClientId              = ClientId,
                        CurrentGames          = games.Count,
                        CurrentPlayers        = games.Sum(x => x?.Players?.Count ?? 0),
                        DuplicateGamesRemoved = DupGamesKilled,
                        ThreadCount           = 0,//Process.GetCurrentProcess().Threads.Count,
                        //TotalGames = GamesStarted,
                        //TotalPlayers = games.Sum(x => x.Players?.Count ?? 0) + TotalPlayers,
                        Uptime       = DateTime.Now - StartupTime,
                        Version      = ver,
                        ShuttingDown = IsShuttingDown,
                        MessagesSent = MessagesSent
                    };

                    foreach (var g in games)
                    {
                        if (g?.Players == null)
                        {
                            try
                            {
                                Games.Remove(g);
                            }
                            catch
                            {
                                // ignored, it was already removed
                            }
                            continue;
                        }
                        var gi = new GameInfo
                        {
                            Language    = g.Language,
                            ChatGroup   = g.ChatGroup,
                            GroupId     = g.ChatId,
                            NodeId      = ClientId,
                            Guid        = g.Guid,
                            State       = g.IsRunning ? GameState.Running : g.IsJoining ? GameState.Joining : GameState.Dead,
                            Users       = g.Players != null ? new HashSet <int>(g.Players.Where(x => !x.IsDead).Select(x => x.TeleUser.Id)) : new HashSet <int>(),
                            PlayerCount = g.Players?.Count ?? 0
                                          //Players = new HashSet<IPlayer>(g.Players)
                        };
                        info.Games.Add(gi);
                    }

                    var json = JsonConvert.SerializeObject(info);
                    infoGathered = true;
                    Client.WriteLine(json);
                }
                catch (Exception e)
                {
                    while (e.InnerException != null)
                    {
                        e = e.InnerException;
                    }
                    Console.WriteLine($"Error in KeepAlive: {e.Message}\n{e.StackTrace}\n");
                    if (infoGathered) //only disconnect if tcp error
                    {
                        if (Client != null)
                        {
                            try
                            {
                                Client.DataReceived          -= ClientOnDataReceived;
                                Client.DelimiterDataReceived -= ClientOnDelimiterDataReceived;
                                Client.Disconnect();
                            }
                            catch
                            {
                                // ignored
                            }
                        }
                        Connect();
                    }
                }
                Thread.Sleep(500);
            }
        }
Пример #60
0
 //return list of all active connections
 public List <string> GetAllActiveConnections()
 {
     return(CurrentConnections.ToList());
 }