public void PrependNoIteratingSourceBeforeFirstItem() { var ie = new List<int>(); var prepended = (from i in ie select i).Prepend(4); ie.Add(42); Assert.Equal(prepended, ie.Prepend(4)); }
public string AddBinary(string a, string b) { List <char> aList = a.ToCharArray().ToList(); List <char> bList = b.ToCharArray().ToList(); if (a.Length > b.Length) { for (int i = 0; i < a.Length - b.Length; i++) { bList = bList.Prepend('0').ToList(); } } else if (b.Length > a.Length) { for (int i = 0; i < b.Length - a.Length; i++) { aList = aList.Prepend('0').ToList(); } } List <int> sumList = new List <int>(new int[aList.Count]); for (int i = aList.Count - 1; i >= 0; i--) { sumList[i] += int.Parse(aList[i].ToString()) + int.Parse(bList[i].ToString()); if (i > 0 && sumList[i] >= 2) { sumList[i] -= 2; sumList[i - 1] += 1; } else if (i == 0 && sumList[0] >= 2) { sumList[0] -= 2; sumList = sumList.Prepend(1).ToList(); } } string sumStr = string.Join("", sumList); return(sumStr); }
public IList <IList <string> > DisplayTable(IList <IList <string> > orders) { var header = new List <string>(); var foodMap = new Dictionary <string, int>(); var tableMap = new Dictionary <string, IList <int> >(); foreach (var order in orders) { string table = order[1], food = order[2]; if (!foodMap.TryGetValue(food, out int fi)) { fi = header.Count; header.Add(food); foodMap[food] = fi; } if (!tableMap.TryGetValue(table, out var t)) { t = new List <int>(); tableMap[table] = t; } while (t.Count <= fi) { t.Add(0); } t[fi]++; } header = header.OrderBy(f => f, StringComparer.Ordinal).ToList(); var foodIndices = header .Select(f => foodMap[f]) .ToArray(); return(tableMap .OrderBy(t => int.Parse(t.Key)) .Select <KeyValuePair <string, IList <int> >, IList <string> >(t => foodIndices .Select(i => t.Value.Count > i ? t.Value[i].ToString() : "0") .Prepend(t.Key.ToString()) .ToList()) .Prepend(header.Prepend("Table").ToList()) .ToList()); }
private static List <string> GenerateAsciiProgram(string fullpath, List <string> path, List <string> moves) { const int MaxCommandLength = 20; var moveNames = new string[] { "A", "B", "C" }; if (moves.Count == moveNames.Length) { var reduce = fullpath; for (var i = 0; i < moveNames.Length; i++) { reduce = reduce.Replace(moves[i], moveNames[i]); } return(reduce.Length > MaxCommandLength ? null : moves.Prepend(reduce).ToList()); } for (var offset = 0; path.GetRange(0, offset).AsMovement().Length < MaxCommandLength; offset++) { for (var len = 1; ; len++) { var head = path.GetRange(offset, len).AsMovement(); if (head.Length > MaxCommandLength) // too wide { break; } var tail = path.GetRange(offset + len, path.Count() - (offset + len)); moves.Add(head); var asciiProgram = GenerateAsciiProgram(fullpath, tail, moves); if (asciiProgram != null) { return(asciiProgram); } moves.RemoveAt(moves.Count - 1); } } return(null); }
protected override void DrawUnifiedElementInternal(Rect rect, T old_value) { string old_text = old_value.ToStringEX("None"); string new_text = EditorGUI.DelayedTextField(GetElementRect(), old_text); if (new_text != old_text) { List <T> options = GetOptions(new_text) .Sort(o => o.ToStringEX().Length) .ToList(); if (options.HasOnlyOne()) { GetProperty().SetContentValues(options.GetOnly()); } else { GenericMenuExtensions.Create <T>(options.Prepend(default(T)), o => GetProperty().SetContentValues(o)) .DropDown(GetElementRect()); } } }
public static void Changecollection2() { ChangeCollection2Options(); int option; option = InputChangeCollecction2Option(); switch (option) { case 1: Ship FirstShip = CreateElement(); shipsList.Prepend(FirstShip); Console.Write("Добавлен элемент в начало: "); FirstShip.Show(); break; case 2: Ship LastShip = CreateElement(); shipsList.Append(LastShip); Console.Write("Добавлен элемент в конец: "); LastShip.Show(); break; case 3: if (shipsList.Count == 0) { Console.WriteLine("Список пуст"); } else { int index = InputIndex(); Ship DeletedShip = shipsList[index]; shipsList.RemoveAt(index); Console.Write("Удалён элемент: "); DeletedShip.Show(); } break; } }
private void updateDisplay(ValueChangedEvent <DirectoryInfo> dir) { flow.Clear(); List <DirectorySelectorDirectory> pathPieces = new List <DirectorySelectorDirectory>(); DirectoryInfo ptr = dir.NewValue; while (ptr != null) { pathPieces.Insert(0, CreateDirectoryItem(ptr)); ptr = ptr.Parent; } var caption = CreateCaption(); if (caption != null) { flow.Add(caption); } flow.AddRange(pathPieces.Prepend(CreateRootDirectoryItem())); }
/// <summary> /// Shifts the lists items to the Right /// </summary> /// <param name="List">The list to shift</param> /// <param name="amount">The number of spaces to shift items</param> /// <param name="wrapAround">If false the shift acts like a pull, shortening the list with every shift</param> /// <returns>The shifted List<T></returns> public static List <T> shiftRight <T>(this List <T> List, int amount = 1, bool wrapAround = false) { if (List.Count == 0 || amount == 0) { return(List); } if (!wrapAround && amount >= List.Count) { return(default(List <T>)); } for (int i = 0; i < amount; i++) { var tmp = List[List.Count - 1]; List = List.GetRange(0, List.Count - 2); if (wrapAround) { List.Prepend(tmp); } } return(List); }
public object Convert(object value, Type targetType, object parameter, string language) { if (value is Item item) { var labelList = item.Labels.Select(i => MainPage.Labels.First(j => i == j.Id).Name).ToList(); List <string> list = new List <string> { MainPage.Projects.FirstOrDefault(i => i.Id == item.ProjectId)?.Name }; switch (labelList.Count) { case 0: break; case 1: list.Add("[" + labelList.First() + "]"); break; default: list.Add("[" + labelList.Aggregate((i, j) => i + "," + j) + "]"); break; } var due = item.Due?.Date.ToString("m"); if (due != null) { list = list.Prepend(due).ToList(); } return(list.Aggregate((i, j) => i + " • " + j)); } return(""); }
static List <int> ShiftLeftorRightXTimes(List <int> numbers, int count, string leftOrRight) { var temp = 0; if (leftOrRight == "left") { for (int i = 0; i < count; i++) { temp = numbers[0]; numbers.RemoveAt(0); numbers.Add(temp); } } else { for (int i = 0; i < count; i++) { temp = numbers[numbers.Count - 1]; numbers.RemoveAt(numbers.Count - 1); numbers = numbers.Prepend(temp).ToList(); } } return(numbers); }
private static long Solution2(string[] input) { List <int> inputs = input.Select(i => int.Parse(i)).ToList(); inputs.Sort(); int outlet = 0; int device = inputs.Last() + 3; inputs = inputs.Prepend(outlet).Append(device).ToList(); long total = 1; long runningCount = 0; for (int i = 0; i < inputs.Count - 1; i++) { int item = inputs[i]; int nearby = inputs.Skip(i + 1) .Take(3) .Where(a => a <= item + 3).Count(); if (nearby == 1 && runningCount > 1) { if (runningCount == 2) { runningCount++; } total *= (runningCount - 1); runningCount = 0; } else if (nearby > 1) { runningCount += nearby; } } return(total); }
//Memoize //Only divide by the previous prime numbers. //The runtime difference between this and the standard function isnt obvious until very large numbers public static List <int> PrimesToN2(int n) { bool primeFlag = true; List <int> primes = new List <int>(); primes.Add(2); for (int i = 3; i < n; ++i) { foreach (int prime in primes) { if (prime > Math.Sqrt(i)) { break; } if (i % prime == 0) { primeFlag = false; break; } } if (primeFlag) { primes.Add(i); } else { primeFlag = true; } } primes.Prepend(1); return(primes); }
private Expr PerformNonOrderlessNumericOperation(Func <double, double, double> operation, Expr opHead, IList <Expr> args, Func <IList <Expr>, Expr> inverseOp) { var exprs = new List <Expr>(); var firstArg = args.First(); if (firstArg is Number firstNum) { var result = firstNum.Value.value; foreach (var item in args.Skip(1)) { if (item is Number num) { result = operation(result, num.Value.value); } else { exprs.Add(item); } } if (exprs.Count == 0) { return(result); } else { return(opHead[exprs.Prepend(result).ToArray()]); } } else { return(opHead[firstArg, inverseOp(args.Skip(1).ToList())]); } }
public void TestLists() { var db = new ObjectDatabase(Array.Empty <int>(), null); const string TestFilePath = @"..\..\..\TestData\TestLists.w3o"; using var fileStream = File.OpenRead(TestFilePath); using var binaryReader = new BinaryReader(fileStream); var objectData = binaryReader.ReadObjectData(false); var errorLines = new List <string>(); // Verify unit data var unitData = objectData.UnitData; // Empty lists test var peasant = new Unit(UnitType.Peasant, db); peasant.TechtreeStructuresBuilt = Array.Empty <Unit>(); var keep = new Unit(UnitType.Keep, db); keep.ArtRequiredAnimationNames = Array.Empty <string>(); keep.PathingPlacementRequires = Array.Empty <PathingType>(); keep.TechtreeResearchesAvailable = Array.Empty <Upgrade>(); keep.StatsUnitClassification = Array.Empty <UnitClassification>(); var cannonTower = new Unit(UnitType.Cannontower, db); cannonTower.TechtreeRequirements = Array.Empty <Tech>(); var arcaneVault = new Unit(UnitType.Arcanevault, db); arcaneVault.TechtreeItemsMade = Array.Empty <Item>(); var paladin = new Unit(UnitType.Paladin, db); paladin.ArtSpecial = Array.Empty <string>(); paladin.AbilitiesNormal = Array.Empty <Ability>(); paladin.AbilitiesHero = Array.Empty <Ability>(); paladin.EditorTilesets = Array.Empty <Tileset>(); paladin.CombatTargetedAs = Array.Empty <Target>(); var ziggurat = new Unit(UnitType.Ziggurat, db); ziggurat.PathingPlacementPreventedBy = Array.Empty <PathingType>(); // Non-empty lists test var bloodmage = new Unit(UnitType.Bloodmage, db); bloodmage.ArtRequiredAnimationNames = new[] { "upgrade", "second" }; bloodmage.TechtreeStructuresBuilt = new[] { keep, cannonTower, arcaneVault }; bloodmage.TechtreeItemsSold = new[] { new Item(ItemType.ClawsOfAttack15), new Item(ItemType.CrownOfKings5) }; bloodmage.TechtreeRequirements = new[] { new Tech(peasant), new Tech(new Upgrade(UpgradeType.HumanAnimalBreeding)), new Tech(TechEquivalent.AnyTier1Hall) }; bloodmage.TechtreeRequirementsLevels = new[] { 1, 2, 0 }; bloodmage.ArtSpecial = new[] { @"buildings\other\ElvenFarm\ElvenFarm.mdl", string.Empty }; bloodmage.AbilitiesNormal = new Ability[] { new Abilities.Alarm(), new Abilities.Inventory() }; bloodmage.AbilitiesHero = new Ability[] { new Abilities.BloodMageFlameStrike(), new Abilities.BloodMageBanish() }; bloodmage.EditorTilesets = new[] { Tileset.Ashenvale, Tileset.All }; bloodmage.StatsUnitClassification = new[] { UnitClassification.Ancient, UnitClassification.Giant }; bloodmage.CombatTargetedAs = new[] { Target.Alive, Target.Hero }; var workshop = new Unit(UnitType.Workshop, db); workshop.TechtreeResearchesAvailable = new[] { new Upgrade(UpgradeType.HumanFlare), new Upgrade(UpgradeType.HumanFragShards) }; workshop.PathingPlacementRequires = new[] { PathingType.Unfloat, PathingType.Blighted }; workshop.PathingPlacementPreventedBy = new[] { PathingType.Unbuildable, PathingType.Unwalkable }; var expectUnit = new Dictionary <string, Type>() { // Bloodmage { "uani", bloodmage.ArtRequiredAnimationNamesRaw.GetType() }, { "ubui", bloodmage.TechtreeStructuresBuiltRaw.GetType() }, { "usei", bloodmage.TechtreeItemsSoldRaw.GetType() }, { "ureq", bloodmage.TechtreeRequirementsRaw.GetType() }, { "urqa", bloodmage.TechtreeRequirementsLevelsRaw.GetType() }, { "uspa", bloodmage.ArtSpecialRaw.GetType() }, { "uabi", bloodmage.AbilitiesNormalRaw.GetType() }, { "uhab", bloodmage.AbilitiesHeroRaw.GetType() }, { "util", bloodmage.EditorTilesetsRaw.GetType() }, { "utyp", bloodmage.StatsUnitClassificationRaw.GetType() }, { "utar", bloodmage.CombatTargetedAsRaw.GetType() }, // Workshop { "ures", workshop.TechtreeResearchesAvailableRaw.GetType() }, { "upap", workshop.PathingPlacementRequiresRaw.GetType() }, { "upar", workshop.PathingPlacementPreventedByRaw.GetType() }, // Arcane vault { "umki", arcaneVault.TechtreeItemsMadeRaw.GetType() }, }; foreach (var unit in objectData.GetAllUnits()) { var actualUnit = db.GetUnit(unit.OldId); foreach (var mod in unit.Modifications) { if (expectUnit.TryGetValue(mod.Id.ToRawcode(), out var type)) { if (mod.Type != ObjectDataType.String) { errorLines.Add($"'{mod.Id.ToRawcode()}' TYPE: Expected {mod.Type}, actual {type}."); } var actualMod = actualUnit.Modifications[mod.Id]; var value = actualMod.Value; if (!object.Equals(mod.Value, value)) { errorLines.Add($"'{mod.Id.ToRawcode()}' VALUE: Expected {{{mod.Value}}}, actual {{{value}}}."); Assert.AreNotEqual(mod.Value.ToString(), value.ToString()); } } else { Assert.Fail($"Key '{mod.Id.ToRawcode()}' not found."); } } } // Verify ability data var abilityData = objectData.AbilityData; // Empty lists test var aerialShackles = new Abilities.AerialShackles(db); aerialShackles.StatsBuffs[1] = Array.Empty <Buff>(); aerialShackles.ArtLightningEffects = Array.Empty <LightningEffect>(); var reveal = new Abilities.RevealArcaneTower(db); reveal.StatsEffects[1] = Array.Empty <Buff>(); // Non-empty lists test var stormHammers = new Abilities.StormHammers(db); stormHammers.StatsBuffs[1] = new[] { new Buff(BuffType.AcidBomb), new Buff(BuffType.AntiMagicShell) }; stormHammers.StatsEffects[1] = new[] { new Buff(BuffType.Blizzard_XHbz), new Buff(BuffType.CloudOfFog_Xclf) }; stormHammers.ArtLightningEffects = new[] { LightningEffect.AFOD, LightningEffect.SPLK }; var expectAbility = new Dictionary <string, Type>() { { "abuf", stormHammers.StatsBuffsRaw[1].GetType() }, { "aeff", stormHammers.StatsEffectsRaw[1].GetType() }, { "alig", stormHammers.ArtLightningEffectsRaw.GetType() }, }; foreach (var ability in objectData.GetAllAbilities()) { var actualAbility = db.GetAbility(ability.OldId) ?? throw new NullReferenceException(ability.OldId.ToRawcode()); foreach (var mod in ability.Modifications) { if (expectAbility.TryGetValue(mod.Id.ToRawcode(), out var type)) { if (mod.Type != ObjectDataType.String) { errorLines.Add($"'{mod.Id.ToRawcode()}' TYPE: Expected {mod.Type}, actual {type}."); } var actualMod = mod.Level > 0 ? actualAbility.Modifications[mod.Id, mod.Level] : actualAbility.Modifications[mod.Id]; var value = actualMod.Value; if (!object.Equals(mod.Value, value)) { errorLines.Add($"'{mod.Id.ToRawcode()}' VALUE: Expected {{{mod.Value}}}, actual {{{value}}}."); Assert.AreNotEqual(mod.Value.ToString(), value.ToString()); } } else { Assert.Fail($"Key '{mod.Id.ToRawcode()}' not found."); } } } Assert.AreEqual(0, errorLines.Count, string.Join("\r\n ", errorLines.Prepend("\r\nFound one or more errors:"))); }
public override void Run(Window window) { Conformant conformant = new Conformant(window); conformant.Show(); Box box = new Box(window) { AlignmentX = -1, AlignmentY = -1, WeightX = 1, WeightY = 1, }; box.Show(); conformant.SetContent(box); List list = new List(window) { AlignmentX = -1, AlignmentY = -1, WeightX = 1, WeightY = 1 }; for (int i = 0; i < 5; i++) { list.Append(string.Format("{0} item", _count++)); } list.ItemSelected += List_Selected; list.ItemUnselected += List_Unselected; list.ItemActivated += List_ItemActivated; list.ItemDoubleClicked += List_ItemDoubleClicked; list.ItemLongPressed += List_ItemLongPressed; list.RenderPost += List_RenderPost; list.Update(); list.Show(); box.PackEnd(list); Button append = new Button(window) { Text = "Append", AlignmentX = -1, WeightX = 1, }; Button prepend = new Button(window) { Text = "Prepend", AlignmentX = -1, WeightX = 1, }; append.Clicked += (s, e) => { list.Append(string.Format("{0} item", _count++)); list.Update(); }; prepend.Clicked += (s, e) => { list.Prepend(string.Format("{0} item", _count++)); list.Update(); }; append.Show(); prepend.Show(); box.PackEnd(append); box.PackEnd(prepend); }
public bool Compile(ProjectContext context, string config, string buildBasePath) { // Set up Output Paths var outputPaths = context.GetOutputPaths(config, buildBasePath); var outputPath = outputPaths.CompilationOutputPath; var intermediateOutputPath = outputPaths.IntermediateOutputDirectoryPath; Directory.CreateDirectory(outputPath); Directory.CreateDirectory(intermediateOutputPath); // Create the library exporter var exporter = context.CreateExporter(config, buildBasePath); // Gather exports for the project var dependencies = exporter.GetDependencies().ToList(); var diagnostics = new List <DiagnosticMessage>(); var missingFrameworkDiagnostics = new List <DiagnosticMessage>(); // Collect dependency diagnostics foreach (var diag in context.LibraryManager.GetAllDiagnostics()) { if (diag.ErrorCode == ErrorCodes.DOTNET1011 || diag.ErrorCode == ErrorCodes.DOTNET1012) { missingFrameworkDiagnostics.Add(diag); } diagnostics.Add(diag); } if (diagnostics.Any(d => d.Severity == DiagnosticMessageSeverity.Error)) { // We got an unresolved dependency or missing framework. Don't continue the compilation. return(false); } // Get compilation options var outputName = outputPaths.CompilationFiles.Assembly; var compilationOptions = context.ResolveCompilationOptions(config); // Set default platform if it isn't already set and we're on desktop if (compilationOptions.EmitEntryPoint == true && string.IsNullOrEmpty(compilationOptions.Platform) && context.TargetFramework.IsDesktop()) { // See https://github.com/dotnet/cli/issues/2428 for more details. compilationOptions.Platform = RuntimeInformation.ProcessArchitecture == Architecture.X64 ? "x64" : "anycpu32bitpreferred"; } var references = new List <string>(); var sourceFiles = new List <string>(); // Add metadata options var assemblyInfoOptions = AssemblyInfoOptions.CreateForProject(context); foreach (var dependency in dependencies) { references.AddRange(dependency.CompilationAssemblies.Select(r => r.ResolvedPath)); sourceFiles.AddRange(dependency.SourceReferences.Select(s => s.GetTransformedFile(intermediateOutputPath))); } var resources = new List <string>(); if (compilationOptions.PreserveCompilationContext == true) { var allExports = exporter.GetAllExports().ToList(); var dependencyContext = new DependencyContextBuilder().Build(compilationOptions, allExports, allExports, false, // For now, just assume non-portable mode in the legacy deps file (this is going away soon anyway) context.TargetFramework, context.RuntimeIdentifier ?? string.Empty); var writer = new DependencyContextWriter(); var depsJsonFile = Path.Combine(intermediateOutputPath, compilationOptions.OutputName + "dotnet-compile.deps.json"); using (var fileStream = File.Create(depsJsonFile)) { writer.Write(dependencyContext, fileStream); } resources.Add($"\"{depsJsonFile}\",{compilationOptions.OutputName}.deps.json"); } // Add project source files if (compilationOptions.CompileInclude == null) { sourceFiles.AddRange(context.ProjectFile.Files.SourceFiles); } else { var includeFiles = IncludeFilesResolver.GetIncludeFiles(compilationOptions.CompileInclude, "/", diagnostics: null); sourceFiles.AddRange(includeFiles.Select(f => f.SourcePath)); } if (String.IsNullOrEmpty(intermediateOutputPath)) { return(false); } var translated = TranslateCommonOptions(compilationOptions, outputName); var allArgs = new List <string>(translated); allArgs.AddRange(GetDefaultOptions()); // Generate assembly info var assemblyInfo = Path.Combine(intermediateOutputPath, $"dotnet-compile.assemblyinfo.cs"); File.WriteAllText(assemblyInfo, AssemblyInfoFileGenerator.GenerateCSharp(assemblyInfoOptions, sourceFiles)); allArgs.Add($"\"{assemblyInfo}\""); if (!String.IsNullOrEmpty(outputName)) { allArgs.Add($"-out:\"{outputName}\""); } allArgs.AddRange(references.Select(r => $"-r:\"{r}\"")); allArgs.AddRange(resources.Select(resource => $"-resource:{resource}")); allArgs.AddRange(sourceFiles.Select(s => $"\"{s}\"")); allArgs.Prepend($"-noconfig"); // Execute CSC! var result = RunCsc(allArgs.ToArray()) .WorkingDirectory(Directory.GetCurrentDirectory()) .ForwardStdErr() .ForwardStdOut() .Execute(); return(result.ExitCode == 0); }
// Because of AC layouts, it’s the most difficult bit of guessing. Basic track without layouts, // track with layouts, extra layout for a multi-layout track, basic track for a multi-layout track (as a layout), // extra layout for a basic track… private async Task <ContentEntryBase> CheckDirectoryNodeForTrack(DirectoryNode directory, CancellationToken cancellation) { var ui = directory.GetSubDirectory("ui"); if (ui == null) { return(null); } Logging.Write("Candidate to be a track: " + directory.Key); // First of all, let’s find out if it’s a track at all var uiTrack = ui.GetSubFile("ui_track.json"); var uiTrackSubs = ui.Directories.Select(x => x.GetSubFile("ui_track.json")).NonNull().ToList(); if (uiTrack == null && uiTrackSubs.Count == 0) { // It’s not a track Logging.Write("Not a track"); return(null); } // INI-files with modes var iniTrack = uiTrack == null ? null : directory.GetSubFile("models.ini"); var iniTrackSubs = new List <FileNode>(); for (var i = uiTrackSubs.Count - 1; i >= 0; i--) { var layoutName = uiTrackSubs[i].Parent.NameLowerCase; var models = directory.GetSubFile($"models_{layoutName}.ini"); if (models == null) { uiTrackSubs.RemoveAt(i); } else { iniTrackSubs.Add(models); } } // Let’s get missing content stuff out of the way (we’ll still keep throwing that exception // later if needed, this piece is just to ensure all required files are asked for in the first pass) var missingContent = uiTrack?.Info.IsAvailable() == false | iniTrack?.Info.IsAvailable() == false | uiTrackSubs.Aggregate(false, (v, x) => v | !x.Info.IsAvailable()) | iniTrackSubs.Aggregate(false, (v, x) => v | !x.Info.IsAvailable()); if (missingContent) { // And, if it’s just a first step, let’s ask for outlines as well foreach (var node in uiTrackSubs.Append(uiTrack).NonNull()) { node.GetSibling("outline.png")?.Info.IsAvailable(); } Logging.Write("Missing content…"); throw new MissingContentException(); } // It’s a track, let’s find out layout IDs // var layoutLowerCaseIds = uiTrackSubs.Select(x => x.Parent.NameLowerCase).ToList(); // And track ID (so far, without layouts) var trackId = directory.Name; if (trackId == null) { Logging.Write("Directory’s name is null, let’s try to guess track’s ID"); if (iniTrack != null || iniTrackSubs.Count > 0) { // Looks like KN5 are referenced via ini-files, we can’t rely on KN5 name to determine // missing track ID // UPD: Let’s try anyway, by looking for the biggest referenced KN5-file with an unusual name Logging.Debug("CAN’T FOUND PROPER TRACK ID NOWHERE! LET’S TRY TO GUESS…"); bool IsNameUnusual(string name) { var n = name.ToLowerInvariant().ApartFromLast(".kn5"); if (n.Length < 5) { // Could be some sort of shortening. return(false); } if (n.Contains(" ")) { // It might be the right name, but it’s unlikely. return(false); } if (double.TryParse(n, NumberStyles.Any, CultureInfo.InvariantCulture, out double v)) { // Numbers: 0.kn5, 10.kn5, … // Kunos name their extra files like that. return(false); } var marks = "drift|circuit|sprint|race|trackday|full|layout|start|trees|grass|normal|reverse|chicane|oval|wet|dtm|gp|pit"; if (Regex.IsMatch(n, $@"^(?:{marks})(?![a-z])|(?<![a-z])(?:{marks})$")) { // Might look like some extra layouts. return(false); } return(true); } var potentialId = (await iniTrackSubs.Prepend(iniTrack).NonNull().Select(x => x.Info.ReadAsync()).WhenAll()) .SelectMany(x => TrackContentEntry.GetLayoutModelsNames(IniFile.Parse(x.ToUtf8String())).ToList()) .Distinct().Where(IsNameUnusual).OrderByDescending(x => directory.GetSubFile(x)?.Info.Size) .FirstOrDefault()?.ToLowerInvariant().ApartFromLast(".kn5"); if (potentialId != null) { trackId = potentialId; } else { Logging.Write("Can’t determine ID because of ini-files"); return(null); } } else { trackId = directory.Files.Where(x => x.NameLowerCase.EndsWith(".kn5")).OrderByDescending(x => x.Size) .FirstOrDefault()?.NameLowerCase.ApartFromLast(".kn5"); if (trackId == null) { Logging.Write("Can’t determine ID"); return(null); } } Logging.Write("Guessed ID: " + trackId); } Logging.Write("Track ID: " + directory.Name); // Some functions async Task <Tuple <string, string, byte[]> > LoadNameVersionIcon(FileNode uiFile) { var icon = await(uiFile.GetSibling("outline.png")?.Info.ReadAsync() ?? Task.FromResult((byte[])null)); var data = await uiFile.Info.ReadAsync() ?? throw new MissingContentException(); var parsed = JsonExtension.Parse(data.ToUtf8String()); cancellation.ThrowIfCancellationRequested(); return(Tuple.Create(parsed.GetStringValueOnly("name"), parsed.GetStringValueOnly("version"), icon)); } // Tuple: (models in array; required, but missing models) async Task <Tuple <List <string>, List <string> > > LoadModelsIni(FileNode node) { var data = node == null ? null : await node.Info.ReadAsync(); cancellation.ThrowIfCancellationRequested(); if (data == null) { return(null); } var names = TrackContentEntry.GetModelsNames(IniFile.Parse(data.ToUtf8String())).ToList(); var existing = names.Where(directory.HasSubFile).ToList(); return(Tuple.Create(existing, names.ApartFrom(existing).ToList())); } Task <Tuple <List <string>, List <string> > > LoadMainModelsIni() { if (iniTrack != null) { return(LoadModelsIni(iniTrack)); } var name = $@"{trackId}.kn5"; return(Task.FromResult(directory.HasSubFile(name) ? Tuple.Create(new List <string> { name }, new List <string>(0)) : Tuple.Create(new List <string>(0), new List <string> { name }))); } if (uiTrack != null && uiTrackSubs.Count == 0) { // It’s a basic track, no layouts Logging.Write("Basic type of track"); var nvi = await LoadNameVersionIcon(uiTrack); var models = await LoadMainModelsIni(); return(await TrackContentEntry.Create(directory.Key ?? "", trackId, models.Item1, models.Item2, nvi.Item1, nvi.Item2, nvi.Item3)); } // Let’s prepare layouts if (uiTrackSubs.Count == 0) { Logging.Write("Layouts not found"); return(null); } // It’s a basic track, no layouts Logging.Write("Layouts"); var layouts = new List <TrackContentLayoutEntry>(uiTrackSubs.Count); for (var i = 0; i < uiTrackSubs.Count; i++) { var sub = uiTrackSubs[i]; var nvi = await LoadNameVersionIcon(sub); var models = await LoadModelsIni(iniTrackSubs[i]); layouts.Add(new TrackContentLayoutEntry(sub.Parent.Name ?? "-", models.Item1, models.Item2, nvi.Item1, nvi.Item2, nvi.Item3)); } if (uiTrack != null) { var nvi = await LoadNameVersionIcon(uiTrack); var models = await LoadMainModelsIni(); layouts.Add(new TrackContentLayoutEntry("", models.Item1, models.Item2, nvi.Item1, nvi.Item2, nvi.Item3)); } return(await TrackContentEntry.Create(directory.Key ?? "", trackId, layouts)); }
static void Main(string[] args) { List <string> names = new List <string> { "Vlad", "Dasha", "Mimimi", "Dasha", }; List <int> ages1 = new List <int> { 1, 2, 3, 4, 5, 6, }; List <int> ages2 = new List <int> { 3, 4, 5, }; int i = 1; var newAges1 = ages1.Where(x => x < 4).Reverse().Union(ages2).Select(x => Convert.ToString($"{i++}. {x}")).Union(names).Skip(1).Distinct().OrderByDescending(x => x.Contains("a")).ThenBy(x => x); //Console.WriteLine(string.Join(Environment.NewLine, newAges1)); var newAges2 = ages1.Where(x => x < 4); // newAges2 is IEnuberable, that have all elements in ages1 that < 4 var newAges3 = ages1.Where(x => x < 4).Reverse(); // And reverse (change to the opposite) var newAges4 = ages1.Where(x => x < 4).Reverse().Union(ages2); // And add ages2 without repetition var newAges5 = ages1.Where(x => x < 4).Reverse().Union(ages2).Select(x => Convert.ToString($"{i++}. {x}")); // And Convert to string and add numbering var newAges6 = ages1.Where(x => x < 4).Reverse().Union(ages2).Select(x => Convert.ToString($"{i++}. {x}")).Skip(1); // And skip first element var newAges7 = ages1.Where(x => x < 4).Reverse().Union(ages2).Select(x => Convert.ToString($"{i++}. {x}")).Skip(1).Distinct(); // And delete all distinction var newAges8 = ages1.Where(x => x < 4).Reverse().Union(ages2).Select(x => Convert.ToString($"{i++}. {x}")).Skip(1).Distinct().OrderByDescending(x => x.Contains("1")); // And first all elements, that have 1 var newAges9 = ages1.Where(x => x < 4).Reverse().Union(ages2).Select(x => Convert.ToString($"{i++}. {x}")).Skip(1).Distinct().OrderByDescending(x => x.Contains("1")).ThenBy(x => x); // And to alphabetically var newAges10 = ages1.Count(); // Count all elements var newAges11 = ages1.Sum(); // Sum all elements var newAges12 = ages1.Take(6); // Take 6 elements, if elements are small than 6, take all elements var newAges13 = ages1.Aggregate((x, y) => y > x ? y : x); // If y > x, x = y, else x = x var newAges14 = ages1.Aggregate(10, (x, y) => y > x ? y : x); // x = 10, if y > x, x = y, else x = x, return x var newAges15 = ages1.All(x => x == 5); // If all elements have 5 return true, else - return false var newAges16 = ages1.Any(x => x == 2); // If any elements have 2 return true, else - return false var newAges17 = ages1.Append(4); // Add 4 var newAges18 = ages1.AsEnumerable(); // Convert to IEnumerable var newAges19 = ages1.AsParallel(); // var newAges20 = ages1.AsQueryable(); // Convert to Queryable var newAges21 = ages1.Average(); // Return average (середнє значення) var newAges22 = ages1.Cast <long>(); // Casts the elements of an IEnumerable to the long type var newAges23 = ages1.Concat(ages2); // Add IEnumerable<T> to IEnumerable<t> (ages2 to ages1) var newAges24 = ages1.ElementAt(0); // Take 1 element var newAges25 = ages1.ElementAtOrDefault(50); // Take some element by the index, if index is OutOfRange - element is equal null/0 var newAges26 = ages1.First(); // Take first element var newAges27 = ages1.FirstOrDefault(); // Take first element, if element is OutOfRange - element is equal null/0 var newAges28 = ages1.Last(); // Take last element var newAges29 = ages1.LastOrDefault(); // Take last element, if last element is OutOfRange - element is equal null/0 var newAges30 = ages1.Except(ages2); // All elements ages1, except ages2 //var newAges31 = ages1.GroupJoin(); // var newAges32 = ages1.Intersect(ages2); // Is intersect ages1 and ages2 //var newAges33 = ages1.Join(ages2, x => x, p => p, (x,p) => Convert.ToString($"{x} + {p} = {x+p}")); // If element ages1 = elevement ages2 return their sum var newAges34 = ages1.LongCount(); // Return count elements in long var newAges35 = ages1.Max(); // Max element var newAges36 = ages1.Max <int>(); // Max element var newAges37 = ages1.Min(); // Min element var newAges38 = ages1.Min <int>(); // Min element //var newAges39 = ages1.OfType<long>(); // var newAges40 = ages1.Prepend(2); // Adds element to the beginning IEnumerable //var newAges41 = ages1.Reverse(); // var newAges42 = ages1.Select(x => Convert.ToString($"Element - {x}")); // //var newAges43 = ages1.SelectMany(); // var newAges44 = ages1.SequenceEqual(ages2); // var newAges45 = ages1.Single(x => x == 5); // If IEnumerable has 1 element "5", return 5. If IEnumerable has't element 5, return InvalidOperationException. If IEnumerable has 2 element 5, return InvalidOperationException: var newAges46 = ages1.SingleOrDefault(x => x == 5); // If IEnumerable has 1 element "5", return 5. If IEnumerable has't element 5, return null/0. If IEnumerable has 2 element 5, return InvalidOperationException: var newAges47 = ages1.Skip(5); // Skip 5 element var newAges48 = ages1.SkipWhile(x => x * x < 7); // Skip all elements that, when raised to a degree less than 7 var newAges50 = ages1.Sum(); // Sum all elements var newAges51 = ages1.Take(3); // Take first 3 elements var newAges52 = ages1.TakeWhile(x => x * x < 7); // Take first elements that, when raised to a degree less than 7 var newAges53 = ages1.Union(ages2); // Sum all elements ages1 and ages2 without repetition var newAges54 = ages1.Where(x => x == 3); // Return all elements are equal 3 var newAges55 = ages1.Zip(ages2, (x, y) => x + y); // Add element x to element y Console.WriteLine(string.Join(Environment.NewLine, newAges55)); Console.WriteLine(); List <int> agees = new List <int> { 54, 12, 23, 12, }; var test = agees.GroupBy(g => g).Where(g => g.Count() > 1).Select(g => g.Key); // test is Enumerable, that have all elements, that are more 1 in agees Console.WriteLine(string.Join(Environment.NewLine, test)); Console.ReadKey(); }
private bool Initialize(ApplicationData currentTrade, ApplicationHistory tradeHistory) { _data.Clear(); _computedChain.Clear(); Dictionary <ulong, ulong> prevMonthList = null; if (tradeHistory.Count() > 0) { prevMonthList = FillPreviousTradesPairs(currentTrade, tradeHistory.GetTrade(0)); } Dictionary <ulong, ulong> prevPrevMonthList = null; if (tradeHistory.Count() > 1) { prevPrevMonthList = FillPreviousTradesPairs(currentTrade, tradeHistory.GetTrade(1)); } Dictionary <UserData, List <ulong> > tmpData = new Dictionary <UserData, List <ulong> >(); foreach (UserData user1 in currentTrade.GetStorage()) { List <ulong> candidate = new List <ulong>(); ulong prevPartner = 0; if (prevMonthList != null) { prevMonthList.TryGetValue(user1.UserId, out prevPartner); } ulong prevPrevPartner = 0; if (prevPrevMonthList != null) { prevPrevMonthList.TryGetValue(user1.UserId, out prevPrevPartner); } bool bPushBack = false; foreach (UserData user2 in currentTrade.GetStorage()) { if (user2.UserId == user1.UserId || user2.UserId == prevPartner || user2.UserId == user1.PreferenceId) { continue; } if (user2.UserId == prevPrevPartner) { bPushBack = true; } else { candidate.Add(user2.UserId); } } candidate = candidate.OrderBy(x => Guid.NewGuid()).ToList(); if (bPushBack) { candidate.Add(prevPrevPartner); } if (user1.PreferenceId != 0) { candidate = candidate.Prepend(user1.PreferenceId).ToList(); } if (candidate.Count == 0) { return(false); } tmpData.Add(user1, candidate); } if (tmpData.Count == 0) { return(false); } // order by number of candidates first, if someone had someone else as a partner las trade, it is removed from candidates this trade foreach (var byCount in tmpData.GroupBy(x => x.Value.Count)) { foreach (var byPreference in byCount.GroupBy(x => x.Key.PreferenceId != 0)) { foreach (var dat in byPreference.OrderBy(x => Guid.NewGuid())) { _data.Add(dat.Key.UserId, dat.Value); } } } //_data = _data.OrderBy(x => x.Value.Count).ToDictionary(x => x.Key, x => x.Value); return(true); }
static void Main(string[] args) { /* * This program gets 2 inputs: * List of all functions in cleaned format from IDA Pro as a list: * <function_name> <address> <length> * * And trace block information in cleaned format from DynamoRIO block tracking tool "drcov": * <block_adress> * * No other input is neccesary. * * Program outputs a graph in .dot format to be used with any GraphViz visualizer. * * There is sample input and output included in this repository. * * All numbers are in base 16. Detailed information about this algorithm can be found in the masters thesis: * MACHINE CODE INSTRUMENTATION FOR BLOCK RUNTIME STATISTICAL ANALYSIS AND PREDICTION */ // Input const string FUNCTION_LIST_INPUT_PATH = @"C:\Users\edza\Desktop\mag\case_study_big\fun_list_all.txt"; const string TRACED_BLOCKS_INPUT_PATH = @"C:\Users\edza\Desktop\mag\case_study_big\doc_cleaned.log"; // Input seperator for function data columns <function_name>_SEPERATOR_<address>_SEPERATOR_<length> const string FUNCTION_SEPERATOR = "_SEPERATOR_"; // Output const string NODE_STATS_OUTPUT_PATH = @"C:\Users\edza\Desktop\mag\case_study_big\node_stats.txt"; const string GRAPH_OUTPUT_PATH = @"C:\Users\edza\Desktop\mag\case_study_big\graph.dot"; const string TABLE_OUTPUT_PATH = @"C:\Users\edza\Desktop\mag\case_study_big\node_table.txt"; const string NODE_LIST_OUTPUT_PATH = @"C:\Users\edza\Desktop\mag\case_study_big\node_sequence.txt"; // We want to create a list of all functions with their beginning and end adresses List <string> functionsAsText = File.ReadAllText(FUNCTION_LIST_INPUT_PATH) .Split('\n') .Select(l => l.Trim()) .ToList(); var functionTextPattern = new Regex($"([^\\s]+){FUNCTION_SEPERATOR}([^\\s]+){FUNCTION_SEPERATOR}([^\\s]+)"); List <MachineCodeFunction> functions = new List <MachineCodeFunction>(); foreach (string functionTextLine in functionsAsText) { var match = functionTextPattern.Match(functionTextLine); functions.Add(new MachineCodeFunction() { Name = match.Groups[1].Value, Start = Convert.ToInt64(match.Groups[2].Value, 16), End = Convert.ToInt64(match.Groups[2].Value, 16) + Convert.ToInt64(match.Groups[3].Value, 16), }); } // We know have a block trace, for each block we figure out which function that is and replace it with a function List <string> linesBlocks = File.ReadAllText(TRACED_BLOCKS_INPUT_PATH) .Split('\n', StringSplitOptions.RemoveEmptyEntries) .Select(l => l.Trim()) .ToList(); List <MachineCodeFunction> functionSequence = new List <MachineCodeFunction>(); foreach (string block in linesBlocks) { long address = Convert.ToInt64(block, 16); foreach (MachineCodeFunction idaFun in functions) { if (address >= idaFun.Start && address <= idaFun.End) { functionSequence.Add(idaFun); break; } } } // Add start and end functionSequence = functionSequence.Prepend(new MachineCodeFunction(customShortName: "Start") { Name = "Start", }).ToList(); functionSequence = functionSequence.Append(new MachineCodeFunction(customShortName: "Exit") { Name = "Exit", }).ToList(); // Now we reduce the function trace list by removing repeating blocks within the same func (eg. A A A B B C A A -> A B C A) List <MachineCodeFunction> functionListBlocksJoined = new List <MachineCodeFunction>(); foreach (var function in functionSequence) { if (functionListBlocksJoined.Count == 0 || functionListBlocksJoined.Last() != function) { functionListBlocksJoined.Add(function); } } string outputNodeSeq = string.Empty; foreach (var function in functionListBlocksJoined) { outputNodeSeq += function.ShortName + Environment.NewLine; } File.WriteAllText(NODE_LIST_OUTPUT_PATH, outputNodeSeq); string nodeStats = string.Empty; // We also calculate how often each function is called and store that as extra info functionListBlocksJoined.GroupBy(fun => fun) .ToList() .ForEach(functionCalls => { var info = functionCalls.First(); info.Calls = functionCalls.Count(); nodeStats += $"Node nr. {info.ShortName} ({info.Name}), called count: {info.Calls}\r\n"; }); // Then calculate avarage and stdev, if it's more than 1 stdev color change, 2 stdev extra color change var uniqueFunctions = functionListBlocksJoined.Distinct().ToList(); (double stdev, double avarage) = GetStandardDeviation(uniqueFunctions.Select(node => (double)node.Calls).ToList()); nodeStats = $"Avarage calls: {avarage}, standard deviation: {stdev}\r\n" + nodeStats; foreach (var function in uniqueFunctions) { if (function.Calls > avarage + 2 * stdev) { function.NodeColor = DotColor.Green4; nodeStats += $"Node nr. {function.ShortName} ({function.Name}), is called 2 STDEV more than AVG.\r\n"; } else if (function.Calls > avarage + 1 * stdev) { function.NodeColor = DotColor.Olivedrab; nodeStats += $"Node nr. {function.ShortName} ({function.Name}), is called 1 STDEV more than AVG.\r\n"; } else if (function.Calls < avarage - 2 * stdev) { function.NodeColor = DotColor.Red1; nodeStats += $"Node nr. {function.ShortName} ({function.Name}), is called 2 STDEV less than AVG.\r\n"; } else if (function.Calls < avarage - 1 * stdev) { function.NodeColor = DotColor.Red4; nodeStats += $"Node nr. {function.ShortName} ({function.Name}), is called 1 STDEV less than AVG.\r\n"; } } File.WriteAllText(NODE_STATS_OUTPUT_PATH, nodeStats); // For each node calculate all its successors for table visualization for (int i = 0; i < functionListBlocksJoined.Count; i++) { var @this = functionListBlocksJoined[i]; if (i + 1 != functionListBlocksJoined.Count) { @this.Next.Add(functionListBlocksJoined[i + 1]); } } string outputTable = string.Empty; var uniqueFunctionsNoRepeatingBlocks = functionListBlocksJoined.Distinct(); List <(MachineCodeFunction, List <MachineCodeFunctionGrouping>)> graphAsTable = new List <(MachineCodeFunction, List <MachineCodeFunctionGrouping>)> (); foreach (var function in uniqueFunctionsNoRepeatingBlocks) { List <MachineCodeFunctionGrouping> tableEntry = function.Next.GroupBy( functionNext => functionNext, functionNext => functionNext, (key, grouping) => new MachineCodeFunctionGrouping { ShortName = key.ShortName, PreviousElement = function.ShortName, NodeColor = function.NodeColor, Key = key, Probability = grouping.Count() / (double)function.Next.Count }).ToList(); outputTable += function.ShortName + Environment.NewLine; foreach (var group in tableEntry) { outputTable += group.ShortName + $" {Math.Round(group.Probability, 2)} "; } outputTable += Environment.NewLine; graphAsTable.Add((function, tableEntry)); } File.WriteAllText(TABLE_OUTPUT_PATH, outputTable); // GraphViz export var directedGraph = new DotGraph("BlockTraceGraph", true); foreach (var(node, _) in graphAsTable) { var graphNode = new DotNode(node.ShortName) { Shape = DotNodeShape.Ellipse, Label = node.ShortName + $"({node.Calls})", // FillColor = node.NodeColor != null ? DotColor.Grey100 : DotColor.White, FontColor = node.NodeColor ?? DotColor.Black, Style = (node.NodeColor != null ? DotNodeStyle.Bold : DotNodeStyle.Default), Height = 0.5f, }; directedGraph.Add(graphNode); } foreach (var(_, edges) in graphAsTable) { // Let's do some coloring // If all edges have the same weights color blue // If there is one and ONLY one that is higher prob than everyone then GREEN // if there is one and ONLY one that is higher prob than everyone then RED // If only GREY bool areAllSameProbability = edges.All(e => e.Probability == edges[0].Probability); if (!areAllSameProbability) { var maxProbability = edges.Max(e => e.Probability); var isOnly = edges.Count(e => e.Probability == maxProbability) == 1; if (isOnly) { edges.First(e => e.Probability == maxProbability).Color = DotColor.Green3; } var minProbability = edges.Min(e => e.Probability); var isOnlyMin = edges.Count(e => e.Probability == minProbability) == 1; if (isOnlyMin) { edges.First(e => e.Probability == minProbability).Color = DotColor.Red1; } } foreach (var edge in edges) { var arrow = new DotArrow(edge.PreviousElement, edge.ShortName) { ArrowLabel = Math.Round(edge.Probability, 2).ToString() }; if (areAllSameProbability) { arrow.ArrowColor = DotColor.Blue; } if (edge.Color != null) { arrow.ArrowColor = edge.Color.Value; } if (edges.Count == 1) { arrow.ArrowColor = DotColor.Gray; } directedGraph.Add(arrow); } } // Indented version var dot = directedGraph.Compile(false); // Save it to a file File.WriteAllText(GRAPH_OUTPUT_PATH, dot); }
private LNode Term() { TokenType la0; LNode first = default(LNode); List <LNode> rest = new List <LNode>(); LNode result = default(LNode); // Line 222: ( TT.Id | TT.Num | TT.LBrace TT.RBrace | TT.LBrace Expr (TT.Comma Expr)* TT.RBrace | TT.LParen Expr TT.RParen ) do { la0 = (TokenType)LA0; if (la0 == TT.Id) { var t = MatchAny(); // line 222 result = F.Id(t); } else if (la0 == TT.Num) { var t = MatchAny(); // line 223 result = F.Literal(t); } else if (la0 == TT.LBrace) { switch ((TokenType)LA(1)) { case TT.RBrace: { Skip(); Skip(); // line 224 result = F.AltList(); } break; case TT.Id: case TT.LBrace: case TT.LParen: case TT.Num: case TT.Sub: { Skip(); first = Expr(); // Line 225: (TT.Comma Expr)* for (;;) { la0 = (TokenType)LA0; if (la0 == TT.Comma) { Skip(); rest.Add(Expr()); } else { break; } } Match((int)TT.RBrace); // line 225 result = F.AltList(rest?.Prepend(first) ?? Enumerable.Repeat(first, 1)); } break; default: goto error; } } else if (la0 == TT.LParen) { Skip(); result = Expr(); Match((int)TT.RParen); // line 226 result = F.InParens(result); } else { goto error; } break; error: { // line 227 result = F.Missing; Error(0, "Expected identifer, number, or (parens)"); } } while (false); return(result); }
private void BuildResult(OptimizationResult output, int numberOfRoutes, GRBVar[][] w, GRBVar[][] c) { var routes = new List <Route>(); for (int s = 0; s < numberOfRoutes; s++) { Debug.WriteLine($"Santa {s} uses way"); var route = new Route(); var wpList = new List <Waypoint>(); route.SantaId = s % input.Santas.Length; var lastId = 0; var day = s / input.Santas.Length; do { var(id, startingTime) = GetNextVisit(lastId, w[s], c[s]); if (id == 0) { // if last visit var lastVisit = input.Visits[lastId - 1]; wpList.Add(new Waypoint { StartTime = wpList.Last().StartTime + lastVisit.Duration + lastVisit.WayCostToHome, VisitId = id - 1 }); } else { wpList.Add(new Waypoint { StartTime = startingTime + input.Days[day].from, VisitId = id - 1 }); } lastId = id; } while (lastId != 0 && lastId != -1); if (wpList.Count == 0 || lastId == -1) { continue; } var firstWaypoint = wpList.First(); var firstVisit = input.Visits[firstWaypoint.VisitId]; route.Waypoints = wpList .Prepend(new Waypoint { StartTime = firstWaypoint.StartTime - firstVisit.WayCostFromHome, VisitId = Constants.VisitIdHome }) .ToArray(); routes.Add(route); for (int i = 0; i < distances.GetLength(0); i++) { for (int j = 0; j < distances.GetLength(1); j++) { if (Math.Round(AccessW(w[s], i, j).X, 0) > 0) { Debug.WriteLine($"[{i},{j}]=\t{c[s][j].X}"); } } } } output.Routes = routes.ToArray(); }
private static List <BreakPoint> GetResultBreaks(PiecewiseFunction f, PiecewiseFunction g) { var resultBreaks = new List <BreakPoint>(); var fbreaks = f.GetBreakPointsExtended(); var gbreaks = g.GetBreakPointsExtended(); var hasMinusInfinity = false; var hasPlusInfinity = false; // Проходим по точкам функции f foreach (var fbreak in fbreaks) { if (double.IsNegativeInfinity(fbreak.X)) { hasMinusInfinity = true; continue; } if (double.IsPositiveInfinity(fbreak.X)) { hasPlusInfinity = true; continue; } // Проходим по точкам функции g foreach (var gbreak in gbreaks) { if (double.IsNegativeInfinity(gbreak.X)) { hasMinusInfinity = true; continue; } if (double.IsPositiveInfinity(gbreak.X)) { hasPlusInfinity = true; continue; } // здесь будет добавлена обработка функций Дирака var newBreak = new BreakPoint(fbreak.X + gbreak.X, false, false); resultBreaks.Add(newBreak); } } // нужно возвращать уникальные и отсортированные точки resultBreaks.Sort(delegate(BreakPoint b1, BreakPoint b2) { return(b1.X.CompareTo(b2.X)); }); if (hasMinusInfinity) { resultBreaks = resultBreaks.Prepend(new BreakPoint(double.NegativeInfinity, false, false)).ToList(); } if (hasPlusInfinity) { resultBreaks = resultBreaks.Append(new BreakPoint(double.PositiveInfinity, false, false)).ToList(); } var uniqueBreakPoints = GetUniqueBreakPoints(resultBreaks); return(uniqueBreakPoints); }
public bool Compile(ProjectContext context, string config, string buildBasePath) { // Set up Output Paths var outputPaths = context.GetOutputPaths(config, buildBasePath); var outputPath = outputPaths.CompilationOutputPath; var intermediateOutputPath = outputPaths.IntermediateOutputDirectoryPath; Directory.CreateDirectory(outputPath); Directory.CreateDirectory(intermediateOutputPath); // Create the library exporter var exporter = context.CreateExporter(config, buildBasePath); // Gather exports for the project var dependencies = exporter.GetDependencies().ToList(); var diagnostics = new List<DiagnosticMessage>(); var missingFrameworkDiagnostics = new List<DiagnosticMessage>(); // Collect dependency diagnostics foreach (var diag in context.LibraryManager.GetAllDiagnostics()) { if (diag.ErrorCode == ErrorCodes.DOTNET1011 || diag.ErrorCode == ErrorCodes.DOTNET1012) { missingFrameworkDiagnostics.Add(diag); } diagnostics.Add(diag); } if(diagnostics.Any(d => d.Severity == DiagnosticMessageSeverity.Error)) { // We got an unresolved dependency or missing framework. Don't continue the compilation. return false; } // Get compilation options var outputName = outputPaths.CompilationFiles.Assembly; var compilationOptions = context.ResolveCompilationOptions(config); // Set default platform if it isn't already set and we're on desktop if (compilationOptions.EmitEntryPoint == true && string.IsNullOrEmpty(compilationOptions.Platform) && context.TargetFramework.IsDesktop()) { // See https://github.com/dotnet/cli/issues/2428 for more details. compilationOptions.Platform = RuntimeInformation.ProcessArchitecture == Architecture.X64 ? "x64" : "anycpu32bitpreferred"; } var references = new List<string>(); var sourceFiles = new List<string>(); // Add metadata options var assemblyInfoOptions = AssemblyInfoOptions.CreateForProject(context); foreach (var dependency in dependencies) { references.AddRange(dependency.CompilationAssemblies.Select(r => r.ResolvedPath)); sourceFiles.AddRange(dependency.SourceReferences.Select(s => s.GetTransformedFile(intermediateOutputPath))); } var resources = new List<string>(); if (compilationOptions.PreserveCompilationContext == true) { var allExports = exporter.GetAllExports().ToList(); var dependencyContext = new DependencyContextBuilder().Build(compilationOptions, allExports, allExports, false, // For now, just assume non-portable mode in the legacy deps file (this is going away soon anyway) context.TargetFramework, context.RuntimeIdentifier ?? string.Empty); var writer = new DependencyContextWriter(); var depsJsonFile = Path.Combine(intermediateOutputPath, compilationOptions.OutputName + "dotnet-compile.deps.json"); using (var fileStream = File.Create(depsJsonFile)) { writer.Write(dependencyContext, fileStream); } resources.Add($"\"{depsJsonFile}\",{compilationOptions.OutputName}.deps.json"); } // Add project source files if (compilationOptions.CompileInclude == null) { sourceFiles.AddRange(context.ProjectFile.Files.SourceFiles); } else { var includeFiles = IncludeFilesResolver.GetIncludeFiles(compilationOptions.CompileInclude, "/", diagnostics: null); sourceFiles.AddRange(includeFiles.Select(f => f.SourcePath)); } if (String.IsNullOrEmpty(intermediateOutputPath)) { return false; } var translated = TranslateCommonOptions(compilationOptions, outputName); var allArgs = new List<string>(translated); allArgs.AddRange(GetDefaultOptions()); // Generate assembly info var assemblyInfo = Path.Combine(intermediateOutputPath, $"dotnet-compile.assemblyinfo.cs"); File.WriteAllText(assemblyInfo, AssemblyInfoFileGenerator.GenerateCSharp(assemblyInfoOptions, sourceFiles)); allArgs.Add($"\"{assemblyInfo}\""); if (!String.IsNullOrEmpty(outputName)) { allArgs.Add($"-out:\"{outputName}\""); } allArgs.AddRange(references.Select(r => $"-r:\"{r}\"")); allArgs.AddRange(resources.Select(resource => $"-resource:{resource}")); allArgs.AddRange(sourceFiles.Select(s => $"\"{s}\"")); allArgs.Prepend($"-noconfig"); // Execute CSC! var result = RunCsc(allArgs.ToArray()) .WorkingDirectory(Directory.GetCurrentDirectory()) .ForwardStdErr() .ForwardStdOut() .Execute(); return result.ExitCode == 0; }
public static void RegisterPlugin(IPlugin plugin, bool favorPlugins) { Signatures = (List <ISignature>)Signatures.Prepend(plugin.Signature); }
public IEnumerable <string> GetAllNames() { return(alternate_names.Prepend(name)); }
public void TestEnums() { var db = new ObjectDatabase(Array.Empty <int>(), null); const string TestFilePath = @"..\..\..\TestData\TestEnums.w3o"; using var fileStream = File.OpenRead(TestFilePath); using var binaryReader = new BinaryReader(fileStream); var objectData = binaryReader.ReadObjectData(false); var errorLines = new List <string>(); var castType = new Dictionary <Type, ObjectDataType> { { typeof(int), ObjectDataType.Int }, { typeof(string), ObjectDataType.String }, }; // Verify unit data var unitData = objectData.UnitData; var peasant = new Unit(UnitType.Peasant, db); peasant.ArtShadowImageUnit = ShadowImage.ShadowFlyer; peasant.CombatArmorType = ArmorType.Stone; peasant.CombatAttack1AttackType = AttackType.Hero; peasant.CombatAttacksEnabled = AttackBits.Attack2Only; peasant.PathingAIPlacementType = AiBuffer.Resource; peasant.ArtTeamColor = TeamColor.Player1Red; var paladin = new Unit(UnitType.Paladin, db); paladin.CombatAttack2WeaponSound = CombatSound.MetalLightChop; paladin.CombatDeathType = DeathType.CanRaiseDoesDecay; paladin.CombatDefenseType = DefenseType.Normal; paladin.MovementType = MoveType.Amph; paladin.StatsPrimaryAttribute = AttributeType.AGI; var altar = new Unit(UnitType.Altarofkings, db); altar.ArtModelFileExtraVersions = VersionFlags.ReignOfChaos | VersionFlags.TheFrozenThrone; altar.CombatAttack1WeaponType = WeaponType.Mline; altar.PathingPlacementPreventedBy = new[] { PathingType.Unbuildable, PathingType.Blighted }; altar.PathingPlacementRequires = Array.Empty <PathingType>(); altar.StatsHitPointsRegenerationType = RegenType.Night; altar.StatsRace = UnitRace.Other; altar.StatsUnitClassification = new[] { UnitClassification.Ancient, UnitClassification.Mechanical, UnitClassification.Peon }; var expectUnit = new Dictionary <string, ObjectDataType>() { // Peasant { "ushu", castType[peasant.ArtShadowImageUnitRaw.GetType()] }, { "uarm", castType[peasant.CombatArmorTypeRaw.GetType()] }, { "ua1t", castType[peasant.CombatAttack1AttackTypeRaw.GetType()] }, { "uaen", castType[peasant.CombatAttacksEnabledRaw.GetType()] }, { "uabt", castType[peasant.PathingAIPlacementTypeRaw.GetType()] }, { "utco", castType[peasant.ArtTeamColorRaw.GetType()] }, // Paladin { "ucs2", castType[paladin.CombatAttack2WeaponSoundRaw.GetType()] }, { "udea", castType[paladin.CombatDeathTypeRaw.GetType()] }, { "udty", castType[paladin.CombatDefenseTypeRaw.GetType()] }, { "umvt", castType[paladin.MovementTypeRaw.GetType()] }, { "upra", castType[paladin.StatsPrimaryAttributeRaw.GetType()] }, // Altar { "uver", castType[altar.ArtModelFileExtraVersionsRaw.GetType()] }, { "ua1w", castType[altar.CombatAttack1WeaponTypeRaw.GetType()] }, { "upar", castType[altar.PathingPlacementPreventedByRaw.GetType()] }, { "upap", castType[altar.PathingPlacementRequiresRaw.GetType()] }, { "uhrt", castType[altar.StatsHitPointsRegenerationTypeRaw.GetType()] }, { "urac", castType[altar.StatsRaceRaw.GetType()] }, { "utyp", castType[altar.StatsUnitClassificationRaw.GetType()] }, }; foreach (var unit in objectData.GetAllUnits()) { var actualUnit = db.GetUnit(unit.OldId); foreach (var mod in unit.Modifications) { if (expectUnit.TryGetValue(mod.Id.ToRawcode(), out var type)) { if (mod.Type != type) { errorLines.Add($"'{mod.Id.ToRawcode()}' TYPE: Expected {mod.Type}, actual {type}."); } var actualMod = actualUnit.Modifications[mod.Id]; var value = actualMod.Value; if (!object.Equals(mod.Value, value)) { errorLines.Add($"'{mod.Id.ToRawcode()}' VALUE: Expected {{{mod.Value}}}, actual {{{value}}}."); Assert.AreNotEqual(mod.Value.ToString(), value.ToString()); } } else { Assert.Fail($"Key '{mod.Id.ToRawcode()}' not found."); } } } // Verify item data var itemData = objectData.ItemData; var gauntlets = new Item(ItemType.GauntletsOfOgreStrength3, db); gauntlets.StatsClassification = ItemClass.Miscellaneous; var expectItem = new Dictionary <string, ObjectDataType>() { // Gauntlets { "icla", castType[gauntlets.StatsClassificationRaw.GetType()] }, }; foreach (var item in objectData.GetAllItems()) { var actualItem = db.GetItem(item.OldId); foreach (var mod in item.Modifications) { if (expectItem.TryGetValue(mod.Id.ToRawcode(), out var type)) { if (mod.Type != type) { errorLines.Add($"'{mod.Id.ToRawcode()}' TYPE: Expected {mod.Type}, actual {type}."); } var actualMod = actualItem.Modifications[mod.Id]; var value = actualMod.Value; if (!object.Equals(mod.Value, value)) { errorLines.Add($"'{mod.Id.ToRawcode()}' VALUE: Expected {{{mod.Value}}}, actual {{{value}}}."); Assert.AreNotEqual(mod.Value.ToString(), value.ToString()); } } else { Assert.Fail($"Key '{mod.Id.ToRawcode()}' not found."); } } } // Verify destructable data var destructableData = objectData.DestructableData; var stoneDoor = new Destructable(DestructableType.RollingStoneDoor_ZTd6, db); stoneDoor.EditorCategory = DestructableCategory.BridgesRamps; stoneDoor.EditorTilesets = new[] { Tileset.LordaeronFall, Tileset.LordaeronSummer, Tileset.SunkenRuins }; var expectDestructable = new Dictionary <string, ObjectDataType>() { // Stone door { "bcat", castType[stoneDoor.EditorCategoryRaw.GetType()] }, { "btil", castType[stoneDoor.EditorTilesetsRaw.GetType()] }, }; foreach (var destructable in objectData.GetAllDestructables()) { var actualDestructable = db.GetDestructable(destructable.OldId); foreach (var mod in destructable.Modifications) { if (expectDestructable.TryGetValue(mod.Id.ToRawcode(), out var type)) { if (mod.Type != type) { errorLines.Add($"'{mod.Id.ToRawcode()}' TYPE: Expected {mod.Type}, actual {type}."); } var actualMod = actualDestructable.Modifications[mod.Id]; var value = actualMod.Value; if (!object.Equals(mod.Value, value)) { errorLines.Add($"'{mod.Id.ToRawcode()}' VALUE: Expected {{{mod.Value}}}, actual {{{value}}}."); Assert.AreNotEqual(mod.Value.ToString(), value.ToString()); } } else { Assert.Fail($"Key '{mod.Id.ToRawcode()}' not found."); } } } // Verify doodad data var doodadData = objectData.DoodadData; var trough = new Doodad(DoodadType.Trough, db); trough.EditorCategory = DoodadCategory.Cinematic; var expectDoodad = new Dictionary <string, ObjectDataType>() { // Trough { "dcat", castType[trough.EditorCategoryRaw.GetType()] }, }; foreach (var doodad in objectData.GetAllDoodads()) { var actualDoodad = db.GetDoodad(doodad.OldId); foreach (var mod in doodad.Modifications) { if (expectDoodad.TryGetValue(mod.Id.ToRawcode(), out var type)) { if (mod.Type != type) { errorLines.Add($"'{mod.Id.ToRawcode()}' TYPE: Expected {mod.Type}, actual {type}."); } var actualMod = actualDoodad.Modifications[mod.Id]; var value = actualMod.Value; if (!object.Equals(mod.Value, value)) { errorLines.Add($"'{mod.Id.ToRawcode()}' VALUE: Expected {{{mod.Value}}}, actual {{{value}}}."); Assert.AreNotEqual(mod.Value.ToString(), value.ToString()); } } else { Assert.Fail($"Key '{mod.Id.ToRawcode()}' not found."); } } } // Verify ability data var abilityData = objectData.AbilityData; var darkRangerSilence = new Abilities.DarkRangerSilence(db); darkRangerSilence.DataAttacksPrevented[1] = SilenceFlags.Melee | SilenceFlags.Ranged | SilenceFlags.Special | SilenceFlags.Spells; var demonHunterMetamorphosis = new Abilities.DemonHunterMetamorphosis(db); demonHunterMetamorphosis.DataMorphingFlags[1] = MorphFlags.RequiresPayment; var farseerFarSight = new Abilities.FarseerFarSight(db); farseerFarSight.DataDetectionType[1] = DetectionType.Invisible; var seaWitchFrostArrows = new Abilities.SeaWitchFrostArrows(db); seaWitchFrostArrows.DataStackFlags[1] = 0; var illidanChannel = new Abilities.IllidanChannel(db); illidanChannel.DataTargetType[1] = ChannelType.UnitOrPointTarget; illidanChannel.DataOptions[1] = ChannelFlags.UniversalSpell | ChannelFlags.UniqueCast; var alliedBuilding = new Abilities.AlliedBuilding(db); alliedBuilding.DataInteractionType[1] = InteractionFlags.AnyUnitWInventory | InteractionFlags.AnyNonBuilding; var rejuvination = new Abilities.Rejuvination(db); rejuvination.DataAllowWhenFull[1] = FullFlags.ManaOnly; var rootAncientProtector = new Abilities.RootAncientProtector(db); rootAncientProtector.DataUprootedDefenseType[1] = DefenseTypeInt.Normal; var preservation = new Abilities.Preservation(db); preservation.DataBuildingTypesAllowed[1] = PickFlags.General; var expectAbility = new Dictionary <string, ObjectDataType>() { // Dark ranger silence { "Nsi1", castType[darkRangerSilence.DataAttacksPreventedRaw[1].GetType()] }, // Demon hunter metamorphosis { "Eme2", castType[demonHunterMetamorphosis.DataMorphingFlagsRaw[1].GetType()] }, // Farseer far sight { "Ofs1", castType[farseerFarSight.DataDetectionTypeRaw[1].GetType()] }, // Sea witch frost arrows { "Hca4", castType[seaWitchFrostArrows.DataStackFlagsRaw[1].GetType()] }, // Illidan channel { "Ncl2", castType[illidanChannel.DataTargetTypeRaw[1].GetType()] }, { "Ncl3", castType[illidanChannel.DataOptionsRaw[1].GetType()] }, // Allied building { "Neu2", castType[alliedBuilding.DataInteractionTypeRaw[1].GetType()] }, // Rejuvination { "Rej3", castType[rejuvination.DataAllowWhenFullRaw[1].GetType()] }, // Root ancient protector { "Roo4", castType[rootAncientProtector.DataUprootedDefenseTypeRaw[1].GetType()] }, // Preservation { "Npr1", castType[preservation.DataBuildingTypesAllowedRaw[1].GetType()] }, }; foreach (var ability in objectData.GetAllAbilities()) { var actualAbility = db.GetAbility(ability.OldId) ?? throw new NullReferenceException(ability.OldId.ToRawcode()); foreach (var mod in ability.Modifications) { if (expectAbility.TryGetValue(mod.Id.ToRawcode(), out var type)) { if (mod.Type != type) { errorLines.Add($"'{mod.Id.ToRawcode()}' TYPE: Expected {mod.Type}, actual {type}."); } var actualMod = mod.Level > 0 ? actualAbility.Modifications[mod.Id, mod.Level] : actualAbility.Modifications[mod.Id]; var value = actualMod.Value; if (!object.Equals(mod.Value, value)) { errorLines.Add($"'{mod.Id.ToRawcode()}' VALUE: Expected {{{mod.Value}}}, actual {{{value}}}."); Assert.AreNotEqual(mod.Value.ToString(), value.ToString()); } } else { Assert.Fail($"Key '{mod.Id.ToRawcode()}' not found."); } } } // Verify buff data var buffData = objectData.BuffData; var avatar = new Buff(BuffType.Avatar, db); avatar.ArtLightning = LightningEffect.DRAB; avatar.ArtRequiredSpellDetail = SpellDetail.Medium; var expectBuff = new Dictionary <string, ObjectDataType>() { // Avatar { "flig", castType[avatar.ArtLightningRaw.GetType()] }, { "fspd", castType[avatar.ArtRequiredSpellDetailRaw.GetType()] }, }; foreach (var buff in objectData.GetAllBuffs()) { var actualBuff = db.GetBuff(buff.OldId); foreach (var mod in buff.Modifications) { if (expectBuff.TryGetValue(mod.Id.ToRawcode(), out var type)) { if (mod.Type != type) { errorLines.Add($"'{mod.Id.ToRawcode()}' TYPE: Expected {mod.Type}, actual {type}."); } var actualMod = actualBuff.Modifications[mod.Id]; var value = actualMod.Value; if (!object.Equals(mod.Value, value)) { errorLines.Add($"'{mod.Id.ToRawcode()}' VALUE: Expected {{{mod.Value}}}, actual {{{value}}}."); Assert.AreNotEqual(mod.Value.ToString(), value.ToString()); } } else { Assert.Fail($"Key '{mod.Id.ToRawcode()}' not found."); } } } // Verify upgrade data var upgradeData = objectData.UpgradeData; var humanAnimalBreeding = new Upgrade(UpgradeType.HumanAnimalBreeding, db); humanAnimalBreeding.StatsClass = UpgradeClass.Caster; humanAnimalBreeding.DataEffect2 = UpgradeEffect.Radl; var expectUpgrade = new Dictionary <string, ObjectDataType>() { // Human animal breeding { "gcls", castType[humanAnimalBreeding.StatsClassRaw.GetType()] }, { "gef2", castType[humanAnimalBreeding.DataEffect2Raw.GetType()] }, }; foreach (var upgrade in objectData.GetAllUpgrades()) { var actualUpgrade = db.GetUpgrade(upgrade.OldId); foreach (var mod in upgrade.Modifications) { if (expectUpgrade.TryGetValue(mod.Id.ToRawcode(), out var type)) { if (mod.Type != type) { errorLines.Add($"'{mod.Id.ToRawcode()}' TYPE: Expected {mod.Type}, actual {type}."); } var actualMod = actualUpgrade.Modifications[mod.Id]; var value = actualMod.Value; if (!object.Equals(mod.Value, value)) { errorLines.Add($"'{mod.Id.ToRawcode()}' VALUE: Expected {{{mod.Value}}}, actual {{{value}}}."); Assert.AreNotEqual(mod.Value.ToString(), value.ToString()); } } else { Assert.Fail($"Key '{mod.Id.ToRawcode()}' not found."); } } } Assert.AreEqual(0, errorLines.Count, string.Join("\r\n ", errorLines.Prepend("\r\nFound one or more errors:"))); }
static void Main(string[] args) { var potionLines = new List <string>(); var statusLines = new List <string>(); var potionXmlLines = new List <string>(); var statusXmlLines = new List <string>(); var entries = new Dictionary <string, List <Tuple <string, int> > > { // Attributes //{ "Strength", new List<Tuple<string, int>> { } }, { "Finesse", new List <Tuple <string, int> > { Tuple.Create("Initiative", 1), Tuple.Create("DodgeBoost", 1) /*, Tuple.Create("Movement", 20)*/ } }, { "Intelligence", new List <Tuple <string, int> > { Tuple.Create("FireResistance", 1), Tuple.Create("WaterResistance", 1), Tuple.Create("AirResistance", 1), Tuple.Create("EarthResistance", 1) } }, { "Constitution", new List <Tuple <string, int> > { Tuple.Create("PhysicalResistance", 1), Tuple.Create("PoisonResistance", 1) } }, //{ "Memory", new List<Tuple<string, int>> { } }, { "Wits", new List <Tuple <string, int> > { Tuple.Create("AccuracyBoost", 1) /*, Tuple.Create("RangeBoost", 100)*/ } } }; foreach (var entry in entries) { if (entry.Value.Count == 0) { continue; } var stat = entry.Key; var dataPoints = entry.Value; potionLines.AddRange(new List <string> { string.Format("new entry \"_Chronos38_Stats_{0}\"\r\n", stat), "type \"Potion\"\r\n", "\r\n" }); statusLines.AddRange(new List <string> { string.Format("new entry \"_Chronos38_CustomStatValue_{0}\"\r\n", stat), "type \"StatusData\"\r\n", "data \"StatusType\" \"CONSUME\"\r\n", "\r\n" }); potionXmlLines.AddRange(new List <string> { "<stat_object color=\"#FF5F9EA0\" is_substat=\"false\">\r\n", "<fields>\r\n", string.Format("<field name=\"Name\" type=\"NameStatObjectFieldDefinition\" value=\"_Chronos38_Stats_{0}\" />\r\n", stat), "</fields>\r\n", "</stat_object>\r\n" }); statusXmlLines.AddRange(new List <string> { "<stat_object color=\"#FF5F9EA0\" is_substat=\"false\">\r\n", "<fields>\r\n", string.Format("<field name=\"Name\" type=\"NameStatObjectFieldDefinition\" value=\"_Chronos38_CustomStatValue_{0}\" />\r\n", stat), "</fields>\r\n", "</stat_object>\r\n" }); for (int i = -10; i <= 50; ++i) { if (i == 0) { continue; } ///////////////////////////////////////////////////////////////////////////////////// potionLines.Add(string.Format("new entry \"Chronos38_Stats_{0}_{1}\"\r\n", stat, i)); potionLines.Add("type \"Potion\"\r\n"); potionXmlLines.Add("<stat_object is_substat=\"false\">\r\n"); potionXmlLines.Add("<fields>\r\n"); potionXmlLines.Add(string.Format("<field name=\"Name\" type=\"NameStatObjectFieldDefinition\" value=\"Chronos38_Stats_{0}_{1}\" />\r\n", stat, i)); foreach (var dataPoint in dataPoints) { potionLines.Add(string.Format("data \"{0}\" \"{1}\"\r\n", dataPoint.Item1, dataPoint.Item2 * i)); potionXmlLines.Add(string.Format("<field name=\"{0}\" type=\"IntegerStatObjectFieldDefinition\" value=\"{1}\" />\r\n", dataPoint.Item1, dataPoint.Item2 * i)); } potionLines.Add("\r\n"); potionXmlLines.Add("</fields>\r\n"); potionXmlLines.Add("</stat_object>\r\n"); ///////////////////////////////////////////////////////////////////////////////////// statusLines.Add(string.Format("new entry \"Chronos38_CustomStatValue_{0}_{1}\"\r\n", stat, i)); statusLines.Add("type \"StatusData\"\r\n"); statusLines.Add("data \"StatusType\" \"CONSUME\"\r\n"); statusLines.Add(string.Format("data \"StatsId\" \"Chronos38_Stats_{0}_{1}\"\r\n", stat, i)); statusLines.Add("\r\n"); statusXmlLines.Add("<stat_object is_substat=\"false\">\r\n"); statusXmlLines.Add("<fields>\r\n"); statusXmlLines.Add(string.Format("<field name=\"Name\" type=\"NameStatObjectFieldDefinition\" value=\"Chronos38_CustomStatValue_{0}_{1}\" />\r\n", stat, i)); statusXmlLines.Add(string.Format("<field name=\"StatsId\" type=\"StringStatObjectFieldDefinition\" value=\"Chronos38_Stats_{0}_{1}\" />\r\n", stat, i)); statusXmlLines.Add("</fields>\r\n"); statusXmlLines.Add("</stat_object>\r\n"); } } var potionContent = potionLines.Aggregate((content, line) => content += line); var statusContent = statusLines.Aggregate((content, line) => content += line); potionXmlLines = potionXmlLines .Prepend("<stat_objects>\r\n") .Prepend("<stats stat_object_definition_id=\"48e63fff-81e0-42bb-ac51-39f5904b97be\">\r\n") .Prepend("<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n") .ToList(); potionXmlLines.Add("</stat_objects>\r\n"); potionXmlLines.Add("</stats>\r\n"); var potionXmlContent = potionXmlLines.Aggregate((content, line) => content += line); statusXmlLines = statusXmlLines .Prepend("<stat_objects>\r\n") .Prepend("<stats stat_object_definition_id=\"e2a8d59b-0e34-4a7c-bf5f-db7a2bb34cde\">\r\n") .Prepend("<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n") .ToList(); statusXmlLines.Add("</stat_objects>\r\n"); statusXmlLines.Add("</stats>\r\n"); var statusXmlContent = statusXmlLines.Aggregate((content, line) => content += line); File.WriteAllText("Potion.txt", potionContent); File.WriteAllText("Status_CONSUME.txt", statusContent); File.WriteAllText("Potion.stats", potionXmlContent); File.WriteAllText("Status_CONSUME.stats", statusXmlContent); }
/// <summary> /// Извличане на всчики съдилища от Вертикално движение на дело - между институциите за комбо /// </summary> /// <param name="caseId"></param> /// <param name="addDefaultElement"></param> /// <param name="addAllElement"></param> /// <returns></returns> public List <SelectListItem> GetDropDownList_Court(int caseId, bool addDefaultElement = true, bool addAllElement = false) { var result = new List <SelectListItem>(); var caseMigrationFind = repo.All <CaseMigration>().Where(x => x.CaseId == caseId).FirstOrDefault(); if (caseMigrationFind != null) { var caseMigrations = repo.All <CaseMigration>() .Include(x => x.Case) .ThenInclude(x => x.Court) .Where(x => x.InitialCaseId == caseMigrationFind.InitialCaseId) .ToList(); foreach (var caseMigration in caseMigrations.OrderBy(x => x.Case.Court.Label)) { if (!result.Any(x => x.Value == caseMigration.Case.Court.Id.ToString())) { var selectListItem = new SelectListItem() { Text = caseMigration.Case.Court.Label, Value = caseMigration.Case.Court.Id.ToString() }; result.Add(selectListItem); } } } if (result.Count < 1) { var selectListItem = new SelectListItem() { Text = userContext.CourtName, Value = userContext.CourtId.ToString() }; result.Add(selectListItem); } if (addDefaultElement) { result = result .Prepend(new SelectListItem() { Text = "Избери", Value = "-1" }) .ToList(); } if (addAllElement) { result = result .Prepend(new SelectListItem() { Text = "Всички", Value = "-2" }) .ToList(); } return(result); }
protected override Assembly?Load(AssemblyName assemblyName) { if (string.IsNullOrEmpty(assemblyName.Name)) { throw new ArgumentNullException(nameof(assemblyName)); } // Ignore Resolver if (PrivateAssemblies.Contains(assemblyName.Name)) { return(null); } Assembly?assembly; // Load overrides if (File.Exists(Path.Combine(_basePath, $"{assemblyName.Name}.dll"))) { assembly = LoadAssemblyFromFilePath(Path.Combine(_basePath, $"{assemblyName.Name}.dll")); LoadedAssemblies.Add(assemblyName.Name, assembly); return(assembly); } // Shared Resolver if (SharedAssemblies.TryGetValue(assemblyName.Name, out assembly) && assembly != null) { LoadedAssemblies.Add(assemblyName.Name, assembly); return(assembly); } //Logger.LogError(SharedAssemblies.ContainsKey(assemblyName.Name)); foreach (var sharedContext in SharedContexts) { if (!sharedContext.LoadedAssemblies.TryGetValue(assemblyName.Name, out assembly)) { continue; } Logger.LogInfo($"Loading from shared {assemblyName.Name}."); LoadedAssemblies.Add(assemblyName.Name, assembly); return(assembly); } Logger.LogInfo($"Didn't load from shared {assemblyName.Name}."); // Probe Resource Roots if (!string.IsNullOrEmpty(assemblyName.CultureName) && !string.Equals("neutral", assemblyName.CultureName)) { foreach (var resourceRoot in _resourceRoots) { string resourcePath = Path.Combine(resourceRoot, assemblyName.CultureName, assemblyName.Name + ".dll"); if (!File.Exists(resourcePath)) { continue; } assembly = LoadAssemblyFromFilePath(resourcePath); LoadedAssemblies.Add(assemblyName.Name, assembly); return(assembly); } return(null); } // Native Resolver string?resolvedPath = _dependencyResolver.ResolveAssemblyToPath(assemblyName); if (!string.IsNullOrEmpty(resolvedPath) && File.Exists(resolvedPath)) { assembly = LoadAssemblyFromFilePath(resolvedPath); LoadedAssemblies.Add(assemblyName.Name, assembly); return(assembly); } // Probe Additional Paths string dllName = assemblyName.Name + ".dll"; foreach (var probingPath in AdditionalProbingPaths.Prepend(_basePath)) { string localFile = Path.Combine(probingPath, dllName); if (!File.Exists(localFile)) { continue; } assembly = LoadAssemblyFromFilePath(localFile); LoadedAssemblies.Add(assemblyName.Name, assembly); return(assembly); } Logger.LogInfo($"Failed to load {assemblyName.Name}."); return(null); }
public static void toBack(Window WINDOW) { Windows.Remove(WINDOW); Windows = Windows.Prepend(WINDOW).ToList(); }
public void Start() => _tasks.Prepend(Task.Factory.StartNew(() => _VM.Start(), _cancellationToken));