public void Test()
        {
            string filename = "companyData.json";
              List<Company> expected;
              List<Company> actual;

              try
              {
            var file = "../../../Stocks.Service/companyData.json";
            var configurationService = new ConfigurationService(file);
            expected = configurationService.GetCompanies();

            var worker = new FileSerializer();
            worker.SerializeJson(filename, expected);

            actual = worker.DeserializeJson<Company>(filename);
              }
              finally
              {
            if (File.Exists(filename))
              File.Delete(filename);
              }

              Assert.Equal(expected.Count, actual.Count);

              for (int i = 0; i < actual.Count; i++)
              {
            Assert.Equal(expected[i].Symbol, actual[i].Symbol);
            Assert.Equal(expected[i].Name, actual[i].Name);
              }
        }
Ejemplo n.º 2
0
        private void ProceedCommand(string command)
        {
            switch (command)
            {
            case "Enter":
                Console.Clear();
                this.renderer.RenderPlayfield(this.playfield);
                this.PlayTurn();
                break;

            case "Save":
                var memory = new Caretaker();
                memory.Memento = this.playfield.SaveMemento();

                var fileSerializer = new FileSerializer();
                fileSerializer.SerializeObject(memory.Memento, GameLocation);
                break;

            case "Exit":
                Environment.Exit(0);
                break;

            default:
                Console.Clear();
                Console.WriteLine(ChooseCommand);
                this.ProceedCommand(Console.ReadLine());
                break;
            }
        }
