public DrawableMapSection(PathItem item, Polygon polygon, int maxPixelsToDraw) { this.polygon = polygon; this.item = item; this.maxPixelsToDraw = maxPixelsToDraw; }
/// <summary> /// The build. /// </summary> /// <returns> /// The <see cref="PathItem"/>. /// </returns> public PathItem Build() { var item = new PathItem() { Parameters = parameters }; switch (method) { case HttpMethod.Get: item.Get = operation; break; case HttpMethod.Post: item.Post = operation; break; case HttpMethod.Patch: item.Patch = operation; break; case HttpMethod.Delete: item.Delete = operation; break; case HttpMethod.Put: item.Put = operation; break; case HttpMethod.Head: item.Head = operation; break; case HttpMethod.Options: item.Options = operation; break; } return item; }
public AutomationElementPathFromRoot(AutomationElement element, string qryString, string glbQryString) { Stack<AutomationElement> pathToRoot = new Stack<AutomationElement>(); while (element != null) { pathToRoot.Push(element); try { element = TreeWalker.RawViewWalker.GetParent(element); } catch { element = null; } } if (pathToRoot.Count > 0) { this.Path = new PathItem(); PathItem tempPathItem = this.Path; PathItem lastPathItem = null; while (pathToRoot.Count > 0) { AutomationElement e = pathToRoot.Pop(); tempPathItem.AutomationId = e.Current.AutomationId; tempPathItem.ClassName = e.Current.ClassName; tempPathItem.LocalizedControlType = e.Current.LocalizedControlType; tempPathItem.ControlType = e.Current.ControlType.ProgrammaticName; tempPathItem.Name = e.Current.Name; tempPathItem.RuntimeId = string.Join(".", Array.ConvertAll<int, string>(e.GetRuntimeId(), new Converter<int, string>(delegate(int i) { return i.ToString(); }))); #if NATIVE_UIA if (pathToRoot.Count == 1) { tempPathItem.ProviderDescription = (string)e.GetCurrentPropertyValue(AutomationElement.ProviderDescriptionProperty); if (qryString != String.Empty) { tempPathItem.QueryString = qryString; } if (glbQryString != String.Empty) { tempPathItem.GlobalizedQryString = glbQryString; } } #endif lastPathItem = tempPathItem; tempPathItem = tempPathItem.ChildItem = new PathItem(); } if (lastPathItem != null) lastPathItem.ChildItem = null; } }
protected override void EnterNode(Node node, IEnumerable<Link> availableThrough) { this.visitedLinks.UnionWith(availableThrough); var item = new PathItem(node); foreach (var pathItem in this.currentPath) { pathItem.Increment(item.CommandExecutionCount); } this.currentPath.Push(item); }
public void MenuAddFile_Click(object sender, RoutedEventArgs e) { var selected = TreeFolderBrowser.SelectedItem as PathItem; if (selected == null) { // No files/folders selected = new PathItem() { IsFolder = true, FullPath = Sidebar.FolderPath }; Sidebar.ActivePathItem = selected; } string path; TreeViewItem parentTreeViewItem = Sidebar.GetNestedTreeviewItem(selected); if (selected.FullPath == "..") { path = Path.Combine(Sidebar.FolderPath, "README.md"); } else if (!selected.IsFolder) { path = Path.Combine(Path.GetDirectoryName(selected.FullPath), "README.md"); } else { if (parentTreeViewItem != null) { parentTreeViewItem.IsExpanded = true; } path = Path.Combine(selected.FullPath, "README.md"); } if (File.Exists(path)) { path = Path.Combine(Path.GetDirectoryName(path), "NewFile.md"); if (File.Exists(path)) { for (int i = 1; i < 30; i++) { path = Path.Combine(Path.GetDirectoryName(path), $"NewFile{i}.md"); if (!File.Exists(path)) { break; } } } } var item = new PathItem { FullPath = path, IsFolder = false, IsFile = true, IsEditing = true, IsSelected = true }; item.EditName = item.DisplayName; item.SetIcon(); if (selected.FullPath == "..") { item.Parent = Sidebar.ActivePathItem; // current path } else if (!selected.IsFolder) { item.Parent = selected.Parent; } else { item.Parent = selected; } item.Parent.Files.Insert(0, item); Model.Window.Dispatcher.InvokeAsync( () => Sidebar.SetTreeViewSelectionByItem(item, parentTreeViewItem), DispatcherPriority.ApplicationIdle); }
private void TranslateForHorizontalOrVerticalLine(PathItem item, IList<PathItem> result) { //TODO check if this is correct IList<float> numbers = item.Coordinates; if (numbers.Count == 0) { numbers.Add(0f); } float[] currentPoint = GetCurrentPoint(result); if (!item.IsRelative()) { //take the last command IList<float> coordinates = new List<float>(); if (item.IsHorizontalLineTo()) { coordinates.Add(numbers[numbers.Count - 1]); coordinates.Add(currentPoint[1]); } else { coordinates.Add(currentPoint[0]); coordinates.Add(numbers[numbers.Count - 1]); } result.Add(new PathItem(coordinates, PathItem.LINE)); } else { float coordinate = 0f; for (int i = 0; i < numbers.Count; i++) { coordinate = numbers[i]; } IList<float> coordinates = new List<float>(); if (item.IsHorizontalLineTo()) { coordinates.Add(coordinate + currentPoint[0]); coordinates.Add(currentPoint[1]); } else { coordinates.Add(currentPoint[0]); coordinates.Add(coordinate + currentPoint[1]); } result.Add(new PathItem(coordinates, PathItem.LINE)); } }
private void TranslateArc(PathItem item, IList<PathItem> result) { //add the current point at the end int size = 7; //needs groups of 7 coordinates IList<float> numbers = item.Coordinates; for (int i = 0; i < (numbers.Count / size); i++) { //first add the current coordinates, copy all and if relative, change the last two coordinates IList<float> coordinates = new List<float>(); float[] currentPoint = GetCurrentPoint(result); for (int j = 0; j < size; j++) { if (j == size - 2 && item.IsRelative()) { //x coordinates.Add(currentPoint[0] + (numbers[(i * size) + j])); } else if (j == size - 1 && item.IsRelative()) { //y coordinates.Add(currentPoint[1] + (numbers[(i * size) + j])); } else { coordinates.Add(numbers[(i * size) + j]); } } //this is a bit strange but easiest way to transfer the coordinates coordinates.Add(currentPoint[0]); coordinates.Add(currentPoint[1]); result.Add(new PathItem(coordinates, PathItem.ARC)); } if (numbers.Count % size != 0) { throw new Exception("Something wrong with the number of coordinates in the path"); } }
public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer) { IPrincipal user = HttpContext.Current.User; foreach (ApiDescription apiDescription in apiExplorer.ApiDescriptions) { var authorizeAttributes = apiDescription .ActionDescriptor.GetCustomAttributes <AuthorizeAttribute>().ToList(); authorizeAttributes.AddRange(apiDescription .ActionDescriptor.ControllerDescriptor.GetCustomAttributes <AuthorizeAttribute>()); if (!authorizeAttributes.Any()) { continue; } var roles = authorizeAttributes .SelectMany(attr => attr.Roles.Split(',')) .Distinct() .ToList(); if (!user.Identity.IsAuthenticated || !roles.Any(role => user.IsInRole(role) || role == "")) { string key = "/" + apiDescription.RelativePath; PathItem pathItem = swaggerDoc.paths[key]; switch (apiDescription.HttpMethod.Method.ToLower()) { case "get": pathItem.get = null; break; case "put": pathItem.put = null; break; case "post": pathItem.post = null; break; case "delete": pathItem.delete = null; break; case "options": pathItem.options = null; break; case "head": pathItem.head = null; break; case "patch": pathItem.patch = null; break; } if (pathItem.get == null && pathItem.put == null && pathItem.post == null && pathItem.delete == null && pathItem.options == null && pathItem.head == null && pathItem.patch == null) { swaggerDoc.paths.Remove(key); } } } swaggerDoc.paths = swaggerDoc.paths.Count == 0 ? null : swaggerDoc.paths; swaggerDoc.definitions = swaggerDoc.paths == null ? null : swaggerDoc.definitions; }
public void MenuAddFile_Click(object sender, RoutedEventArgs e) { var selected = TreeFolderBrowser.SelectedItem as PathItem; if (selected == null) { // No files/folders selected = new PathItem() { IsFolder = true, FullPath = Sidebar.FolderPath }; Sidebar.ActivePathItem = selected; } string path; if (selected.FullPath == "..") { path = Path.Combine(Sidebar.FolderPath, "NewFile.md"); } if (!selected.IsFolder) { path = Path.Combine(Path.GetDirectoryName(selected.FullPath), "NewFile.md"); } else { var treeItem = Sidebar.GetTreeviewItem(selected); if (treeItem != null) { treeItem.IsExpanded = true; } path = Path.Combine(selected.FullPath, "NewFile.md"); } var item = new PathItem { FullPath = path, IsFolder = false, IsFile = true, IsEditing = true, IsSelected = true }; item.SetIcon(); if (selected.FullPath == "..") { item.Parent = Sidebar.ActivePathItem; // current path } else if (!selected.IsFolder) { item.Parent = selected.Parent; } else { item.Parent = selected; } item.Parent.Files.Insert(0, item); Sidebar.SetTreeViewSelectionByItem(item); }
private PathItem CreatePathItem( IEnumerable <ServiceEntry> serviceEntries, ISchemaRegistry schemaRegistry) { var pathItem = new PathItem(); foreach (var entry in serviceEntries) { var methodInfo = entry.Type.GetTypeInfo().DeclaredMethods.Where(p => p.Name == entry.MethodName).FirstOrDefault(); var parameterInfo = methodInfo.GetParameters(); if (entry.Methods.Count() == 0) { if (parameterInfo != null && parameterInfo.Any(p => !UtilityType.ConvertibleType.GetTypeInfo().IsAssignableFrom(p.ParameterType))) { pathItem.Post = CreateOperation(entry, methodInfo, schemaRegistry); } else { pathItem.Get = CreateOperation(entry, methodInfo, schemaRegistry); } } else { foreach (var httpMethod in entry.Methods) { switch (httpMethod) { case "GET": pathItem.Get = CreateOperation(entry, methodInfo, schemaRegistry); break; case "PUT": pathItem.Put = CreateOperation(entry, methodInfo, schemaRegistry); break; case "POST": pathItem.Post = CreateOperation(entry, methodInfo, schemaRegistry); break; case "DELETE": pathItem.Delete = CreateOperation(entry, methodInfo, schemaRegistry); break; case "OPTIONS": pathItem.Options = CreateOperation(entry, methodInfo, schemaRegistry); break; case "HEAD": pathItem.Head = CreateOperation(entry, methodInfo, schemaRegistry); break; case "PATCH": pathItem.Patch = CreateOperation(entry, methodInfo, schemaRegistry); break; } } } } return(pathItem); }
/***************************************************/ /**** Comparer ****/ /***************************************************/ int IComparable <PathItem <T> > .CompareTo(PathItem <T> other) { return(Score.CompareTo(other.Score)); }
/// <summary></summary> public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer) { var thisAssemblyTypes = Assembly.GetExecutingAssembly().GetTypes().ToList(); var odatacontrollers = thisAssemblyTypes.Where(t => t.IsSubclassOf(typeof(ODataController))).ToList(); var odataRoutes = GlobalConfiguration.Configuration.Routes.Where(a => a.GetType() == typeof(ODataRoute)).ToList(); if (!odataRoutes.Any() || !odatacontrollers.Any()) { return; } var odatamethods = new[] { "Get", "Put", "Post", "Delete" }; var route = odataRoutes.FirstOrDefault() as ODataRoute; foreach (var odataContoller in odatacontrollers) // this is all of the OData controllers in your API { var methods = odataContoller.GetMethods().Where(a => odatamethods.Contains(a.Name)).ToList(); if (!methods.Any()) { continue; // next controller -- this one doesn't have any applicable methods } foreach (var method in methods) // this is all of the methods for a SINGLE controller (e.g. GET, POST, PUT, etc) { var path = "/" + route.RoutePrefix + "/" + odataContoller.Name.Replace("Controller", ""); if (swaggerDoc.paths.ContainsKey(path)) { Debug.WriteLine("Path " + path + " already exists"); Console.WriteLine("Path " + path + " already exists"); continue; } var odataPathItem = new PathItem(); var op = new Operation(); // This is assuming that all of the odata methods will be listed under a heading called OData in the swagger doc op.tags = new List <string> { "OData" }; op.operationId = "OData_" + odataContoller.Name.Replace("Controller", ""); // This should probably be retrieved from XML code comments.... op.summary = "Summary for your method / data"; op.description = "Here is where we go deep into the description and options for the call."; op.consumes = new List <string>(); op.produces = new List <string> { "application/atom+xml", "application/json", "text/json", "application/xml", "text/xml" }; op.deprecated = false; var response = new Response() { description = "OK" }; response.schema = new Schema { type = "array", items = schemaRegistry.GetOrRegister(method.ReturnType) }; op.responses = new Dictionary <string, Response> { { "200", response } }; var security = GetSecurityForOperation(odataContoller); if (security != null) { op.security = new List <IDictionary <string, IEnumerable <string> > > { security } } ; odataPathItem.get = op; // this needs to be a switch based on the method name if (swaggerDoc.paths.ContainsKey(path)) { Debug.WriteLine("Path " + path + " already exists"); Console.WriteLine("Path " + path + " already exists"); } else { swaggerDoc.paths.Add(path, odataPathItem); } } } }
/// <summary> /// Apply /// </summary> /// <param name="swaggerDoc"></param> /// <param name="schemaRegistry"></param> /// <param name="apiExplorer"></param> public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer) { PathItem item = new PathItem(); item.post = new Operation(); item.post.tags = new List <string> { "Auth" }; item.post.consumes = new List <string> { "application/x-www-form-urlencoded" }; item.parameters = new List <Parameter>(); Parameter grantType = new Parameter() { type = "string", name = "grant_type", required = true, @in = "password" }; Parameter userName = new Parameter() { type = "string", name = "username", required = true, @in = "Kullanıcı Adı" }; Parameter password = new Parameter() { type = "string", name = "password", required = true, @in = "Şifre" }; Parameter clientId = new Parameter() { type = "string", name = "client_id", required = true, @in = "client_id" }; item.parameters.Add(clientId); item.parameters.Add(password); item.parameters.Add(userName); item.parameters.Add(grantType); swaggerDoc.paths.Add(Settings.Default.TokenPath, item); //swaggerDoc.paths.Add(Settings.Default.TokenPath, new PathItem //{ // post = new Operation // { // tags = new List<string> { "Auth" }, // consumes = new List<string> // { // "application/x-www-form-urlencoded" // }, // parameters = new List<Parameter> { // new Parameter // { // type = "string", // name = "grant_type", // required = true, // @in = "password" // }, // new Parameter // { // type = "string", // name = "username", // required = true, // @in = "Kullanıcı Adı" // }, // new Parameter // { // type = "string", // name = "password", // required = true, // @in = "Şifre" // }, // new Parameter // { // type = "string", // name = "client_id", // required = true, // @in = "Client ID" // } // } // } //}); }
private static PathItem[] ParsePath(JObject paths) { var result = new List<PathItem>(); foreach (JProperty path in paths.Children()) { var pathItem = new PathItem { Path = path.Name }; pathItem.Get = ParseOperation(path.Children()["get"].SingleOrDefault()); pathItem.Put = ParseOperation(path.Children()["put"].SingleOrDefault()); pathItem.Post = ParseOperation(path.Children()["post"].SingleOrDefault()); pathItem.Delete = ParseOperation(path.Children()["delete"].SingleOrDefault()); pathItem.Options = ParseOperation(path.Children()["options"].SingleOrDefault()); pathItem.Head = ParseOperation(path.Children()["head"].SingleOrDefault()); pathItem.Patch = ParseOperation(path.Children()["patch"].SingleOrDefault()); pathItem.Parameters = ParseParameters(path.Children()["parameters"].SingleOrDefault()); result.Add(pathItem); } Debug.WriteLine($"Paths parsed: {result.Aggregate("", (curr, next) => curr + (curr.Length > 0 ? ", " : "") + next)}"); return result.ToArray(); }
public void Update(float deltaTime) { if (Count == 0 && currentItem == null) { StopAction = null; return; } DeltaD += deltaTime; DeltaF += deltaTime; PathStartTimeF += deltaTime; PathStartTimeD += deltaTime; if (currentItem == null) { SetCurrentItem(); Update(0f); } else { try { switch (currentItem.Invoke(this)) { case Status.Continue: return; case Status.OK: SetCurrentItem(); ResetTimers(); return; case Status.Now: case Status.Immediately: SetCurrentItem(); ResetTimers(); Update(0); return; case Status.Error: actions = errors; errors = new Queue <PathItem>(); SetCurrentItem(); ResetTimers(); Loop = false; Update(0); return; case Status.Stop: StopPath(); return; } } catch (Exception e) { var ex = e; if (e.InnerException != null) { ex = e.InnerException; } Log.Error(ex); currentItem = null; actions = errors; errors = new Queue <PathItem>(); SetCurrentItem(); ResetTimers(); Loop = false; Update(0); } } }
public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context) { Assembly assembly = typeof(ODataController).Assembly; var thisAssemblyTypes = Assembly.GetExecutingAssembly().GetTypes().ToList(); var projectTypeNames = GetProjectTypes(); //var allowedControllers = new string[] { // "ProjectDetailsController" //}; var odatacontrollers = thisAssemblyTypes.Where(t => t.BaseType == typeof(ODataController) /*&& allowedControllers.Contains(t.Name)*/) .ToList(); var xmlComments = LoadCommentsXML(); foreach (var odataContoller in odatacontrollers) // this the OData controllers in the API { //Requires endpoint methods to be decorated with [HttpGet], [HttpPost], etc... var methods = odataContoller.GetMethods() .Where(a => a.CustomAttributes.Any(x => x.AttributeType == typeof(HttpGetAttribute) || x.AttributeType == typeof(HttpPostAttribute) || x.AttributeType == typeof(HttpPutAttribute) || x.AttributeType == typeof(HttpPatchAttribute) || x.AttributeType == typeof(HttpDeleteAttribute))) .ToList(); if (!methods.Any()) { continue; // next controller } foreach (var method in methods) // this is all of the public methods in controller { var methodComments = GetMethodComments(xmlComments, method); StringBuilder sb = new StringBuilder(); //Add method name - ignore implicit names var implicitNames = new string[] { "get", "post", "put", "patch", "delete" }; if (!implicitNames.Contains(method.Name.ToLower())) { sb.Append("/" + method.Name); } //Get parameters List <string> listParams = new List <string>(); var parameterInfo = method.GetParameters().Where(pi => !pi.CustomAttributes.Any(x => x.AttributeType == typeof(FromBodyAttribute))); //Process any parameters if (parameterInfo.Count() > 0) { sb.Append("("); foreach (ParameterInfo pi in parameterInfo) { listParams.Add("{" + pi.Name + "}"); } sb.Append(string.Join(", ", listParams.ToArray())); sb.Append(")"); } ; //Construct Operation var op = new Operation(); var _params = new List <IParameter>(); parameterInfo = method.GetParameters(); foreach (var pi in parameterInfo) { var body = pi.CustomAttributes.Any(x => x.AttributeType == typeof(FromBodyAttribute)); if (body) { _params.Add(new BodyParameter() { Name = pi.Name, In = "body", Required = !pi.IsOptional, Description = GetParamComment(methodComments, pi.Name), Schema = context.SchemaRegistry.GetOrRegister(pi.ParameterType) }); } else { _params.Add(new NonBodyParameter() { Name = pi.Name, In = "path", Required = true, //path params must always be required according to OpenAPI spec Description = GetParamComment(methodComments, pi.Name), Type = context.SchemaRegistry.GetOrRegister(pi.ParameterType).Type }); } } op.Parameters = _params; // The odata methods will be listed under a heading with the Controller name in swagger doc op.Tags = new List <string> { odataContoller.Name.Replace("Controller", "") }; op.OperationId = method.ToString().ToBase64(); //path; op.Summary = GetComment(methodComments, "summary"); op.Description = "Returns: " + GetComment(methodComments, "returns"); op.Consumes = new List <string> { "application/json" }; //Other options: "application/atom+xml", "application/json", "text/json", "application/xml", "text/xml" op.Produces = new List <string> { "application/json" }; //Other options: "application/atom+xml", "application/json", "text/json", "application/xml", "text/xml" op.Deprecated = false; //Process responses var successResponse = new Response() { Description = "OK" }; if (projectTypeNames.Any(x => method.ReturnType.FullName.Contains(x))) { successResponse.Schema = context.SchemaRegistry.GetOrRegister(method.ReturnType); } var failResponse = new Response() { Description = "Bad Request" }; op.Responses = new Dictionary <string, Response> { { "200", successResponse }, { "400", failResponse }, }; //Process security var security = GetSecurityForOperation(method); if (security != null) { op.Security = new List <IDictionary <string, IEnumerable <string> > > { security }; } //Find existing pathItem (if any) var path = "/" + "odata" + "/" + odataContoller.Name.Replace("Controller", "") + sb.ToString(); var odataPathItem = new PathItem(); if (swaggerDoc.Paths.ContainsKey(path)) { odataPathItem = swaggerDoc.Paths[path]; } //Requires endpoint methods to be decorated with [HttpGet], [HttpPost], etc... if (method.CustomAttributes.Any(x => x.AttributeType == typeof(HttpPostAttribute))) { odataPathItem.Post = op; } else if (method.CustomAttributes.Any(x => x.AttributeType == typeof(HttpPutAttribute))) { odataPathItem.Put = op; } else if (method.CustomAttributes.Any(x => x.AttributeType == typeof(HttpPatchAttribute))) { odataPathItem.Patch = op; } else if (method.CustomAttributes.Any(x => x.AttributeType == typeof(HttpDeleteAttribute))) { odataPathItem.Delete = op; } else { odataPathItem.Get = op; } //Add to SwaggerDoc if (!swaggerDoc.Paths.ContainsKey(path)) { try { swaggerDoc.Paths.Add(path, odataPathItem); } catch { } } } } //Remove model definitions that I did not create (i.e. not defined in this project) var removeDefs = swaggerDoc.Definitions.Where(d => !projectTypeNames.Contains(d.Key)).Select(d => d.Key).ToList(); foreach (var def in removeDefs) { swaggerDoc.Definitions.Remove(def); } }
static void Main(string[] args) { var random = new Random(); var ts = new TransportSystem("TransportSystem"); const int noOfTests = 500; // no of test to conduct const int minSpeed = 1; const int maxSpeed = 12; // max speed for heuresutic int validTestNo = 0; Console.WriteLine("Så kører vi"); var fs = new FileStream(@"C:\Dropbox\CSS\TransportSystem\Heurestics.csv", FileMode.Create); using (var writer = new StreamWriter(fs, Encoding.UTF8)) { writer.Write("Test no; From Stop; To Stop; Date Time; Day;Distance;rute time;lowest Speed; min speed; min iter; 0-routeTime;0-time;"); for (int i = minSpeed; i <= maxSpeed; i++) { writer.Write($"{i} -routeTime; {i} -time;"); } writer.WriteLine(); for (int i = 0; i < noOfTests; i++) { // first find arbitrary stop points and time! TestData thisTest = new TestData { FromStop = GetStopNo(105, 10946), ToStop = GetStopNo(105, 10946), //DateTime = (int)UTCHelpers.Parse () // giver "DateTime_Now" i datasættet DateTime = random.Next(1461546000, 1462155600) }; thisTest.TestDatas = new List <Test>(); var referenceTest = ConductTest(thisTest.FromStop, thisTest.ToStop, thisTest.DateTime, 0); Console.WriteLine(thisTest + "Distance = " + referenceTest.Distance + " m. Tid brugt = " + referenceTest.TimeUsed); thisTest.PathFound = !(referenceTest.Path == null); if (!thisTest.PathFound) { continue; // no path found, skipping rest of test! } Console.WriteLine($"Path found for test # {i}"); referenceTest.Valid = true; // speed = 0 => Dijkstra Algorithm. thisTest.TestDatas.Add(referenceTest); Console.WriteLine($"Reference test = {referenceTest.Iterations}. Route Time = {referenceTest.RouteTime.ToTime()}."); validTestNo++; for (int j = minSpeed; j <= maxSpeed; j++) { var newTest = ConductTest(thisTest.FromStop, thisTest.ToStop, thisTest.DateTime, j); newTest.Valid = ComparteTests(referenceTest.Path, newTest.Path); Console.WriteLine($"Test med Speed = {j} m/s, {newTest.Iterations} iterationer, er {newTest.Valid}. Tid brugt = {newTest.TimeUsed}. Route længde = {newTest.RouteTime.ToTime()}"); thisTest.TestDatas.Add(newTest); } var dateTime = TimeHelpers.UnixTimeToDateTime(thisTest.DateTime); writer.Write($"{validTestNo};{thisTest.FromStop};{thisTest.ToStop};{dateTime.ToTime()};{dateTime.ToDayOfWeek()};{thisTest.TestDatas[0].Distance};{thisTest.TestDatas[0].RouteTime.ToTime()};"); int minInterations = Int32.MaxValue - 1; int speedMinIterations = 0; int lowestSpeed = Int32.MaxValue - 1; StringBuilder s = new StringBuilder(); for (int t = 0; t < thisTest.TestDatas.Count; t++) { var test = thisTest.TestDatas[t]; s.Append($"{test.RouteTime.ToTime()};"); if (test.Valid) { s.Append($"{test.TimeUsed};"); if (test.Iterations < minInterations) { minInterations = test.Iterations; speedMinIterations = test.Speed; } if ((test.Speed < lowestSpeed) & t > 0) // Dijkstra not to be included! { lowestSpeed = test.Speed; } } else { s.Append($"0;"); } } writer.Write($"{lowestSpeed};{speedMinIterations};{speedMinIterations};"); writer.Write(s.ToString()); writer.WriteLine(); } writer.Flush(); } if (fs != null) { fs.Close(); fs.Dispose(); } Console.WriteLine("Tryk en tast.."); Console.ReadKey(); int GetStopNo(int min, int max) { int stopFound = 0; while (stopFound == 0) { int r = random.Next(min, max); stopFound = ts.NetworkNodes.Where(s => s.StopId == r).Select(s => s.StopId).SingleOrDefault(); } return(stopFound); } Test ConductTest(int a, int b, int time, int speed) { var AStar = new AStar(ts); var test = new Test { Speed = speed, Valid = false }; test.Distance = AStar.DistanceAB(a, b); if (speed == 0) { AStar.StandardSpeed = 0; } else { AStar.StandardSpeed = speed; } test.Path = AStar.FindPath(a, b, time, true); test.Iterations = AStar.Iterations; test.TimeUsed = AStar.StopWatch; test.RouteTime = CalculateRouteTime(test.Path); return(test); } Boolean ComparteTests(List <PathItem> refList, List <PathItem> list) { if (list == null) { return(false); } if (refList.Count != list.Count) { return(false); } for (var i = 0; i < refList.Count; i++) { if (!refList[i].Equals(list[i])) { return(false); } } return(true); } long CalculateRouteTime(List <PathItem> refList) { if (refList == null) { return(0); } long startTime, endTime, walkTime = 0; int i = 0; PathItem item = refList[i]; // TimeTableId == -1 => Walking distance while ((item.TimeTableId == -1) & (i < refList.Count - 1)) { walkTime += ts.Edges.Where(x => x.EdgeId == item.EdgeId).FirstOrDefault().DistanceWalk; i++; item = refList[i]; // take next in list } var t = ts.TimeTables.Where(y => y.TimeTableId == item.TimeTableId).FirstOrDefault(); if (t == null) { return(0); // invalid path! } startTime = t.DepartureTime - walkTime; walkTime = 0; i = refList.Count - 1; item = refList[i]; while ((item.TimeTableId == -1) & (i > 0)) { walkTime += ts.Edges.Where(x => x.EdgeId == item.EdgeId).First().DistanceWalk; i--; item = refList[i]; } t = ts.TimeTables.Where(y => y.TimeTableId == item.TimeTableId).FirstOrDefault(); endTime = t.ArrivalTime + walkTime; return(endTime - startTime); } }
/// <summary> /// Teleports the player a new path item (cheat away!) /// </summary> /// <param name="item">The item to teleport to</param> public void TeleportTo(PathItem item) { this.moveTarget = item; this.location = new Vector2( (item.location.X), (item.location.Y - this.GetDrawRectangle().Height / 2)); if (this.onPlayerReachedPathItemListeners != null) this.onPlayerReachedPathItemListeners(item); }
private void CreateFile(PathItem pathItem) { Console.WriteLine("Creating XCode files."); }
private PathItem CreatePathItem(IEnumerable <ApiDescription> apiDescriptions, ISchemaRegistry schemaRegistry) { var pathItem = new PathItem(); var newApiDescriptions = ReGenerateApiDes(apiDescriptions); // Group further by http method var perMethodGrouping = newApiDescriptions .GroupBy(apiDesc => apiDesc.HttpMethod); foreach (var group in perMethodGrouping) { var httpMethod = group.Key; if (httpMethod == null) { throw new NotSupportedException( $"Ambiguous HTTP method for action - {@group.First().ActionDescriptor.DisplayName}. " + "Actions require an explicit HttpMethod binding for Swagger"); } if (group.Count() > 1) { throw new NotSupportedException( $"HTTP method \"{httpMethod}\" & path \"{@group.First().RelativePathSansQueryString()}\" overloaded by actions - {string.Join(",", @group.Select(apiDesc => apiDesc.ActionDescriptor.DisplayName))}. " + "Actions require unique method/path combination for Swagger"); } var apiDescription = group.Single(); switch (httpMethod) { case "GET": pathItem.Get = CreateOperation(apiDescription, schemaRegistry); break; case "PUT": pathItem.Put = CreateOperation(apiDescription, schemaRegistry); break; case "POST": pathItem.Post = CreateOperation(apiDescription, schemaRegistry); break; case "DELETE": pathItem.Delete = CreateOperation(apiDescription, schemaRegistry); break; case "OPTIONS": pathItem.Options = CreateOperation(apiDescription, schemaRegistry); break; case "HEAD": pathItem.Head = CreateOperation(apiDescription, schemaRegistry); break; case "PATCH": pathItem.Patch = CreateOperation(apiDescription, schemaRegistry); break; } } return(pathItem); }
//-------------------------------------------------------------------------------- /// <summary> /// Auto-generate swagger PathItem from an http trigger method /// </summary> //-------------------------------------------------------------------------------- private static PathItem CreatePathItemFromMethod(MethodInfo azureFunction) { var functionNameAttribute = GetCustomAttribute(azureFunction, "FunctionNameAttribute"); var httpTriggerAttribute = GetCustomAttribute(azureFunction.GetParameters()[0], "HttpTriggerAttribute"); var handlerProperty = azureFunction.DeclaringType.GetProperty("Handler", BindingFlags.Public | BindingFlags.Static); var handlerMethod = handlerProperty.PropertyType.GetMethod(azureFunction.Name); var parameters = new List <Parameter>(); foreach (var property in handlerMethod.GetParameters()[0].ParameterType.GetProperties()) { var functionInfo = property.GetParams(); var name = property.GetSourcePropertyName(); parameters.Add(new Parameter() { Name = name, In = functionInfo == null ? ParameterIn.Query : functionInfo.Source, Description = functionInfo?.SwaggerDescription, Required = functionInfo == null ? false : functionInfo.IsRequired, Type = property.PropertyType.Name, }); } var schemaProperties = new Dictionary <string, Schema>(); schemaProperties.Add("Count", new Schema() { Type = "integer", Description = "Number of Values" }); schemaProperties.Add("ErrorCode", new Schema() { Type = "string", Description = "Short Text Description of any error (if any)" }); schemaProperties.Add("ErrorMessage", new Schema() { Type = "string", Description = "Detailed error message (if any)" }); schemaProperties.Add("Value", new Schema() { Type = "array", Items = new Item() { Type = handlerMethod.ReturnType.Name }, Description = "Data returned from a successful operation (in any)" }); var itemResponses = new Dictionary <string, Response>(); itemResponses.Add("*", new Response() { Description = "Any Response", Schema = new Schema() { Type = "object", Properties = schemaProperties } }); var pathItem = new PathItem(); var operation = new Operation() { OperationId = GetPropertyValue <string>(functionNameAttribute, "Name"), Produces = new[] { "application/json" }, Consumes = new[] { "application/json" }, Parameters = parameters, Responses = itemResponses }; foreach (var method in GetPropertyValue <string[]>(httpTriggerAttribute, "Methods")) { switch (method.ToLower()) { case "get": pathItem.Get = operation; break; case "post": pathItem.Post = operation; break; case "put": pathItem.Put = operation; break; case "head": pathItem.Head = operation; break; case "patch": pathItem.Patch = operation; break; case "delete": pathItem.Delete = operation; break; case "options": pathItem.Options = operation; break; } } return(pathItem); }
private IList<float[]> ArcToLines(PathItem item) { IList<float> numbers = item.Coordinates; EllipseArc ellipse = EllipseArc.CreateEllipseArc(numbers[7], numbers[8], numbers[5], numbers[6], numbers[0], numbers[1], numbers[4], numbers[3]); IList<float[]> newCoordinates = PdfContentByte.BezierArc(ellipse.Cx - numbers[0], ellipse.Cy - numbers[1], ellipse.Cx + numbers[0], ellipse.Cy + numbers[1], ellipse.StartAng, ellipse.Extend); IList<float[]> result = new List<float[]>(); if (newCoordinates.Count == 0) return result; float[] pt = newCoordinates[0]; float x0 = pt[0]; float y0 = pt[1]; for (int k = 0; k < newCoordinates.Count; ++k) { pt = newCoordinates[k]; foreach (float[] point in BezierCurveToLines(x0, y0, pt[2], pt[3], pt[4], pt[5], pt[6], pt[7], true)) { result.Add(point); } x0 = pt[6]; y0 = pt[7]; } return result; }
public void AddToPathItems(PathItem pathItem) { base.AddObject("PathItems", pathItem); }
private IList<float[]> BezierCurveToLines(IList<float[]> coordinates, PathItem item){ IList<float> numbers = item.Coordinates; float[] start = coordinates[coordinates.Count - 1]; float x0 = start[0]; float y0 = start[1]; float x1 = numbers[0]; float y1 = numbers[1]; float x2 = numbers[2]; float y2 = numbers[3]; float x3 = 0; float y3 = 0; if(item.IsCubicBezier()){ x3 = numbers[4]; y3 = numbers[5]; } return BezierCurveToLines(x0, y0, x1, y1, x2, y2, x3, y3, item.IsCubicBezier()); }
public PathItem(ITlaState state, PathItem prev, ITlaTransition fromTransition) { this.State = state; this.Prev = prev; this.FromTransition = fromTransition; }
/** CoroutineMain */ public System.Collections.IEnumerator CoroutineMain(Fee.AssetBundleList.OnAssetBundleListCoroutine_CallBackInterface a_callback_interface, string a_assetbundle_name) { //result this.result = new ResultType(); { AssetBundleItem t_assetbundle_item = Fee.AssetBundleList.AssetBundleList.GetInstance().GetAssetBundleItem(a_assetbundle_name); if (t_assetbundle_item != null) { //成功。 this.result.assetbundle_item = t_assetbundle_item; yield break; } } PathItem t_pathitem = AssetBundleList.GetInstance().GetPathItem(a_assetbundle_name); if (t_pathitem == null) { //失敗。 this.result.errorstring = "Coroutine_LoadPathItemAssetBundleItem : Not Found Path : " + a_assetbundle_name; yield break; } //ダミーアセットバンドルの読み込み。 #if (UNITY_EDITOR) if (t_pathitem.assetbundle_pathtype == AssetBundlePathType.AssetsPathDummyAssetBundle) { string t_result_string = null; { Fee.File.Item t_item_dummy_assetbundle_json = Fee.File.File.GetInstance().RequestLoad(File.File.LoadRequestType.LoadAssetsPathTextFile, t_pathitem.assetbundle_path); if (t_item_dummy_assetbundle_json == null) { //失敗。 this.result.errorstring = "Coroutine_LoadPathItemAssetBundleItem : item_json = null : " + a_assetbundle_name; yield break; } do { if (a_callback_interface != null) { a_callback_interface.OnAssetBundleListCoroutine(t_item_dummy_assetbundle_json.GetResultProgress()); } yield return(null); }while(t_item_dummy_assetbundle_json.IsBusy() == true); if (t_item_dummy_assetbundle_json.GetResultAssetType() == Asset.AssetType.Text) { t_result_string = t_item_dummy_assetbundle_json.GetResultAssetText(); } if (t_result_string == null) { //失敗。 this.result.errorstring = "Coroutine_LoadPathItemAssetBundleItem : result_string == null : " + a_assetbundle_name; yield break; } } //DummryAssetBundle Fee.AssetBundleList.DummryAssetBundle t_dummyassetbundle = Fee.JsonItem.Convert.JsonStringToObject <Fee.AssetBundleList.DummryAssetBundle>(t_result_string); if (t_dummyassetbundle == null) { //失敗。 this.result.errorstring = "Coroutine_LoadPathItemAssetBundleItem : dummyassetbundle = null : " + a_assetbundle_name; yield break; } AssetBundleItem t_assetbundle_item = new AssetBundleItem(t_dummyassetbundle, t_pathitem); //登録。 Fee.AssetBundleList.AssetBundleList.GetInstance().RegistAssetBundleItem(a_assetbundle_name, t_assetbundle_item); //成功。 this.result.assetbundle_item = t_assetbundle_item; yield break; } #endif //アセットバンドルの読み込み。 { //アセットバンドル。 Fee.Pattern.Progress t_progress = new Fee.Pattern.Progress(new float[] { 0.5f, 0.5f }); //アセットバンドルのバイナリ読み込み。 byte[] t_result_binary = null; { Fee.File.Item t_item_bianry = null; switch (t_pathitem.assetbundle_pathtype) { #if (UNITY_EDITOR) case AssetBundlePathType.AssetsPathAssetBundle: { //アセットフォルダにあるアセットバンドルの相対パス。 t_item_bianry = Fee.File.File.GetInstance().RequestLoad(File.File.LoadRequestType.LoadAssetsPathBinaryFile, t_pathitem.assetbundle_path); } break; #endif case AssetBundlePathType.UrlAssetBundle: { //URL。 t_item_bianry = Fee.File.File.GetInstance().RequestLoad(File.File.LoadRequestType.LoadUrlBinaryFile, t_pathitem.assetbundle_path); } break; case AssetBundlePathType.StreamingAssetsAssetBundle: { //ストリーミングアセット。 t_item_bianry = Fee.File.File.GetInstance().RequestLoad(File.File.LoadRequestType.LoadStreamingAssetsBinaryFile, t_pathitem.assetbundle_path); } break; case AssetBundlePathType.LocalAssetBundle: { //ローカル。 t_item_bianry = Fee.File.File.GetInstance().RequestLoad(File.File.LoadRequestType.LoadLocalBinaryFile, t_pathitem.assetbundle_path); } break; case AssetBundlePathType.FullPathAssetBundle: { //フルパス。 t_item_bianry = Fee.File.File.GetInstance().RequestLoad(File.File.LoadRequestType.LoadFullPathBinaryFile, t_pathitem.assetbundle_path); } break; default: { //失敗。 this.result.errorstring = "Coroutine_LoadPathItemAssetBundleItem : PathTypeError : " + a_assetbundle_name; yield break; } break; } if (t_item_bianry == null) { //失敗。 this.result.errorstring = "Coroutine_LoadPathItemAssetBundleItem : item_bianry = null : " + a_assetbundle_name; yield break; } do { //■ステップ0。 if (a_callback_interface != null) { t_progress.SetStep((int)Progress_MainStep.Progress_MainStep_0_LoadBinary, 0, 1); a_callback_interface.OnAssetBundleListCoroutine(t_progress.CalcProgress(t_item_bianry.GetResultProgress())); } yield return(null); }while(t_item_bianry.IsBusy() == true); if (t_item_bianry.GetResultAssetType() == Asset.AssetType.Binary) { t_result_binary = t_item_bianry.GetResultAssetBinary(); } if (t_result_binary == null) { //失敗。 this.result.errorstring = "Coroutine_LoadPathItemAssetBundleItem : result_binary == null : " + a_assetbundle_name; yield break; } else { System.Collections.Generic.Dictionary <string, string> t_response_header = t_item_bianry.GetResultResponseHeader(); if (t_response_header != null) { string t_response_code; if (t_item_bianry.GetResultResponseHeader().TryGetValue(Fee.File.Config.RESPONSECODE_KEY, out t_response_code) == true) { if (t_response_code != "200") { //失敗。 this.result.errorstring = "Coroutine_LoadPathItemAssetBundleItem : t_response_code = " + t_response_code; yield break; } } } } } //バイナリーのアセットバンドル化。 { UnityEngine.AssetBundleCreateRequest t_request = null; //LoadFromMemoryAsync try{ t_request = UnityEngine.AssetBundle.LoadFromMemoryAsync(t_result_binary); }catch (System.Exception t_exception) { Tool.DebugReThrow(t_exception); } if (t_request == null) { this.result.errorstring = "Coroutine_LoadPathItemAssetBundleItem : request == null : " + a_assetbundle_name; yield break; } do { //■ステップ1。 if (a_callback_interface != null) { t_progress.SetStep((int)Progress_MainStep.Progress_MainStep_1_LoadFromMemoryAsync, 0, 1); a_callback_interface.OnAssetBundleListCoroutine(t_progress.CalcProgress(t_request.progress)); } yield return(null); }while(t_request.isDone == false); if (t_request.assetBundle == null) { //失敗。 this.result.errorstring = "Coroutine_LoadPathItemAssetBundleItem : assetbundle == null : " + a_assetbundle_name; yield break; } { AssetBundleItem t_assetbundle_item = new AssetBundleItem(t_request.assetBundle, t_pathitem); #if (UNITY_EDITOR) { UnityEngine.Object[] t_object = t_request.assetBundle.LoadAllAssets(); for (int ii = 0; ii < t_object.Length; ii++) { Tool.Log(a_assetbundle_name, t_object[ii].name); } } #endif //登録。 Fee.AssetBundleList.AssetBundleList.GetInstance().RegistAssetBundleItem(a_assetbundle_name, t_assetbundle_item); //成功。 this.result.assetbundle_item = t_assetbundle_item; yield break; } } } }
public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer) { swaggerDoc.info.title = "Smartstore Web-API"; var thisAssemblyTypes = Assembly.GetExecutingAssembly().GetTypes().ToList(); var odataMethods = new[] { "Get", "Put", "Post", "Patch", "Delete" }; var odataControllers = thisAssemblyTypes.Where(t => t.IsSubclassOf(typeof(ODataController))).ToList(); var odataRoutes = GlobalConfiguration.Configuration.Routes.Where(a => a.GetType() == typeof(ODataRoute)).ToList(); if (!odataRoutes.Any() || !odataControllers.Any()) { return; } var route = odataRoutes.FirstOrDefault() as ODataRoute; foreach (var odataContoller in odataControllers.OrderBy(x => x.Name)) { var methods = odataContoller.GetMethods().Where(a => odataMethods.Contains(a.Name)).ToList(); if (!methods.Any()) { continue; } foreach (var method in methods) { var path = "/" + route.RoutePrefix + "/" + odataContoller.Name.Replace("Controller", ""); if (swaggerDoc.paths.ContainsKey(path)) { continue; } var odataPathItem = new PathItem(); var op = new Operation(); // This is assuming that all of the odata methods will be listed under a heading called OData in the swagger doc op.tags = new List <string> { "OData" }; op.operationId = "OData_" + odataContoller.Name.Replace("Controller", ""); // This should probably be retrieved from XML code comments.... op.summary = "Summary for your method / data"; op.description = "Here is where we go deep into the description and options for the call."; op.consumes = new List <string>(); op.produces = new List <string> { "application/json", "text/json", "application/xml", "text/xml" }; op.deprecated = false; var response = new Response { description = "OK" }; response.schema = new Schema { type = "array", items = schemaRegistry.GetOrRegister(method.ReturnType) }; op.responses = new Dictionary <string, Response> { { "200", response } }; // this needs to be a switch based on the method name odataPathItem.get = op; swaggerDoc.paths.Add(path, odataPathItem); } } }
public void ShouldAlwaysGetMin() { var queue = new PathPriorityQueue(); var items = new List <PathItem>(); var random = new Random(); for (var i = 0; i < 5000; i++) { var item = new PathItem { TotalCost = random.Next(0, 100000) }; items.Add(item); queue.Enqueue(item); } for (var i = 0; i < 50; i++) { var min = items.OrderBy(x => x.TotalCost).First(); Assert.AreEqual(min.TotalCost, queue.Pop().TotalCost, $"Failed at index {i}."); items.Remove(min); } for (var i = 0; i < 50; i++) { var item = items[i]; item.TotalCost = random.Next(0, 100000); } for (var i = 0; i < 20; i++) { var item = new PathItem { TotalCost = random.Next(0, 100) }; items.Add(item); queue.Enqueue(item); } for (var i = 0; i < 4500; i++) { var min = items.OrderBy(x => x.TotalCost).First(); Assert.AreEqual(min.TotalCost, queue.Pop().TotalCost, $"Failed at index {i}."); items.Remove(min); } for (var i = 0; i < 20; i++) { var item = items[i]; item.TotalCost = random.Next(0, 1000); } for (var i = 0; i < 20; i++) { var min = items.OrderBy(x => x.TotalCost).First(); Assert.AreEqual(min.TotalCost, queue.Pop().TotalCost, $"Failed at index {i}."); items.Remove(min); } for (var i = 0; i < 400; i++) { var item = items[i]; item.TotalCost = random.Next(0, 100000); } for (var i = 0; i < 450; i++) { var min = items.OrderBy(x => x.TotalCost).First(); Assert.AreEqual(min.TotalCost, queue.Pop().TotalCost, $"Failed at index {i}."); items.Remove(min); } Assert.AreEqual(0, queue.Count); }
/// <summary> /// When the player's path has changed. /// </summary> /// <param name="item">The item to which the path was changed.</param> public void OnPlayerPathChanged(PathItem item) { if (MiniGameOverviewMainGame.GetInstance().backgroundMap != null && MiniGameOverviewMainGame.GetInstance().backgroundMap.GetPathByGame(item.game).isFullyColored) { switch (item.game) { case StateManager.SelectedGame.MainMenu: this.backgroundTexture = MAIN_MENU_DESCRIPTION; this.backgroundColor = Color.Transparent; this.startGameBtn.backgroundTexture = MAIN_MENU_BUTTON; this.startGameBtn.mouseoverBackgroundTexture = MAIN_MENU_BUTTON_HOVER; this.bounds = GameInfoDisplayPanel.GetDrawRectangle(0); break; case StateManager.SelectedGame.BalloonPaintBucketGame: this.backgroundTexture = BALLOON_POPPER_DESCRIPTION; this.startGameBtn.backgroundTexture = START_GAME_BUTTON; this.startGameBtn.mouseoverBackgroundTexture = START_GAME_BUTTON_HOVER; this.bounds = GameInfoDisplayPanel.GetDrawRectangle(1); break; case StateManager.SelectedGame.DigGame: this.backgroundTexture = DIG_DESCRIPTION; this.startGameBtn.backgroundTexture = START_GAME_BUTTON; this.startGameBtn.mouseoverBackgroundTexture = START_GAME_BUTTON_HOVER; this.bounds = GameInfoDisplayPanel.GetDrawRectangle(2); break; case StateManager.SelectedGame.SquatBugsGame: this.backgroundTexture = BUG_SQUAT_DESCRIPTION; this.startGameBtn.backgroundTexture = START_GAME_BUTTON; this.startGameBtn.mouseoverBackgroundTexture = START_GAME_BUTTON_HOVER; this.bounds = GameInfoDisplayPanel.GetDrawRectangle(3); break; case StateManager.SelectedGame.BuzzBattleGame: this.backgroundTexture = BUZZ_DESCRIPTION; this.startGameBtn.backgroundTexture = START_GAME_BUTTON; this.startGameBtn.mouseoverBackgroundTexture = START_GAME_BUTTON_HOVER; this.bounds = GameInfoDisplayPanel.GetDrawRectangle(4); break; } this.visible = true; } else if (item.game == StateManager.SelectedGame.MainMenu) this.visible = true; else this.visible = false; selectedGame = item.game; }
public SwaggerRouteData(string path, PathItem pathItem) { Path = RemovePathParameterTypes(path); PathItem = pathItem; Types = new Dictionary <HttpMethod, Type>(); }
private void TranslateCurves(PathItem item, IList<PathItem> result) { int size; if (item.IsCubicBezier()) { size = 6; } else if (item.IsCubicBezierShorthand() || item.IsQuadraticBezier()) { size = 4; } else { size = 2; } IList<float> numbers = item.Coordinates; for (int i = 0; i < (numbers.Count / size); i++) { IList<float> coordinates = new List<float>(); //shorthand notations - get the coordinates of the first control point if (item.IsCubicBezierShorthand() || item.IsQuadraticBezierShorthand()) { //add the last control point of the previous pathItem if (result != null && result.Count != 0) { PathItem previous = result[result.Count - 1]; if ((previous.IsCubicBezier() && item.IsCubicBezierShorthand()) || (previous.IsQuadraticBezier() && item.IsQuadraticBezierShorthand())) { IList<float> previousCoordinates = result[result.Count - 1].Coordinates; float xPreviousControlPoint = previousCoordinates[previousCoordinates.Count - 4]; float yPreviousControlPoint = previousCoordinates[previousCoordinates.Count - 3]; //reflection if this point to the currentPoint float[] current = GetCurrentPoint(result); coordinates.Add(2 * current[0] - xPreviousControlPoint); coordinates.Add(2 * current[1] - yPreviousControlPoint); } } if (coordinates.Count == 0) { //add the currentPoint float[] current = GetCurrentPoint(result); coordinates.Add(current[0]); coordinates.Add(current[1]); } } for (int j = 0; j < size; j++) { //copy the rest of the coordinates if (item.IsRelative()) { float[] currentPoint = GetCurrentPoint(result); if (j % 2 == 0) { coordinates.Add(currentPoint[0] + (numbers[(i * size) + j])); } else { coordinates.Add(currentPoint[1] + (numbers[(i * size) + j])); } } else { coordinates.Add(numbers[(i * size) + j]); } } if (item.IsCubicBezier() || item.IsCubicBezierShorthand()) { result.Add(new PathItem(coordinates, PathItem.CUBIC_BEZIER)); } else { result.Add(new PathItem(coordinates, PathItem.QUADRATIC_BEZIER)); } } if (numbers.Count % size != 0) { throw new Exception("Something wrong with the number of coordinates in the path"); } }
private void GeneratePath(string objectName, PathItem currentItem, Dictionary <string, int> variableNamePostfixes) { var propertyName = currentItem.PropertyName; var typeFullName = currentItem.PropertyTypeFullName; var indentCount = 0; var variableName = ToVariableName(propertyName ?? typeFullName, variableNamePostfixes); var hasChildren = currentItem.NextItems.Values.Any(); if (propertyName == null) { WriteLine("var {0} = {1} as {2};", variableName, objectName, typeFullName); WriteLine("if ({0} != null)", variableName); WriteLine("{"); PushIndent(Tab); indentCount = 1; } else if (currentItem.IsList) { WriteLine("if ({0}.{1} != null)", objectName, propertyName); WriteLine("{"); PushIndent(Tab); indentCount = 1; if (currentItem.JsonPath != null) { WriteLine("// {0}", currentItem.JsonPath); WriteLine("{0}.{1} = {0}.{1}", objectName, propertyName); WriteLine(" .Select({0} => func({0}))", variableName); WriteLine(" .OfType<{0}>()", typeFullName); WriteLine(" .ToList();"); if (hasChildren) { WriteLine(""); } } if (hasChildren) { WriteLine("foreach (var {0} in {1}.{2}.OfType<{3}>())", variableName, objectName, propertyName, typeFullName); WriteLine("{"); PushIndent(Tab); indentCount = 2; } } else { if (currentItem.JsonPath != null) { WriteLine("// {0}", currentItem.JsonPath); WriteLine("{0}.{1} = func({0}.{1}) as {2};", objectName, propertyName, typeFullName); if (hasChildren) { WriteLine(""); } } if (hasChildren) { WriteLine("var {0} = {1}.{2} as {3};", variableName, objectName, propertyName, typeFullName); WriteLine("if ({0} != null)", variableName); WriteLine("{"); PushIndent(Tab); indentCount = 1; } } foreach (var item in currentItem.NextItems.Values) { GeneratePath(variableName, item, variableNamePostfixes); if (item != currentItem.NextItems.Values.Last()) { WriteLine(""); } } for (var i = 0; i < indentCount; ++i) { PopIndent(); WriteLine("}"); } }
private void TranslateForMoveAndLineTo(PathItem item, IList<PathItem> result) { IList<float> numbers = item.Coordinates; if (numbers.Count % 2 == 1) { numbers.Add(0f); } //for each pair for (int i = 0; i < (numbers.Count / 2); i++) { float x = numbers[i * 2]; float y = numbers[(i * 2) + 1]; if (item.IsRelative()) { float[] currentPoint = GetCurrentPoint(result); x = x + currentPoint[0]; y = y + currentPoint[1]; } IList<float> coordinates = new List<float>(); coordinates.Add(x); coordinates.Add(y); if (item.IsMoveTo() && i == 0) { result.Add(new PathItem(coordinates, PathItem.MOVE)); } else { result.Add(new PathItem(coordinates, PathItem.LINE)); } } }
private int Search(Type type, string[] path, int level, Stack <PathItem> result, PathItem pathRoot, string configKey) { if (level == path.Length) { MergePath(result, path, pathRoot, configKey); return(1); } var propertyName = GetPropertyNameAndType(path[level]).Item1; int foundCount = 0; // find the property with the same name from all public properties of current type var property = GetPublicProperties(type).FirstOrDefault(p => string.Equals(ToCamelCase(p.Name), propertyName, StringComparison.Ordinal)); if (property != null) { var propertyUnderlineType = GetPropertyUnderlineType(property.PropertyType); result.Push(new PathItem() { PropertyName = property.Name, PropertyTypeFullName = propertyUnderlineType.FullName, IsList = property.PropertyType.IsGenericType }); foundCount += Search(propertyUnderlineType, path, level + 1, result, pathRoot, configKey); result.Pop(); } // we have to search all derived types properties, because some of the properties may defined on the derived types. HashSet <Type> deriveds; if (BaseToDeriveds.TryGetValue(type, out deriveds)) { foreach (var derived in deriveds) { // find the property with the same name from the derived type property = derived.GetProperties().FirstOrDefault(p => string.Equals(ToCamelCase(p.Name), propertyName, StringComparison.Ordinal)); if (property != null) { var match = level == 0; if (level > 0) { var typeName = GetPropertyNameAndType(path[level - 1]).Item2; match |= typeName == null || derived.FullName.EndsWith(typeName, StringComparison.Ordinal); } if (match) { var propertyUnderlineType = GetPropertyUnderlineType(property.PropertyType); result.Push(new PathItem() { PropertyTypeFullName = derived.FullName }); result.Push(new PathItem() { PropertyName = property.Name, PropertyTypeFullName = propertyUnderlineType.FullName, IsList = property.PropertyType.IsGenericType }); foundCount += Search(propertyUnderlineType, path, level + 1, result, pathRoot, configKey); result.Pop(); result.Pop(); } } } } return(foundCount); }
private void AddVerb( SwaggerDocument doc, string verb, string filename, string fullFilename) { // Figuring out which key to use, and making sure we put an item into dictionary for URL. var itemType = filename.Substring(0, filename.IndexOf("."));; var key = "/api/hl" + itemType; if (!doc.Paths.ContainsKey(key)) { var p = new PathItem(); doc.Paths[key] = p; } // Retrieving existing item from path. var item = doc.Paths[key]; // Creating our operation item. var tag = filename.Substring(0, filename.IndexOf(".")).Trim('/'); var operation = new Operation { Tags = new List <string> { tag }, }; // Figuring out the type of operation this is. switch (verb) { case "get": operation.Produces = new List <string> { "application/json" }; operation.Description = $"Returns '{itemType}' from the server"; item.Get = operation; break; case "delete": operation.Produces = new List <string> { "application/json" }; operation.Description = $"Deletes '{itemType}' from the server"; item.Delete = operation; break; case "put": operation.Consumes = new List <string> { "application/json" }; operation.Produces = new List <string> { "application/json" }; operation.Description = $"Updates an existing '{itemType}' on the server"; item.Put = operation; break; case "post": operation.Consumes = new List <string> { "application/json" }; operation.Produces = new List <string> { "application/json" }; operation.Description = $"Creates a new '{itemType}' on the server"; item.Post = operation; break; } }
/** constructor */ public AssetBundleItem(Fee.AssetBundleList.DummryAssetBundle a_assetbundle_dummy, PathItem a_pathitem) { //pathitem this.pathitem = a_pathitem; //assetbundle_raw this.assetbundle_raw = null; //assetbundle_dummy this.assetbundle_dummy = a_assetbundle_dummy; }
public static IEnumerable <(string method, Operation operation)> GetOperations(PathItem pathItem) { if (pathItem.Get != null) { yield return("get", pathItem.Get); } if (pathItem.Put != null) { yield return("put", pathItem.Put); } if (pathItem.Post != null) { yield return("post", pathItem.Post); } if (pathItem.Delete != null) { yield return("delete", pathItem.Delete); } if (pathItem.Options != null) { yield return("options", pathItem.Options); } if (pathItem.Head != null) { yield return("head", pathItem.Head); } if (pathItem.Patch != null) { yield return("patch", pathItem.Patch); } }
private void CreateNodeRecursive(NodeControl parent, PathItem path) { Node parentNode = parent.DataContext as Node; path.Source = parentNode; path.Target.ParentPath = path; NodeControl nodeControl = new NodeControl { DataContext = path.Target }; path.Target.CanvasLeft = parentNode.CanvasLeft + (parentNode.Type == path.Target.Type ? 400 : 200); if ((parentNode.CanvasLeft + 150) / 400 > max) { max++; DrawYearLine(max); } nodeControl.AddNewNode += NodeControl_AddNewNode; canvas.Children.Add(nodeControl); foreach (var p in path.Target.Paths) { CreateNodeRecursive(nodeControl, p); } PathControl pathControl = new PathControl { DataContext = path }; MultiBinding multiBinding = new MultiBinding(); multiBinding.Converter = converter; multiBinding.Bindings.Add(new Binding("(Canvas.Left)") { Source = parent }); multiBinding.Bindings.Add(new Binding("(Canvas.Top)") { Source = parent }); multiBinding.Bindings.Add(new Binding("(Canvas.Left)") { Source = nodeControl }); multiBinding.Bindings.Add(new Binding("(Canvas.Top)") { Source = nodeControl }); multiBinding.NotifyOnSourceUpdated = true; pathControl.SetBinding(PathControl.PositionsProperty, multiBinding); pathControl.MouseDown += (s, e) => { viewModel.Selected = ((FrameworkElement)s).DataContext; }; nodeControl.DeleteNode += (s, e) => { parentNode.Paths.Remove(path); canvas.Children.Remove(nodeControl); canvas.Children.Remove(pathControl); }; canvas.Children.Add(pathControl); CreateDragDrop(nodeControl); }
public static PathItem FakePathItem(Type messageType) { var lastChar = ' '; var tag = messageType.Name .Reverse() .TakeWhile(chr => { var stop = char.IsUpper(lastChar); lastChar = chr; return(!stop); }) .Reverse() .ConcatToString(); var operation = new Operation() { Tags = new[] { messageType.Name }, OperationId = "Post", Consumes = new[] { "application/json-patch+json", "application/json", "text/json", "application/*+json", }.ToList(), Parameters = new List <IParameter>() { new BodyParameter() { Name = messageType.FullName, Schema = new Schema() { Ref = "#/definitions/Test2Command", }, } }, Produces = new[] { "application/json" }, Responses = new Dictionary <string, Response>() { { "200", new Response() { Description = "Success", } }, }, }; var pathItem = new PathItem(); switch (tag) { case "Query": pathItem.Get = operation; break; //case "Command": default: pathItem.Post = operation; break; } return(pathItem); }
private void CreateChildNode(NodeControl parent, NodeType type) { Node parentNode = parent.DataContext as Node; Node node = new Node { Type = type }; NodeControl nodeControl = new NodeControl { DataContext = node }; nodeControl.AddNewNode += NodeControl_AddNewNode; node.CanvasLeft = Canvas.GetLeft(parent) + (node.Type == parentNode.Type ? 400 : 200); node.CanvasTop = Canvas.GetTop(parent); if ((node.CanvasLeft + 150) / 400 > max) { max++; DrawYearLine(max); } PathItem path = new PathItem(parentNode, node) { Type = parentNode.Type }; PathControl pathControl = new PathControl { DataContext = path }; MultiBinding multiBinding = new MultiBinding(); multiBinding.Converter = converter; multiBinding.Bindings.Add(new Binding("(Canvas.Left)") { Source = parent }); multiBinding.Bindings.Add(new Binding("(Canvas.Top)") { Source = parent }); multiBinding.Bindings.Add(new Binding("(Canvas.Left)") { Source = nodeControl }); multiBinding.Bindings.Add(new Binding("(Canvas.Top)") { Source = nodeControl }); multiBinding.NotifyOnSourceUpdated = true; pathControl.SetBinding(PathControl.PositionsProperty, multiBinding); pathControl.MouseDown += (s, e) => { viewModel.Selected = ((FrameworkElement)s).DataContext; }; nodeControl.DeleteNode += (s, e) => { parentNode.Paths.Remove(path); canvas.Children.Remove(nodeControl); canvas.Children.Remove(pathControl); }; canvas.Children.Add(nodeControl); canvas.Children.Add(pathControl); CreateDragDrop(nodeControl); }
public void AddODataOtherApi(string prefix, List <EdmEntitySet> containers, List <ControllerActionDescriptor> controllers, Dictionary <string, PathItem> result, ISchemaRegistry schemaRegistry) { foreach (var item in controllers) { var method = item.MethodInfo.GetCustomAttribute <HttpMethodAttribute>(); var paramters = item.Parameters; Operation operation = new Operation() { OperationId = $"{item.Id}", Tags = new List <string>() { item.ControllerName }, Parameters = item.Parameters.Select(x => CreateParamters((ControllerParameterDescriptor)x, schemaRegistry)).ToList(), Responses = CreateResponse(item, schemaRegistry) }; if (item.MethodInfo.CustomAttributes.Any(x => x.AttributeType.Name == "EnableQueryAttribute")) { AddQueryOptionParametersForEntitySet(operation.Parameters); } var controller = containers.FirstOrDefault(x => x.Name == item.ControllerName); if (controller == null) { continue; } var keyType = EdmCoreModel.Instance.GetPrimitiveType(controller.EntityType().DeclaredKey.First().Type.PrimitiveKind()); var isKey = paramters.FirstOrDefault(x => x.ParameterType.Name == keyType.Name); var path = $"/{prefix}/{item.ControllerName}"; if (isKey != null) { path += $"({ConvertODataParamterName(isKey.Name, IsStringParamter(keyType.Name))})"; } bool isProperty = controller.EntityType().Properties().Any(x => string.Equals($"get{x.Name}", item.ActionName, StringComparison.OrdinalIgnoreCase)); if (paramters.Count > 0 && isKey != null && isProperty) { path += $"/{item.ActionName.Substring(3)}"; } paramters = paramters.Where(x => x.BindingInfo == null || x.BindingInfo.BindingSource != BindingSource.Header && x.BindingInfo.BindingSource != BindingSource.Body).ToList(); if (paramters.Count > 0) { List <string> paraterms = new List <string>(); foreach (ControllerParameterDescriptor ps in paramters) { var isbosy = method != null && method.HttpMethods.Any(x => postMethod.Contains(x.ToLower())); var isQuery = ps.BindingInfo != null && ps.BindingInfo.BindingSource == BindingSource.Query; if (ps != isKey && isbosy == false && isQuery == false) { paraterms.Add($"{ps.Name}={ConvertODataParamterName(ps.Name, IsStringParamter(ps.ParameterType))}"); } } if (paraterms.Count > 0) { path += "(" + string.Join(",", paraterms) + ")"; } } if (result.TryGetValue(path, out PathItem pathItem) == false) { result.Add(path, pathItem = new PathItem()); } SettingMethod(pathItem, method, operation); OperationFilterContext operationFilterContext = new OperationFilterContext(new Microsoft.AspNetCore.Mvc.ApiExplorer.ApiDescription() { ActionDescriptor = item }, schemaRegistry, item.MethodInfo); ApplyFilters(operation, operationFilterContext); } }
internal List <SDL.SDL_Rect> GetSDLRects() { PathItem ctl = new PathItem(), ctr = new PathItem(), cbl = new PathItem(), cbr = new PathItem(); List <SDL.SDL_Rect> rects = new List <SDL.SDL_Rect>(); for (int i = 1; i < pathItems.Count; i++) { var pi0 = pathItems[i - 1]; var pi1 = pathItems[i]; if (pi1.arc) { rects.AddRange(GetArcSDLRects(pi1)); switch (pi1.corner) { case RGraphicsPath.Corner.TopLeft: ctl = pi1; break; case RGraphicsPath.Corner.TopRight: ctr = pi1; break; case RGraphicsPath.Corner.BottomLeft: cbl = pi1; break; case RGraphicsPath.Corner.BottomRight: cbr = pi1; break; } } } int xl = ctl.arc_cx >= cbl.arc_cx ? ctl.arc_cx : cbl.arc_cx; int xr = ctr.arc_cx <= cbr.arc_cx ? ctr.arc_cx : cbr.arc_cx; int yt = ctl.arc_y; int yb = cbl.arc_y + cbl.arc_r; rects.Add(new SDL.SDL_Rect { x = xl, y = yt, w = xr - xl, h = yb - yt }); if (ctl.arc_r == cbl.arc_r) { rects.Add(new SDL.SDL_Rect { x = ctl.arc_x, y = ctl.arc_cy, w = ctl.arc_r, h = cbl.arc_cy - ctl.arc_cy }); } else { if (ctl.arc_r < cbl.arc_r) { rects.Add(new SDL.SDL_Rect { x = ctl.arc_x, y = ctl.arc_cy, w = ctl.arc_r, h = cbl.arc_cy - ctl.arc_cy }); rects.Add(new SDL.SDL_Rect { x = ctl.arc_cx, y = ctl.arc_y, w = cbl.arc_r - ctl.arc_r, h = cbl.arc_cy - ctl.arc_y }); } else { rects.Add(new SDL.SDL_Rect { x = ctl.arc_x, y = ctl.arc_cy, w = cbl.arc_r, h = cbl.arc_cy - ctl.arc_cy }); rects.Add(new SDL.SDL_Rect { x = cbl.arc_cx, y = ctl.arc_cy, w = ctl.arc_r - cbl.arc_r, h = cbl.arc_cy - ctl.arc_cy + cbl.arc_r }); } } if (ctr.arc_r == cbr.arc_r) { rects.Add(new SDL.SDL_Rect { x = ctr.arc_x, y = ctr.arc_cy, w = ctr.arc_r, h = cbr.arc_cy - ctr.arc_cy }); } else { if (ctr.arc_r < cbr.arc_r) { rects.Add(new SDL.SDL_Rect { x = cbr.arc_cx, y = ctr.arc_y, w = cbr.arc_r - ctr.arc_r, h = cbr.arc_cy - ctr.arc_y }); rects.Add(new SDL.SDL_Rect { x = ctr.arc_cx, y = ctr.arc_cy, w = ctr.arc_r, h = cbr.arc_cy - ctr.arc_cy }); } else { rects.Add(new SDL.SDL_Rect { x = ctr.arc_cx, y = ctr.arc_cy, w = ctr.arc_r - cbr.arc_r, h = cbr.arc_cy - ctr.arc_cy + cbr.arc_r }); rects.Add(new SDL.SDL_Rect { x = cbr.arc_x, y = ctr.arc_cy, w = cbr.arc_r, h = cbr.arc_cy - ctr.arc_cy }); } } return(rects); }
private PathItem CreatePathItem( IEnumerable <ApiDescription> apiDescriptions, ISchemaRegistry schemaRegistry) { var pathItem = new PathItem(); // Group further by http method var perMethodGrouping = apiDescriptions .GroupBy(apiDesc => apiDesc.HttpMethod); foreach (var group in perMethodGrouping) { var httpMethod = group.Key; if (httpMethod == null) { throw new NotSupportedException(string.Format( "Ambiguous HTTP method for action - {0}. " + "Actions require an explicit HttpMethod binding for Swagger 2.0", group.First().ActionDescriptor.DisplayName)); } if (group.Count() > 1 && _options.ConflictingActionsResolver == null) { throw new NotSupportedException(string.Format( "HTTP method \"{0}\" & path \"{1}\" overloaded by actions - {2}. " + "Actions require unique method/path combination for Swagger 2.0. Use ConflictingActionsResolver as a workaround", httpMethod, group.First().RelativePathSansQueryString(), string.Join(",", group.Select(apiDesc => apiDesc.ActionDescriptor.DisplayName)))); } var apiDescription = (group.Count() > 1) ? _options.ConflictingActionsResolver(group) : group.Single(); switch (httpMethod) { case "GET": pathItem.Get = CreateOperation(apiDescription, schemaRegistry); break; case "PUT": pathItem.Put = CreateOperation(apiDescription, schemaRegistry); break; case "POST": pathItem.Post = CreateOperation(apiDescription, schemaRegistry); break; case "DELETE": pathItem.Delete = CreateOperation(apiDescription, schemaRegistry); break; case "OPTIONS": pathItem.Options = CreateOperation(apiDescription, schemaRegistry); break; case "HEAD": pathItem.Head = CreateOperation(apiDescription, schemaRegistry); break; case "PATCH": pathItem.Patch = CreateOperation(apiDescription, schemaRegistry); break; } } return(pathItem); }
private PathItem CreatePathItem(Utils.TypeDescription typeDescription, string idParam = null) { var pathItem = new PathItem { Parameters = null }; var readPrivilege = (new List <string> { "read" }).AsEnumerable(); var readSecurityRequirement = new Dictionary <SecuritySchemes, IEnumerable <string> > { { SecuritySchemes.Oauth2, readPrivilege } }; var readWritePrivilege = (new List <string> { "read", "write" }).AsEnumerable(); var readWriteSecurityRequirement = new Dictionary <SecuritySchemes, IEnumerable <string> > { { SecuritySchemes.Oauth2, readWritePrivilege } }; var getParameter = new Parameter { In = ParameterIn.Body, Required = true, Ref = $"#/definitions/{typeDescription.CSharpName}" }; var getParameters = new List <Parameter> { getParameter }; pathItem.Get = new Operation { Produces = acceptedFormats, Consumes = acceptedFormats, Description = $"Retrieves all {typeDescription.CSharpName}s.", OperationId = $"get{typeDescription.CSharpName}" + ((idParam != null) ? "ById" : ""), SecurityRequirements = (IDictionary <SecuritySchemes, IEnumerable <string> >)readSecurityRequirement, Parameters = CreateGetParameters(typeDescription, idParam != null), Responses = CreateResponsesFor(new List <string> { "200", "303", "401", "404", "500" }, typeDescription.CSharpName) }; /* * pathItem.Post = new Operation * { * Produces = acceptedFormats, * Consumes = acceptedFormats, * Description = $"Creates a {typeDescription.Name}.", * OperationId = $"add{typeDescription.Name}", * SecurityRequirements = (IDictionary<SecuritySchemes, IEnumerable<string>>)readWriteSecurityRequirement, * Parameters = new List<Parameter> { * new Parameter * { * In = ParameterIn.Body, * Required = true, * Ref = $"#/definitions/{typeDescription.Name}" * } }, * Responses = CreateResponsesFor(new List<string> { "200", "201", "303", "401", "404", "500" }, typeDescription.Name) * }; * * if (idParam == null) * { * pathItem.Put = new Operation * { * Produces = acceptedFormats, * Consumes = acceptedFormats, * Description = $"Update an existing {typeDescription.Name}.", * OperationId = $"update{typeDescription.Name}", * Responses = pathItem.Get.Responses, * }; * } * else * { * pathItem.Delete = pathItem.Post; * pathItem.Delete.Description = $"Delete an existing {typeDescription.Name}."; * pathItem.Delete.OperationId = $"delete{typeDescription.Name}"; * } */ return(pathItem); }
ItemEditor convertPathItem( PathItem old ) { var editor = (ItemEditor)Activator.CreateInstance(getType(@"Oglr.Plugins.PathItemEditor, Oglr.Plugins")); var @new = (PathItemProperties) editor.ItemProperties ; copyPropertiesFromOldToNew( old,@new ); @new.LocalPoints = old.LocalPoints.ToList( ) ; @new.WorldPoints = old.WorldPoints.ToList( ) ; @new.IsPolygon = old.IsPolygon ; @new.LineWidth = old.LineWidth ; @new.LineColor = old.LineColor ; return editor ; }
public static PathItem CreatePathItem(string path, global::System.DateTime updated) { PathItem pathItem = new PathItem(); pathItem.Path = path; pathItem.Updated = updated; return pathItem; }