Ejemplo n.º 3
0
        public static Test Load(string path)
        {
            var test = FileSerializer.ReadConfig <Test>(path, new Test());

            var testDir = new DirectoryInfo(Path.Combine(test.FolderPath, @".\..\_Endpoints\"));

            foreach (var endpointDir in testDir.GetDirectories("*", SearchOption.TopDirectoryOnly))
            {
                if (Is(endpointDir, "Sql-"))
                {
                    var sqlSettings = FileSerializer.ReadConfig <TDSStubSettings>(endpointDir.FullName, new TDSStubSettings {
                        Port = 54300
                    });
                    var stubs   = FileSerializer.ReadStubs <SqlStub>(endpointDir.FullName).ToList();
                    var dirPath = Path.Combine(test.FolderPath, endpointDir.Name);
                    if (Directory.Exists(dirPath))
                    {
                        stubs.AddRange(FileSerializer.ReadStubs <SqlStub>(dirPath));
                    }
                    test.AddEndpoint(new TDSStub(sqlSettings, stubs));
                }
                else if (Is(endpointDir, "Amqp-"))
                {
                    var amqpSettings = FileSerializer.ReadConfig <AMQPStubSettings>(endpointDir.FullName, new AMQPStubSettings {
                        Port = 54400
                    });
                    var stubs   = FileSerializer.ReadStubs <AMQPMessage>(endpointDir.FullName).ToList();
                    var dirPath = Path.Combine(test.FolderPath, endpointDir.Name);
                    if (Directory.Exists(dirPath))
                    {
                        stubs.AddRange(FileSerializer.ReadStubs <AMQPMessage>(dirPath));
                    }
                    test.AddEndpoint(new AMQPStub(amqpSettings, stubs));
                }
                else if (Is(endpointDir, "AzureBlobService-"))
                {
                    var blobSettings = FileSerializer.ReadConfig <AzureBlobServiceStubSettings>(endpointDir.FullName,
                                                                                                new AzureBlobServiceStubSettings {
                        Port = 54500
                    });
                    var stubs   = FileSerializer.ReadStubs <BlobFileStub>(endpointDir.FullName).ToList();
                    var dirPath = Path.Combine(test.FolderPath, endpointDir.Name);
                    if (Directory.Exists(dirPath))
                    {
                        stubs.AddRange(FileSerializer.ReadStubs <BlobFileStub>(dirPath));
                    }
                    test.AddEndpoint(new AzureBlobServiceStub(blobSettings, stubs));
                }
                else if (Is(endpointDir, "Redis-"))
                {
                    var settings = FileSerializer.ReadConfig <RedisEndpointSettings>(endpointDir.FullName,
                                                                                     new RedisEndpointSettings {
                        Port = 54600
                    });
                    test.AddEndpoint(new RedisEdnpoint(settings));
                }
            }

            return(test);
        }
Ejemplo n.º 4
0
        private static async Task <ImageAnalysisResult> PerformTweetImageAnalysisIfNotAlreadyDoneAsync(string partialFileName, string link)
        {
            // Download video locally (for later use)
            string fileExt         = link.Substring(link.Length - 3);
            string destinationFile = $"{partialFileName}.{fileExt}";

            if (!File.Exists(destinationFile))
            {
                await m_WebScraper.DownloadResourceAsync(link, destinationFile);
            }

            // Analyze the content pointed by link in the tweet (if not already done)
            Console.WriteLine($"\t\t{link}");
            destinationFile = $"{partialFileName}_results.txt";
            if (!File.Exists(destinationFile))
            {
                var linkContentAnalysisResult = await m_ContentAnalyzer.AnalyzeImageFromUrlAsync(link);

                // Store results for later user
                await FileSerializer.StoreInFileAsync(linkContentAnalysisResult, destinationFile);

                return(linkContentAnalysisResult);
            }
            else
            {
                return(await FileSerializer.LoadFromFileAsync <ImageAnalysisResult>(destinationFile));
            }
        }
Ejemplo n.º 5
0
        public static void CountNoName()
        {
            var osm = OpenFile(@"C:\Users\Alex\Downloads\Maine\maine-latest-internal.osm.pbf").ToArray();

            var nodes = osm.OfType <Node>().ToDictionary(n => n.Id, n => n.AsPosition());

            var junctions = new HashSet <long>(osm.OfType <Way>().SelectMany(w => w.Nodes).GroupBy(n => n).Where(g => g.Count() > 1).Select(g => g.Key));

            var noName = osm.Where(e => e is Way && e.Tags != null && e.Tags.ContainsKey("highway") && !e.Tags.ContainsKey("name") && !e.Tags.ContainsKey("ref"))
                         .GroupBy(e => e.Tags["highway"])
                         .ToDictionary();

            var residential = noName["residential"].OfType <Way>().Where(r => r.Nodes.Count(n => junctions.Contains(n)) == 1 &&
                                                                         Geometry.DistanceMeters(nodes[r.Nodes.First()], nodes[r.Nodes.Last()]) < 100).ToArray();

            var residentialNodes = new HashSet <long>(residential.SelectMany(r => r.Nodes));

            var elements = residential.OfType <OsmGeo>().Concat(osm.OfType <Node>().Where(n => residentialNodes.Contains(n.Id.Value)));

            FileSerializer.WriteXml("FIXCountNoName\\FIXCountNoName.osm", elements.AsOsm());

            Console.WriteLine(residential.Length);

            //Console.WriteLine(SummarizeGrouping(noName));
        }
Ejemplo n.º 6
0
        private static async Task <VideoAnalysisResult> PerformTweetVideoAnalysisIfNotAlreadyDoneAsync(string partialFileName, string link)
        {
            var    fileExt         = link.Substring(link.Length - 3);
            string destinationFile = $"{partialFileName}.{fileExt}";

            if (!File.Exists(destinationFile))
            {
                await m_WebScraper.DownloadResourceAsync(link, destinationFile);
            }

            // Analyze video content pointed by tweet (if not already done)

            Console.WriteLine($"\t\t{link}");
            destinationFile = $"{partialFileName}_results.txt";
            if (!File.Exists(destinationFile))
            {
                // VIDEO ANALYSIS DISABLED, TOO MUCH TIME FOR DEMO
                return(null);
                //var linkContentAnalysisResult = await m_ContentAnalyzer.AnalyzeVideoAsync(destinationFile, link);

                //// Store results for later user
                //await FileSerializer.StoreInFileAsync(linkContentAnalysisResult, destinationFile);

                //return linkContentAnalysisResult;
            }
            else
            {
                return(await FileSerializer.LoadFromFileAsync <VideoAnalysisResult>(destinationFile));
            }
        }
Ejemplo n.º 7
0
        //in this func use class member BFGen.isITC
        private bool GenBeaconXMLFile(IBeaconInfo beacon, string filename)
        {
            Balise xmlFile = new Balise();

            //BMGR-0002
            xmlFile.name = new StringData(beacon.Name);

            //BMGR-0003
            xmlFile.Telegram.type = new StringData("LONG");

            //Telegram get
            if (isITC)
            {//BMGR-0004
                TraceMethod.RecordInfo("error:iTC not support now!");
                xmlFile.Telegram.Value = new StringData("iTC not support");
            }
            else
            {
                BeaconMessage bm = new BeaconMessage();
                xmlFile.Telegram.Value = new StringData(bm.GenerateMessage(beacon, sydb.LineID));
            }

            FileSerializer.Serialize(xmlFile, filename, AddLogHead());
            return(true);
        }
Ejemplo n.º 8
0
        public static void FIXDupeNames()
        {
            var osm   = OpenFile(@"C:\Users\Alex\Downloads\maine-latest-internal.osm.pbf");
            var index = OsmSharp.Db.Impl.Extensions.CreateSnapshotDb(new MemorySnapshotDb(osm));

            var named = osm.Where(e => (e is Node || e is Way) && e.Tags != null && e.Tags.ContainsKey("name") && !e.Tags.ContainsKey("highway") && !e.Tags.ContainsKey("railway") && !e.Tags.ContainsKey("waterway"))
                        .GroupBy(e => Connonical(e.Tags["name"]))
                        .Where(g => g.Count() > 1)
                        .ToDictionary();

            var dupes       = named.ToDictionary(kvp => kvp.Key, kvp => Geometry.GroupCloseNeighbors(kvp.Value, 1000, index, false).Where(c => c.Count > 1).OrderByDescending(c => c.Count).ToArray()).OrderByDescending(d => d.Value.Length).ToArray();
            var dupeCount   = dupes.SelectMany(d => d.Value.SelectMany(r => r)).Count();
            var av          = dupes.SelectMany(d => d.Value).Average(d => d.Count);
            var ma          = dupes.SelectMany(d => d.Value).Max(d => d.Count);
            var myDupes     = dupes.ToDictionary(d => d.Key, d => d.Value.Where(c => c.Any(e => e.UserName.StartsWith("blackbo"))).ToArray()).Where(c => c.Value.Any()).OrderByDescending(c => c.Value.Count()).ToArray();
            var myDupeCount = myDupes.SelectMany(d => d.Value.SelectMany(r => r)).Count();

            var myOsm = myDupes.SelectMany(d => d.Value.SelectMany(r => r)).ToArray().WithChildren(index).AsOsm();

            FileSerializer.WriteXml("FIXDupeNames\\myDupes.osm", myOsm);

            var allOsm = dupes.SelectMany(d => d.Value.SelectMany(r => r)).ToArray().WithChildren(index).AsOsm();

            FileSerializer.WriteXml("FIXDupeNames\\allDupes.osm", allOsm);
        }
Ejemplo n.º 9
0
        public static void FixIslandPlaces()
        {
            var osm   = OpenFile(@"C:\Users\Alex\Downloads\Maine\maine-latest-internal.osm.pbf").ToArray();
            var index = OsmSharp.Db.Impl.Extensions.CreateSnapshotDb(new MemorySnapshotDb(osm));

            var roadNames     = new HashSet <string>(osm.Where(e => e.Tags != null && e.Tags.ContainsKey("highway") && e.Tags.ContainsKey("name")).Select(e => Connonical(e.Tags["name"])).Distinct());
            var places        = osm.Where(e => e.Tags != null && (e.Tags.ContainsKey("place") || e.Tags.ContainsKey("waterway")));
            var islands       = places.Where(e => e.Tags["place"] == "island" || e.Tags["place"] == "islet" || e.Tags.Any(t => t.Key == "name" && t.Value.Contains("island", StringComparison.OrdinalIgnoreCase))).ToArray();
            var islandsByName = islands.Where(e => e.Tags.ContainsKey("name")).GroupBy(e => Connonical(e.Tags["name"])).ToDictionary();

            var orphans = osm.Where(e => e.Tags != null && e.Tags.ContainsKey("addr:street") && !roadNames.Contains(Connonical(e.Tags["addr:street"])) &&
                                    islandsByName.ContainsKey(Connonical(e.Tags["addr:street"]))).ToArray();

            var matchedOrphans = orphans.Where(e => islandsByName[Connonical(e.Tags["addr:street"])].Any(i => Geometry.MinDistanceMeters(e.AsComplete(index).AsPosition(), i.AsComplete(index)) < 1000)).ToArray();

            FileSerializer.WriteXml(@"Fix IslandPlaces\islands.osm", islands.WithChildren(index).AsOsm());
            FileSerializer.WriteXml(@"Fix IslandPlaces\orphans.osm", orphans.WithChildren(index).AsOsm());
            FileSerializer.WriteXml(@"Fix IslandPlaces\matchedOrphans.osm", matchedOrphans.WithChildren(index).AsOsm());
            FileSerializer.WriteXml(@"Fix IslandPlaces\unmatchedOrphans.osm", orphans.Except(matchedOrphans).WithChildren(index).AsOsm());

            foreach (var orphan in orphans)
            {
                orphan.Tags["addr:place"] = orphan.Tags["addr:street"];
                orphan.Tags.RemoveKey("addr:street");
            }

            var change     = Changes.FromGeos(null, orphans, null);
            var changeTags = GetCommitTags("Moving addr:street tag to addr:place for island addresses.");
            var ids        = Subjects.UploadChange(change, changeTags, "Fix IslandPlaces").Result;
        }
Ejemplo n.º 10
0
        private static async Task <IList <Tweet> > GetTweets(string[] args, string resultsPath)
        {
            // Try to load feed items from local file (if specified)
            string sourceFile          = string.Empty;
            IList <Model.Tweet> tweets = null;

            if (args.Length == 1)
            {
                var tweetList = new List <Model.Tweet>();
                var feedFiles = Directory.GetFiles(args[0], "*_tweets.txt");
                foreach (var file in feedFiles)
                {
                    tweetList.AddRange(await FileSerializer.LoadFromFileAsync <IList <Model.Tweet> >(file));
                }
                tweets = tweetList;
            }

            // Retrieve recent tweets from the configured account
            if (tweets == null)
            {
                tweets = await m_TwitterMonitor.RetrieveTweetsAsync();

                // Store tweets for later user (i.e. repeat analysis on the same content)
                await FileSerializer.StoreInFileAsync(tweets, $"{resultsPath}\\{DateTime.UtcNow.ToString("yyyyMMdd_HHmmss")}_tweets.txt");
            }

            return(tweets);
        }
        private IEnumerable <Entities.ObfuscationInfo> LoadOperations()
        {
            var serializer     = new FileSerializer();
            var obfuscationOps = serializer.LoadObfuscationOps(fileOfuscationOps);

            return(obfuscationOps);
        }
Ejemplo n.º 12
0
        private static NetTopologySuite.Geometries.Geometry LoadBounds(string scopeName, long relationId)
        {
            var scopeFile = $"{scopeName}\\Scope.osm";
            var osm       = FileSerializer.ReadXml <Osm>(scopeFile);
            CompleteRelation relation;

            if (osm != null)
            {
                relation = osm.GetElements().ToComplete().OfType <CompleteRelation>().First();
            }
            else
            {
                NonAuthClient client = new NonAuthClient("https://www.osm.org/api/", new HttpClient());
                relation = client.GetCompleteRelation(relationId).Result;
                FileSerializer.WriteXml(scopeFile, relation.ToSimpleWithChildren().AsOsm());
            }

            var geometry = FeatureInterpreter.DefaultInterpreter.Interpret(relation).First().Geometry;

            if (geometry is LinearRing linRing)
            {
                var polygon = Polygon.DefaultFactory.CreatePolygon(linRing);                 // Or multipolygon?
                return(polygon);
            }
            else if (geometry is MultiPolygon multi)
            {
                return(multi);
                //Polygon.DefaultFactory.CreateMultiPolygon();
            }

            throw new Exception("unexpected geometry type: " + geometry.GetType().Name);
        }
Ejemplo n.º 13
0
        public static void UnlinkGNIS()
        {
            var osm = OpenFile(@"C:\Users\Alex\Downloads\Maine\maine-latest-internal.osm.pbf").ToArray();

            var badsC = osm.Where(e => e.Tags != null && e.Tags.Contains("gnis:reviewed", "no") && e.UserName == "blackboxlogic+bot").ToDictionary(b => b.Id);

            var bads    = osm.Where(e => e.Tags != null && e.Tags.Contains("gnis:reviewed", "no") && e.UserName == "blackboxlogic+bot" && e is Node).ToDictionary(b => b.Id);
            var prevs   = OsmApiClient.GetElements(bads.Values.ToDictionary(b => new OsmGeoKey(b), b => b.Version - 1)).Result;
            var news    = new List <OsmGeo>();
            var changes = new List <OsmGeo>();

            foreach (var prev in prevs.Where(p => !p.Tags.ContainsKey("addr:street") &&
                                             p.Id != 367794548 && p.Id != 367795033 && p.Id != 367794682 && p.Id != 367794721 && p.Id != 367795011 &&
                                             p.Id != 367795009 && p.Id != 367794614 && p.Id != 367794612))
            {
                prev.Version++;
                changes.Add(prev);

                var bad = bads[prev.Id];
                bad.Tags = new TagsCollection(bad.Tags.Where(t => t.Key.StartsWith("addr")));
                bad.Id   = -bad.Id;
                news.Add(bad);
            }

            var change = Changes.FromGeos(news, changes, null);

            FileSerializer.WriteXml("FIX unmerge gnis\\change.osc", change);
            var changeTags = GetCommitTags("Separate addreses which should not have been merged into GNIS elements with reviewed=no");
            var ids        = Subjects.UploadChange(change, changeTags, "FIX unmerge gnis").Result;

            //Console.WriteLine(string.Join(Environment.NewLine, bads.Values.Select(b => b.Type + " " + b.Id)));
        }
Ejemplo n.º 14
0
        public static void FixPlaces()
        {
            var osm = OpenFile(@"C:\Users\Alex\Downloads\maine-latest-internal.osm.pbf").ToArray();

            var index = OsmSharp.Db.Impl.Extensions.CreateSnapshotDb(new MemorySnapshotDb(osm));

            var roadsByName = osm.Where(e => e.Tags != null && e.Tags.ContainsKey("highway") && e.Tags.ContainsKey("name"))
                              .GroupBy(e => Connonical(e.Tags["name"])).ToDictionary();
            var placesByName = osm.Where(e => e.Tags != null && e.Tags.ContainsKey("name") && (e.Tags.ContainsKey("place") || e.Tags.ContainsKey("waterway")))
                               .GroupBy(e => Connonical(e.Tags["name"])).ToDictionary();
            var orphans = osm.Where(e => e.Tags != null && e.Tags.Contains("addr:state", "ME") && e.Tags.ContainsKey("addr:street") && !roadsByName.ContainsKey(Connonical(e.Tags["addr:street"])) &&
                                    placesByName.ContainsKey(Connonical(e.Tags["addr:street"])) &&
                                    placesByName[Connonical(e.Tags["addr:street"])].Any(
                                        p => Geometry.MinDistanceMeters(e.AsComplete(index).AsPosition(), p.AsComplete(index)) < 1000)).ToArray();

            var sad = osm.Where(e => e.Tags != null && e.Tags.ContainsKey("addr:street") && e.Tags["addr:street"].Contains("Island") && !roadsByName.ContainsKey(Connonical(e.Tags["addr:street"])) &&
                                (!placesByName.ContainsKey(Connonical(e.Tags["addr:street"])) ||
                                 !placesByName[Connonical(e.Tags["addr:street"])].Any(
                                     p => Geometry.MinDistanceMeters(e.AsComplete(index).AsPosition(), p.AsComplete(index)) < 1000))).ToArray();

            FileSerializer.WriteXml(@"Fix IslandPlaces\islands.osm", placesByName.Values.SelectMany(ps => ps).WithChildren(index).AsOsm());
            FileSerializer.WriteXml(@"Fix IslandPlaces\orphans.osm", orphans.WithChildren(index).AsOsm());
            FileSerializer.WriteXml(@"Fix IslandPlaces\sadOrphans.osm", sad.WithChildren(index).AsOsm());

            foreach (var orphan in orphans)
            {
                orphan.Tags["addr:place"] = orphan.Tags["addr:street"];
                orphan.Tags.RemoveKey("addr:street");
            }

            var change     = Changes.FromGeos(null, orphans, null);
            var changeTags = GetCommitTags("Moving addr:street tag to addr:place for island addresses.");
            var ids        = Subjects.UploadChange(change, changeTags, "Fix IslandPlaces").Result;
        }
Ejemplo n.º 15
0
        public static void SummarizeKeys()
        {
            var osm = OpenFile(@"C:\Users\Alex\Downloads\maine-latest-internal.osm.pbf")
                      .Where(e => e.UserId == 10307443).ToArray();

            FileSerializer.WriteXml("blackboxlogic.osm", osm.AsOsm());
        }
Ejemplo n.º 16
0
        public void TestBasicWriteRead()
        {
            FileSerializer <SerializationTestBasic> serializer = new FileSerializer <SerializationTestBasic>();

            SerializationTestBasic write = new SerializationTestBasic {
                TestBool       = true,
                TestInt        = -100,
                TestString     = "abc" + Environment.NewLine + "def",
                TestStringNull = null,
                TestEnum       = TestEnum.D
            };

            serializer.Write("basic_wr", write);
            Assert.IsTrue(File.Exists("basic_wr"));

            SerializationTestBasic read = new SerializationTestBasic();

            serializer.Read("basic_wr", read);

            Assert.IsTrue(read.TestBool);
            Assert.AreEqual(-100, read.TestInt);
            Assert.AreEqual("abc" + Environment.NewLine + "def", read.TestString);
            Assert.IsNull(read.TestStringNull);
            Assert.AreEqual(TestEnum.D, read.TestEnum);
        }
Ejemplo n.º 17
0
        public static long[] GetUsersChangesetIds(long userId)
        {
            var changeIds = FileSerializer.ReadJsonCacheOrSource(@"CachesChanges\" + userId + ".userChangeIds",
                                                                 () => GetUsersChangesets(userId).Select(c => c.Id.Value).ToArray());

            return(changeIds);
        }
Ejemplo n.º 18
0
        public void SerializerCanLoad()
        {
            string         filePath       = Path.Combine(this.Repo.GitParentPath, "test-file");
            FileSerializer fileSerializer = new FileSerializer(this.Repo.Context, filePath);

            this.Repo.Context.FileSystem.FileExists(filePath).ShouldEqual(false);
            fileSerializer.ReadAll().ShouldBeEmpty();
            this.Repo.Context.FileSystem.FileExists(filePath).ShouldEqual(true);

            List <string> lines = new List <string>()
            {
                "test1", "test2", "test3"
            };

            foreach (string line in lines)
            {
                fileSerializer.AppendLine(line);
            }

            fileSerializer.ReadAll().Count().ShouldEqual(lines.Count);
            IEnumerator <string> expectedLines = lines.GetEnumerator();

            expectedLines.MoveNext();
            foreach (string fileLine in fileSerializer.ReadAll())
            {
                expectedLines.Current.ShouldEqual(fileLine);
                expectedLines.MoveNext();
            }
        }
Ejemplo n.º 19
0
        public static async Task <long[]> UploadChange(string changeFile, string description)
        {
            var change = FileSerializer.ReadXml <OsmChange>(changeFile);

            Log.LogInformation("Uploading change to OSM");
            var changeTags = GetCommitTags(description);

            changeTags.RemoveKey("municipality");
            var osmApiClient = new BasicAuthClient(Static.HttpClient,
                                                   Static.LogFactory.CreateLogger <BasicAuthClient>(), Static.Config["OsmApiUrl"],
                                                   Static.Config["OsmUsername"], Static.Config["OsmPassword"]);
            var changeParts = change.SplitByCount().ToArray();
            var result      = new long[changeParts.Length];
            int i           = 0;

            foreach (var part in changeParts)
            {
                if (changeParts.Length > 1)
                {
                    changeTags.AddOrReplace("change-part", $"part {i + 1} of {changeParts.Length}");
                }
                result[i] = await UploadChangePart(part, changeTags, osmApiClient, $"{description}/Uploaded/");

                i++;
            }

            return(result);
        }
Ejemplo n.º 20
0
        private Osm GetSubject(Bounds bounds = null)
        {
            var subject = FileSerializer.ReadXmlCacheOrSource(Municipality + "/Subject.osm",
                                                              () => Subjects.GetElementsInBoundingBox(bounds));

            Console.WriteLine("ChangeId high watermark: " + subject.GetHighestChangeSetId());
            return(subject);
        }
Ejemplo n.º 21
0
        public static CompleteWay[] Generate(string from, string to, NetTopologySuite.Geometries.Geometry scope = null)
        {
            var osm = FileSerializer.ReadXmlCacheOrSource(to,
                                                          () => TranslateAndDisolve(from, scope));

            JOSM.MarkAsNeverUpload(to);
            return(osm.GetElements().ToComplete().OfType <CompleteWay>().ToArray());
        }
Ejemplo n.º 22
0
        public static async Task <Osm> Fetch(string scopeName, Func <Feature, bool> filter = null)
        {
            TagTree.Reload();

            Log = Log ?? Static.LogFactory.CreateLogger(typeof(References));
            Log.LogInformation("Fetching Reference material from Maine E911 API");

            // Fetch GIS
            var stateGis = await FileSerializer.ReadJsonCacheOrSource(
                scopeName + "/ReferenceRaw.GeoJson", () => GeoJsonAPISource.FetchMunicipality(scopeName));

            var gisFeatures = stateGis.Features.Where(f => filter == null || filter(f)).ToArray();

            if (IsFeatureSchemaOld(gisFeatures[0]))
            {
                gisFeatures = gisFeatures.Select(UpdateFeatureSchema).ToArray();
            }
            Log.LogInformation("Validating Reference material");
            Validate(gisFeatures);

            // Fetch the list of objectIDs with known errors to omit.
            var blacklist = Static.Municipalities[scopeName].BlackList.ToHashSet();

            Log.LogInformation("Translating Reference material");
            // Convert
            var nodes = gisFeatures
                        .Where(f => !blacklist.Contains((long)f.Properties[KEYS.OBJECTID]))
                        .Select(Convert)
                        .Where(n => n.Tags.ContainsKey("addr:housenumber"))
                        .ToArray();

            if (!nodes.Any())
            {
                return(null);
            }
            nodes = HandleStacks(nodes);
            HandleBlackTags(nodes, Static.Municipalities[scopeName].BlackTags);

            foreach (var node in nodes.Where(n => n.Tags.ContainsKey("addr:unit")))
            {
                var newUnit = RemoveTokens(ReplaceTokens(node.Tags["addr:unit"], UNITs), Tags.UnitOmmisionable);
                if (newUnit == "")
                {
                    node.Tags.RemoveKey("addr:unit");
                }
                else
                {
                    node.Tags["addr:unit"] = newUnit;
                }
            }

            var filtered = new Osm()
            {
                Nodes = nodes, Version = .6, Bounds = nodes.AsBounds()
            };

            return(filtered);
        }
Ejemplo n.º 23
0
        public void StorePayload(ReflectedCrossSiteScriptingPayload payload)
        {
            //todo move directory to config
            string projectPath    = Directory.GetParent(Directory.GetCurrentDirectory()).Parent?.Parent?.FullName;
            var    directory      = projectPath + @"\Data\Payloads\";
            var    fileSerializer = new FileSerializer <ReflectedCrossSiteScriptingPayload>();

            fileSerializer.SerializeToDisk(payload, $"{directory}xss-{Guid.NewGuid()}");
        }
        public bool ExportProgram(string filename, float startTime)
        {
            if (filename.EndsWith(".glo", StringComparison.InvariantCultureIgnoreCase))
            {
                filename = filename.Substring(0, filename.Length - 4);
            }

            return(FileSerializer.ExportGloFiles(CurrentDocument.GetModel(), filename + "_", ".glo", startTime));
        }
Ejemplo n.º 25
0
        public void SerializerCreatesEmptyFileOnRead()
        {
            string         filePath       = Path.Combine(this.Repo.GitParentPath, "test-file");
            FileSerializer fileSerializer = new FileSerializer(this.Repo.Context, filePath);

            this.Repo.Context.FileSystem.FileExists(filePath).ShouldEqual(false);
            fileSerializer.ReadAll().ShouldBeEmpty();
            this.Repo.Context.FileSystem.FileExists(filePath).ShouldEqual(true);
        }
Ejemplo n.º 26
0
        public FileConfigInstance(string filename, T instance, string identifier)
        {
            this.filenameMain   = filename;
            this.filenameBackup = filename + ".bak";
            this.identifier     = identifier;

            this.Instance   = instance;
            this.Serializer = new FileSerializer <T>();
        }
        public static void Execute()
        {
            var files = new List <File>
            {
                new(Layout.Quotation, "QuotationTitle", "QuotationContent", "QuotationInfo"),
                new(Layout.Summary, "SummaryTitle", "SummaryContent", "SummaryInfo")
            };

            files.ForEach(file => FileSerializer.Create(file).Serialize());
        }
Ejemplo n.º 28
0
        private void DoConflate()
        {
            var reference = GetReference();
            var subject   = GetSubject(reference.Bounds.ExpandBy(15));
            var Change    = Conflate.Merge(reference, subject, Municipality, Static.Municipalities[Municipality]);

            FileSerializer.WriteXml(Municipality + "/Conflated.osc", Change);
            References.Report(reference.GetElements().ToArray());
            Conflate.Review(Municipality);
        }
Ejemplo n.º 29
0
        public static void CombineSegments()
        {
            var osm      = OpenFile(@"C:\Users\Alex\Downloads\Franklin_Full_Street_Name_simplified.osm").ToArray();
            var index    = OsmSharp.Db.Impl.Extensions.CreateSnapshotDb(new MemorySnapshotDb(osm));
            var highways = osm.OfType <Way>()
                           .Where(w => w.Tags != null && w.Tags.ContainsKey("highway") && w.Tags.ContainsKey("name")).ToArray();
            var highwaysWithChildren = Geometry.CombineSegments(highways).WithChildren(index);

            FileSerializer.WriteXml("Touchers.osm", highwaysWithChildren.AsOsm());
        }
Ejemplo n.º 30
0
 private static void CreateMissingStubs(String test, IEnumerable <TestExecutionStats> array)
 {
     foreach (var stats in array)
     {
         foreach (var stub in stats.MissingStubs)
         {
             var path = Path.Combine(test, stats.Endpoint.Name, "_Missing", $"{stub.Name}.yml");
             FileSerializer.WriteStub(path, stub);
         }
     }
 }
        public bool SaveDocumentAs(string file, bool compressed)
        {
            if (!FileSerializer.SaveToFile(CurrentDocument.GetModel(), file, compressed))
            {
                return(false);
            }

            FilePath = file;
            IsDirty  = false;
            return(true);
        }