text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DemirbasTakipWpfUI.Entities { public class Allocation { public int Id { get; set; } public int ProductId { get; set; } public int PersonelId { get; set; } public int IslemId { get; set; } public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } public Boolean Status { get; set; } public string Description { get; set; } } }
using System; using Plus.HabboHotel.GameClients; using Plus.HabboHotel.Groups; using Plus.HabboHotel.Users; namespace Plus.Communication.Packets.Outgoing.Groups { internal class GroupInfoComposer : MessageComposer { public Group Group { get; } public bool NewWindow { get; } public Habbo Habbo { get; } public DateTime Origin { get; } public GroupInfoComposer(Group group, GameClient session, bool newWindow = false) : base(ServerPacketHeader.GroupInfoMessageComposer) { DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(group.CreateTime); Group = group; NewWindow = newWindow; Habbo = session.GetHabbo(); } public override void Compose(ServerPacket packet) { packet.WriteInteger(Group.Id); packet.WriteBoolean(true); packet.WriteInteger(Group.Type == GroupType.Open ? 0 : Group.Type == GroupType.Locked ? 1 : 2); packet.WriteString(Group.Name); packet.WriteString(Group.Description); packet.WriteString(Group.Badge); packet.WriteInteger(Group.RoomId); packet.WriteString(Group.GetRoom() != null ? Group.GetRoom().Name : "No room found.."); // room name packet.WriteInteger(Group.CreatorId == Habbo.Id ? 3 : Group.HasRequest(Habbo.Id) ? 2 : Group.IsMember(Habbo.Id) ? 1 : 0); packet.WriteInteger(Group.MemberCount); // Members packet.WriteBoolean(false); //?? CHANGED packet.WriteString(Origin.Day + "-" + Origin.Month + "-" + Origin.Year); packet.WriteBoolean(Group.CreatorId == Habbo.Id); packet.WriteBoolean(Group.IsAdmin(Habbo.Id)); // admin packet.WriteString(PlusEnvironment.GetUsernameById(Group.CreatorId)); packet.WriteBoolean(NewWindow); // Show group info packet.WriteBoolean(Group.AdminOnlyDeco == 0); // Any user can place furni in home room packet.WriteInteger(Group.CreatorId == Habbo.Id ? Group.RequestCount : Group.IsAdmin(Habbo.Id) ? Group.RequestCount : Group.IsMember(Habbo.Id) ? 0 : 0); // Pending users //base.WriteInteger(0);//what the fuck packet.WriteBoolean(Group != null ? Group.ForumEnabled : true); //HabboTalk. } } }
using System; using System.IO.Compression; using System.Web; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace ZiZhuJY.Web.UI { // 注意: 有关启用 IIS6 或 IIS7 经典模式的说明, // 请访问 http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : HttpApplication { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); } public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.ico(/.*)?" }); //routes.Add(new FunctionGrapherRoute(string.Empty, new MvcRouteHandler())); routes.MapRoute( "Localization", // 路由名称 "{culture}/{controller}/{action}/{id}", // 带有参数的 URL new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // 参数默认值 new { culture = @"\w{2}(?:-\w{2})?" } ); routes.MapRoute( "Default", // 路由名称 "{controller}/{action}/{id}", // 带有参数的 URL new { controller = "Home", action = "Index", id = UrlParameter.Optional } // 参数默认值 ); } protected void Application_Error(object sender, EventArgs e) { // Remove any special filtering especially GZip filtering // Better solution is in the Application_PreSendRequestHeaders() //Response.Filter = null; //ZiZhuJY.Helpers.Log.StartTraceListners("zizhujy"); //Exception ex = Server.GetLastError(); //ZiZhuJY.Helpers.Log.Error(ZiZhuJY.Helpers.ExceptionHelper.CentralProcess(ex)); //Server.ClearError(); } protected void Application_PreSendRequestHeaders() { if (HttpContext.Current != null) { // ensure that if GZip/Deflate Encoding is applied that headers are set // also works when error occurs if filters are still active HttpResponse response = HttpContext.Current.Response; if (response.Filter is GZipStream && response.Headers["Content-encoding"] != "gzip") response.AppendHeader("Content-encoding", "gzip"); else if (response.Filter is DeflateStream && response.Headers["Content-encoding"] != "deflate") response.AppendHeader("Content-encoding", "deflate"); } } protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } protected void Application_BeginRequest(object source, EventArgs e) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ArxOne.MrAdvice.Advice; namespace FodyExample3 { class Program { static void Main(string[] args) { ExampleClass exampleClass = new ExampleClass(); exampleClass.QuicklyDoSomething(); exampleClass.SlowlyDoSomething(5); //Console.ReadKey(); } } public class ExampleAdvice : Attribute, IMethodAdvice { public void Advise(MethodAdviceContext context) { //Console.WriteLine("Before method call " + context.TargetMethod); //if (context.Parameters.Count > 0) //{ // Console.WriteLine(" parameter " + context.Parameters[0] + " will be modified"); // context.Parameters[0] = 7; //} context.Proceed(); //Console.WriteLine("after method call " + context.TargetMethod); } } public class ExampleClass { [ExampleAdvice] public void SlowlyDoSomething(int a) { Console.WriteLine("received argument " + a); Task.WaitAll(Task.Delay(3000)); } [ExampleAdvice] public void QuicklyDoSomething() { Task.WaitAll((Task.Delay(500))); } } }
using Microsoft.EntityFrameworkCore; using ShopApp.DataAccess.Abstract; using ShopApp.Entities; using System; using System.Collections.Generic; using System.Linq; namespace ShopApp.DataAccess.Concrete.EfCore { public class EfCoreProductDal : EfCoreGenericRepository<Product, ShopContext>, IProductDal { public Product GetByIdWithCategories(int id) { using (var context = new ShopContext()) { return context.Products .Where(i => i.Id == id) .Include(i => i.ProductCategories) .ThenInclude(i => i.Category) .Include(i => i.ProductBrands) .ThenInclude(i => i.Brand) .FirstOrDefault(); } } public int GetCountByBrand(string brand) { using (var context = new ShopContext()) { var products = context.Products.AsQueryable(); //AsQueryable-->list denmediği sürece sorguyu değiştirebiliyorsunuz //ekstradan where,order by sorgusu gibi ekstra kriter eklenebilir if (!string.IsNullOrEmpty(brand)) { products = products .Include(i => i.ProductBrands) .ThenInclude(i => i.Brand) .Where(i => i.ProductBrands.Any(a => a.Brand.Name.ToLower() == brand.ToLower())); } return products.Count(); } } public int GetCountByCategory(string category) { using (var context = new ShopContext()) { var products = context.Products.AsQueryable(); //AsQueryable-->list denmediği sürece sorguyu değiştirebiliyorsunuz //ekstradan where,order by sorgusu gibi ekstra kriter eklenebilir if (!string.IsNullOrEmpty(category)) { products = products .Include(i => i.ProductCategories) .ThenInclude(i => i.Category) .Where(i => i.ProductCategories.Any(a => a.Category.Name.ToLower() == category.ToLower())); } return products.Count(); } } public Product GetProductDetails(int id) { using (var context = new ShopContext()) { return context.Products .Where(i => i.Id == id) .Include(i => i.ProductCategories) .ThenInclude(i => i.Category) .Include(i => i.ProductBrands) .ThenInclude(i => i.Brand) .FirstOrDefault(); } } public List<Product> GetProductsByBrand(string brand, int page, int pageSize) { using (var context = new ShopContext()) { var products = context.Products.AsQueryable(); //AsQueryable-->list denmediği sürece sorguyu değiştirebiliyorsunuz //ekstradan where,order by sorgusu gibi ekstra kriter eklenebilir if (!string.IsNullOrEmpty(brand)) { products = products .Include(i => i.ProductBrands) .ThenInclude(i => i.Brand) .Where(i => i.ProductBrands.Any(a => a.Brand.Name.ToLower() == brand.ToLower())); } return products.Skip((page - 1) * pageSize).Take(pageSize).ToList();//Skip Ötele , Take al } } public List<Product> GetProductsByCategory(string category, int page, int pageSize) { using (var context = new ShopContext()) { var products = context.Products.AsQueryable(); //AsQueryable-->list denmediği sürece sorguyu değiştirebiliyorsunuz //ekstradan where,order by sorgusu gibi ekstra kriter eklenebilir if (!string.IsNullOrEmpty(category)) { products = products .Include(i => i.ProductCategories) .ThenInclude(i => i.Category) .Where(i => i.ProductCategories.Any(a => a.Category.Name.ToLower() == category.ToLower())); } return products.Skip((page - 1) * pageSize).Take(pageSize).ToList();//Skip Ötele , Take al } } public bool Create(Product entity, int[] categoryIds, int brandId) { using (var context = new ShopContext()) { ProductBrand productBrand = new ProductBrand(); productBrand.BrandId = brandId; productBrand.ProductId = entity.Id; productBrand.Product = entity; context.Set<ProductBrand>().Add(productBrand); context.Set<Product>().Add(entity); context.SaveChanges(); return true; } } public void Update(Product entity, int[] categoryIds, int brandId) { using (var context = new ShopContext()) { var product = context.Products .Include(i => i.ProductCategories) .Include(i => i.ProductBrands) .FirstOrDefault(i => i.Id == entity.Id); if (product != null) { product.Name = entity.Name; product.Description = entity.Description; product.ImageUrl = entity.ImageUrl; product.Price = entity.Price; product.Material = entity.Material; product.Model = entity.Model; product.SequenceMeter = entity.SequenceMeter; product.Dimensions = entity.Dimensions; product.WarrantyPeriod = entity.WarrantyPeriod; product.ProductCategories = categoryIds.Select(catid => new ProductCategory() { CategoryId = catid, ProductId = entity.Id }).ToList(); product.ProductBrands = product.ProductBrands.Where(x => x.ProductId == product.Id).Select(b => new ProductBrand() { BrandId = brandId, ProductId = entity.Id }).ToList(); context.SaveChanges(); } } } } }
using DbUp; using System; using System.Configuration; using System.Reflection; namespace ExamWork.DataAcces { public class Migration { private readonly string _connectionString; public Migration() { _connectionString = ConfigurationManager.ConnectionStrings["ExamApp"].ConnectionString; } public void CheckMigrations() { EnsureDatabase.For.SqlDatabase(_connectionString); var upgrader = DeployChanges.To .SqlDatabase(_connectionString) .WithScriptsEmbeddedInAssembly(Assembly.GetExecutingAssembly()) .LogToConsole() .Build(); var result = upgrader.PerformUpgrade(); if (!result.Successful) { throw new Exception("Ошибка в базе данных"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GuapiGraph { class PositionInfo { public string Name { get; set; }//岗位名称 List<MonthData> monthDataList { get; set; }//月份信息列表 public PositionInfo(string postionName, List<MonthData> monthDatas) { this.Name = postionName; this.monthDataList = monthDatas; } public List<string> getMonths() { List<string> list = new List<string>(); foreach (MonthData mData in monthDataList) list.Add(mData.monthName); return list; } public List<int> getCounts() { List<int> list = new List<int>(); foreach (MonthData mData in monthDataList) list.Add(mData.positionCount); return list; } /* * 例如针对“前端”这一岗位, * 2017年11月有122份岗位,2017年12月有143份岗位, * 那么Name = "前端", * monthDataList里第一项monthName = "2017-11", positionCount = 122 * monthDataList里第二项monthName = "2017-12", positionCount = 143 */ } public class MonthData { public string monthName { get; set; }//2017-12 public int positionCount { get; set; }//2017年12月该position职位个数 } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SmallHouseManagerModel { public class RoomModel { /// <summary> /// 房间编号 /// </summary> public string Code { get; set; } /// <summary> /// 房间号 /// </summary> public string RoomID { get; set; } /// <summary> /// 楼宇号 /// </summary> public string PaID { get; set; } /// <summary> /// 楼宇名 /// </summary> public string PaName { get; set; } /// <summary> /// 单元号 /// </summary> public int CellID { get; set; } /// <summary> /// 单元名 /// </summary> public string CellName { get; set; } /// <summary> /// 朝向号 /// </summary> public int SunnyID { get; set; } /// <summary> /// 朝向名 /// </summary> public string SunnyName { get; set; } /// <summary> /// 装修标准号 /// </summary> public int IndoorID { get; set; } /// <summary> /// 装修标准名 /// </summary> public string IndoorName { get; set; } /// <summary> /// 房间功能号 /// </summary> public int RoomUseID { get; set; } /// <summary> /// 房间功能名 /// </summary> public string RoomUseName { get; set; } /// <summary> /// 房间规格号 /// </summary> public int RoomFormatID { get; set; } /// <summary> /// 房间规格名 /// </summary> public string RoomFormatName { get; set; } /// <summary> /// 房间面积 /// </summary> public double BuildArea { get; set; } /// <summary> /// 可用面积 /// </summary> public double UseArea { get; set; } /// <summary> /// 出售状态 /// </summary> public int State { get; set; } } }
using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using System.Net; using System.Text; using System.Text.RegularExpressions; namespace SimpleCrawler { public class HttpRequestProvider : IHtmlProvider { public event AddUrlEventHandler AddUrlEvent; public event CrawlErrorEventHandler CrawlErrorEvent; public event DataReceivedEventHandler DataReceivedEvent; public void DealHtml(UrlInfo urlInfo, CrawlSettings settings, CookieContainer cookieContainer) { HttpWebRequest request = null; HttpWebResponse response = null; try { if (urlInfo==null) { return ; } // 创建并配置Web请求 request = WebRequest.Create(urlInfo.UrlString) as HttpWebRequest; this.ConfigRequest(request, settings, cookieContainer); if (request != null) { response = request.GetResponse() as HttpWebResponse; } if (response != null) { PersistenceCookie(response, settings, cookieContainer); Stream stream = null; // 如果页面压缩,则解压数据流 if (response.ContentEncoding == "gzip") { Stream responseStream = response.GetResponseStream(); if (responseStream != null) { stream = new GZipStream(responseStream, CompressionMode.Decompress); } } else { stream = response.GetResponseStream(); } using (stream) { string html = this.ParseContent(stream, response.CharacterSet); ParseLinks(urlInfo, html,settings); if (this.DataReceivedEvent != null) { this.DataReceivedEvent( new DataReceivedEventArgs { Url = urlInfo.UrlString, Depth = urlInfo.Depth, Html = html }); } if (stream != null) { stream.Close(); } } } } catch (Exception exception) { if (this.CrawlErrorEvent != null) { if (urlInfo != null) { this.CrawlErrorEvent( new CrawlErrorEventArgs { Url = urlInfo.UrlString, Exception = exception }); } } } finally { if (request != null) { request.Abort(); } if (response != null) { response.Close(); } } } private void ConfigRequest(HttpWebRequest request, CrawlSettings settings, CookieContainer cookieContainer) { request.UserAgent = settings.UserAgent; request.CookieContainer = cookieContainer; request.AllowAutoRedirect = true; request.MediaType = "text/html"; request.Headers["Accept-Language"] = "zh-CN,zh;q=0.8"; if (settings.Timeout > 0) { request.Timeout = settings.Timeout; } } /// <summary> /// The persistence cookie. /// </summary> /// <param name="response"> /// The response. /// </param> private void PersistenceCookie(HttpWebResponse response, CrawlSettings settings, CookieContainer cookieContainer) { if (settings.KeepCookie) { return; } string cookies = response.Headers["Set-Cookie"]; if (!string.IsNullOrEmpty(cookies)) { var cookieUri = new Uri( string.Format( "{0}://{1}:{2}/", response.ResponseUri.Scheme, response.ResponseUri.Host, response.ResponseUri.Port)); cookieContainer.SetCookies(cookieUri, cookies); } } private string ParseContent(Stream stream, string characterSet) { var memoryStream = new MemoryStream(); stream.CopyTo(memoryStream); byte[] buffer = memoryStream.ToArray(); Encoding encode = Encoding.ASCII; string html = encode.GetString(buffer); string localCharacterSet = characterSet; Match match = Regex.Match(html, "<meta([^<]*)charset=([^<]*)\"", RegexOptions.IgnoreCase); if (match.Success) { localCharacterSet = match.Groups[2].Value; var stringBuilder = new StringBuilder(); foreach (char item in localCharacterSet) { if (item == ' ') { break; } if (item != '\"') { stringBuilder.Append(item); } } localCharacterSet = stringBuilder.ToString(); } if (string.IsNullOrEmpty(localCharacterSet)) { localCharacterSet = characterSet; } if (!string.IsNullOrEmpty(localCharacterSet)) { encode = Encoding.GetEncoding(localCharacterSet); } memoryStream.Close(); return encode.GetString(buffer); } private void ParseLinks(UrlInfo urlInfo, string html, CrawlSettings settings) { if (settings.Depth > 0 && urlInfo.Depth >= settings.Depth) { return; } var urlDictionary = new Dictionary<string, string>(); Match match = Regex.Match(html, "(?i)<a .*?href=\"([^\"]+)\"[^>]*>(.*?)</a>"); while (match.Success) { // 以 href 作为 key string urlKey = match.Groups[1].Value; // 以 text 作为 value string urlValue = Regex.Replace(match.Groups[2].Value, "(?i)<.*?>", string.Empty); urlDictionary[urlKey] = urlValue; match = match.NextMatch(); } foreach (var item in urlDictionary) { string href = item.Key; string text = item.Value; if (!string.IsNullOrEmpty(href)) { bool canBeAdd = true; if (settings.EscapeLinks != null && settings.EscapeLinks.Count > 0) { if (settings.EscapeLinks.Any(suffix => href.EndsWith(suffix, StringComparison.OrdinalIgnoreCase))) { canBeAdd = false; } } if (settings.HrefKeywords != null && settings.HrefKeywords.Count > 0) { if (!settings.HrefKeywords.Any(href.Contains)) { canBeAdd = false; } } if (canBeAdd) { string url = href.Replace("%3f", "?") .Replace("%3d", "=") .Replace("%2f", "/") .Replace("&amp;", "&"); if (string.IsNullOrEmpty(url) || url.StartsWith("#") || url.StartsWith("mailto:", StringComparison.OrdinalIgnoreCase) || url.StartsWith("javascript:", StringComparison.OrdinalIgnoreCase)) { continue; } var baseUri = new Uri(urlInfo.UrlString); Uri currentUri = url.StartsWith("http", StringComparison.OrdinalIgnoreCase) ? new Uri(url) : new Uri(baseUri, url); url = currentUri.AbsoluteUri; if (settings.LockHost) { // 去除二级域名后,判断域名是否相等,相等则认为是同一个站点 // 例如:mail.pzcast.com 和 www.pzcast.com if (baseUri.Host.Split('.').Skip(1).Aggregate((a, b) => a + "." + b) != currentUri.Host.Split('.').Skip(1).Aggregate((a, b) => a + "." + b)) { continue; } } //非基础url的过滤 if (settings.LockBaseUrl) { if (!currentUri.AbsoluteUri.Contains(baseUri.AbsolutePath)) { continue; } } if (!IsMatchRegular(url,settings)) { continue; } var addUrlEventArgs = new AddUrlEventArgs { Title = text, Depth = urlInfo.Depth + 1, Url = url }; if (this.AddUrlEvent != null && !this.AddUrlEvent(addUrlEventArgs)) { continue; } UrlQueue.Instance.EnQueue(new UrlInfo(url) { Depth = urlInfo.Depth + 1 }); } } } } private bool IsMatchRegular(string url, CrawlSettings settings) { bool result = false; if (settings.RegularFilterExpressions != null && settings.RegularFilterExpressions.Count > 0) { if ( settings.RegularFilterExpressions.Any( pattern => Regex.IsMatch(url, pattern, RegexOptions.IgnoreCase))) { result = true; } } else { result = true; } return result; } } }
 namespace Arch.Data.Common.Enums { public enum MarkDownCategory { ErrorCount, ErrorPercent } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using ViewModel; namespace WpfView { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : ThemedWindow { public MainWindow() { InitializeComponent(); this.Loaded += (e, o) => { var viewModel = new MainWindowViewModel(); viewModel.ResultItemUpated += OnResultItemUpated; this.DataContext = viewModel; }; } private void OnResultItemUpated(object sender, ResultItemEventArgs e) { InputDataTextBox.Select(e.Index, e.Value.Length); DependencyObject focusScope = FocusManager.GetFocusScope(InputDataTextBox); FocusManager.SetFocusedElement(focusScope, InputDataTextBox); } } }
using Contoso.XPlatform.Flow.Settings.Screen; using Contoso.XPlatform.ViewModels.TextPage; using System; using Xamarin.Forms; namespace Contoso.XPlatform.Views.Factories { public class TextPageFactory : ITextPageFactory { private readonly Func<TextPageViewModel, TextPageViewCS> _getPage; private readonly Func<ScreenSettingsBase, TextPageViewModel> _getViewModel; public TextPageFactory( Func<TextPageViewModel, TextPageViewCS> getPage, Func<ScreenSettingsBase, TextPageViewModel> getViewModel) { _getPage = getPage; _getViewModel = getViewModel; } public Page CreatePage(ScreenSettingsBase screenSettings) => _getPage ( _getViewModel(screenSettings) ); } }
using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.AzureAD.UI; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Mvc; namespace Client.Web.OpenIdConnect.Controllers { public class AccountController : Controller { public IActionResult SignIn() { return Challenge(new AuthenticationProperties { RedirectUri = "/" }); } public IActionResult SignOut() { return SignOut(new AuthenticationProperties { RedirectUri = "/" }, CookieAuthenticationDefaults.AuthenticationScheme, AzureADDefaults.AuthenticationScheme); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _4._6MaxSequenceOfEqualElements { class Program { static void Main(string[] args) { int[] nums = Console.ReadLine().Split(' ').Select(int.Parse).ToArray(); int start = 0; int len = 1; int bestLen = 1; int bestStart = 1; for (int pos = 1; pos <= nums.Length - 1; pos++) { if (nums[pos] == nums[pos - 1]) { len++; if (len > bestLen) { bestLen = len; bestStart = start; } } else { start = pos; len = 1; } } for (int i =bestStart; i <bestStart+bestLen; i++) { Console.Write("{0} ",nums[i]); } } } }
using System; using System.Security.Claims; using System.Security.Principal; using WebVella.ERP.Api.Models; namespace WebVella.ERP.Web.Security { public class ErpIdentity : ClaimsIdentity { public override string AuthenticationType { get { return "WebVellaErp"; } } public override bool IsAuthenticated { get { return User != null && !String.IsNullOrWhiteSpace(User.Email); } } public ErpUser User { get; set; } } }
using System; using System.Linq; namespace _02.DiagonalDifference { class DiagonalDifference { static void Main(string[] args) { int countOfMatrix = int.Parse(Console.ReadLine()); int[][] matrix = new int[countOfMatrix][]; for (int i = 0; i < countOfMatrix; i++) { matrix[i] = Console.ReadLine().Split(new char[] { ' '}, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray(); } int[] primaryDiagonal = new int[countOfMatrix]; int[] secondaryDiagonal = new int[countOfMatrix]; for (int i = 0; i < countOfMatrix; i++) { primaryDiagonal[i] = matrix[i][i]; } for (int i = 0, j = countOfMatrix-1; i < countOfMatrix; i++, j--) { secondaryDiagonal[i] = matrix[i][j]; } Console.WriteLine(Math.Abs(primaryDiagonal.Sum() - secondaryDiagonal.Sum())); } } }
using Newtonsoft.Json; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace Jieshai { public class ObjectComparer { public ObjectComparer() { } public ObjectComparer(params PropertyInfo[] ignoreProerties) : this() { this.IgnoreProerties = new List<PropertyInfo>(); this.IgnoreProerties.AddRange(ignoreProerties); } public List<PropertyInfo> IgnoreProerties { set; get; } public bool OnlySamePropertyType { set; get; } public bool Compare(object obj1, object obj2) { return this.Compare(obj1, obj2, 1); } protected virtual bool Compare(object obj1, object obj2, int depth) { if (depth > 3 || obj1 == obj2) { return true; } if (obj1 == null || obj2 == null) { return false; } if (obj1 is IEnumerable) { return this.CompareEnumer(obj1 as IEnumerable, obj2 as IEnumerable); } else { Type obj1Type = obj1.GetType(); Type obj2Type = obj2.GetType(); PropertyInfo[] obj1Propertys = obj1Type.GetProperties(); foreach (PropertyInfo obj1Property in obj1Propertys) { if (this.IgnoreProerties != null && this.IgnoreProerties.Any(ip => ip.Name == obj1Property.Name)) { continue; } PropertyInfo obj2Property = obj2Type.GetProperty(obj1Property.Name); if (obj2Property == null) { continue; } if (this.OnlySamePropertyType && obj1Property.PropertyType != obj2Property.PropertyType) { continue; } object obj1Value = obj1Property.GetValue(obj1, null); object obj2Value = obj2Property.GetValue(obj2, null); if (ReflectionHelper.IsValueType(obj1Property.PropertyType)) { if (obj1Value == obj2Value) { continue; } if (obj1Value != null && obj1Value.Equals(obj2Value)) { continue; } if (JsonConvert.SerializeObject(obj1Value) == JsonConvert.SerializeObject(obj2Value)) { continue; } if (obj1Value != null && obj2Value != null && obj1Value.ToString() == obj2Value.ToString()) { continue; } throw new Exception(string.Format("{0} {1} 不相等, 期望值: {2}, 实际值: {3}", obj1Type.Name, obj1Property.Name, obj1Value, obj2Value)); } else { if (!this.Compare(obj1Value, obj2Value, depth + 1)) { throw new Exception(string.Format("{0} {1} 不相等, 期望值: {2}, 实际值: {3}", obj1Type.Name, obj1Property.Name, obj1Value, obj2Value)); } } } } return true; } private bool CompareEnumer(IEnumerable obj1, IEnumerable obj2) { if (obj1 == null || obj2 == null) { return false; } IEnumerator enumerator1 = obj1.GetEnumerator(); IEnumerator enumerator2 = obj2.GetEnumerator(); while (true) { bool enumerator1HasItem = enumerator1.MoveNext(); bool enumerator2HasItem = enumerator2.MoveNext(); if (enumerator1HasItem != enumerator2HasItem) { return false; } if (!enumerator1HasItem) { break; } if (!this.Compare(enumerator1.Current, enumerator2.Current, 1)) { return false; } } return true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace ERP_Palmeiras_LA.Models { public enum StatusEquipamento { FUNCIONANDO, QUEBRADO } public partial class StatusEquipamentoWrapper { private StatusEquipamento status; public int Value { get { return (int)status; } set { status = (StatusEquipamento)value; } } public StatusEquipamento EnumValue { get { return status; } set { status = value; } } public static implicit operator StatusEquipamentoWrapper(StatusEquipamento p) { return new StatusEquipamentoWrapper { EnumValue = p }; } public static implicit operator StatusEquipamento(StatusEquipamentoWrapper pw) { if (pw == null) return StatusEquipamento.FUNCIONANDO; else return pw.EnumValue; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Infra; namespace Console2.From_001_To_025 { public class _009_TreeTravelRelated { /// <summary> /// interative travel tree inorder. /// </summary> /// <param name="root"></param> /// <returns></returns> public string InorderTravel(TreeNode root) { StringBuilder sb = new StringBuilder(); Stack<TreeNode> s = new Stack<TreeNode>(); bool backTrack = false; s.Push(root); while (s.Count != 0) { TreeNode node = s.Peek(); if (!backTrack && node.LeftChild != null) { s.Push(node.LeftChild); continue; } node = s.Pop(); sb.Append(node.Value + ","); backTrack = true; if (node.RightChild != null) { s.Push(node.RightChild); backTrack = false; } } return sb.ToString(); } /// <summary> /// Postorder interative tree travel.. /// </summary> /// <param name="root"></param> /// <returns></returns> public string PostOrderTravel(TreeNode root) { StringBuilder sb = new StringBuilder(); Stack<TreeNode> s = new Stack<TreeNode>(); bool backTrack = false; TreeNode prev = null; s.Push(root); while (s.Count != 0) { TreeNode node = s.Peek(); if (!backTrack && node.LeftChild != null) { s.Push(node.LeftChild); continue; } if (backTrack && node.RightChild != null && prev != node.RightChild) { s.Push(node.RightChild); continue; } node = s.Pop(); prev = node; sb.Append(node.Value + ","); backTrack = true; } return sb.ToString(); } } }
using System.Globalization; using System.Windows; using BPiaoBao.AppServices.DataContracts.DomesticTicket; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Data; using BPiaoBao.Client.DomesticTicket.Model; using BPiaoBao.Common.Enums; using JoveZhao.Framework.Expand; using NPOI.SS.Formula.Functions; namespace BPiaoBao.Client.DomesticTicket.View.Converters { /// <summary> /// 把航班列表转换为字符串 /// </summary> public class SkywaysConverter : IValueConverter { /// <summary> /// 转换值。 /// </summary> /// <param name="value">绑定源生成的值。</param> /// <param name="targetType">绑定目标属性的类型。</param> /// <param name="parameter">要使用的转换器参数。</param> /// <param name="culture">要用在转换器中的区域性。</param> /// <returns> /// 转换后的值。如果该方法返回 null,则使用有效的 null 值。 /// </returns> /// <exception cref="System.NotImplementedException"></exception> public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value is IList<SkyWayDto>) { var list = value as IList<SkyWayDto>; StringBuilder sb = new StringBuilder(); foreach (var item in list) { if (parameter == null) sb.AppendFormat("{0} {1}-{2} {3},{4},", item.FlightNumber, item.FromCityCode, item.ToCityCode, item.StartDateTime.ToString("yyyy-MM-dd HH:mm"), item.Seat); else sb.AppendFormat("{0}-{1},", item.FromCity, item.ToCity); } if (sb.Length > 0) sb = sb.Remove(sb.Length - 1, 1); var result = sb.ToString(); return result; } if (value is IList<ResponseSkyWay>) { var list = value as IList<ResponseSkyWay>; StringBuilder sb = new StringBuilder(); foreach (var item in list) { if (parameter == null) sb.AppendFormat("{0} {1}-{2} {3},{4},", item.FlightNumber, item.FromCityCode, item.ToCityCode, item.StartDateTime.ToString("yyyy-MM-dd HH:mm"), item.Seat); else sb.AppendFormat("{0}-{1},", item.FromCity, item.ToCity); } if (sb.Length > 0) sb = sb.Remove(sb.Length - 1, 1); var result = sb.ToString(); return result; } return null; } /// <summary> /// 转换值。 /// </summary> /// <param name="value">绑定目标生成的值。</param> /// <param name="targetType">要转换到的类型。</param> /// <param name="parameter">要使用的转换器参数。</param> /// <param name="culture">要用在转换器中的区域性。</param> /// <returns> /// 转换后的值。如果该方法返回 null,则使用有效的 null 值。 /// </returns> /// <exception cref="System.NotImplementedException"></exception> public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } /// <summary> /// 支付方式 /// </summary> public class PayWayConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value == null) { return ""; } var payWay = (EnumPayMethod)value; return payWay.ToEnumDesc(); } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } /// <summary> /// 乘客转换 /// </summary> public class PassengersConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value is List<ResponsePassenger>) { var sb = new StringBuilder(); var passers = (IList<ResponsePassenger>)value; foreach (var p in passers) { sb.AppendFormat("{0},", p.PassengerName); } if (sb.Length > 0) { var str = sb.ToString().Substring(0, sb.Length - 1); return str; } } if (value is ResponseAfterSalePassenger) { var sb = new StringBuilder(); var passers = (IList<ResponseAfterSalePassenger>)value; foreach (var p in passers) { sb.AppendFormat("{0},", p.PassengerName); } if (sb.Length > 0) { var str = sb.ToString().Substring(0, sb.Length - 1); return str; } } return ""; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } /// <summary> /// 非也 /// </summary> public class NotBooleanConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value == null) return true; if (value is bool) return !(bool)value; if (value is FlightInfoModel) { var model = value as FlightInfoModel; if (model.DefaultSite.PolicySpecialType != EnumPolicySpecialType.DynamicSpecial) return true; return model.DefaultSite.IsGotSpecial && model.DefaultSite.IsReceivedSpecial; } if (value is Site) { var site = value as Site; if (site.PolicySpecialType != EnumPolicySpecialType.DynamicSpecial) return true; return site.IsGotSpecial && site.IsReceivedSpecial; } return false; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } /// <summary> /// 非显 /// </summary> public class NotBooleanToVisibilityConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value == null) return Visibility.Collapsed;//正常执行非显 if(value is bool) return (bool)value ? Visibility.Collapsed : Visibility.Visible; if (value is FlightInfoModel)//默认舱位舱位价 { var model = value as FlightInfoModel; if (model.DefaultSite.PolicySpecialType == EnumPolicySpecialType.Normal) return Visibility.Visible; return (model.DefaultSite.PolicySpecialType == EnumPolicySpecialType.DynamicSpecial && model.DefaultSite.IsGotSpecial && model.DefaultSite.IsReceivedSpecial) || (model.DefaultSite.PolicySpecialType != EnumPolicySpecialType.Normal && model.DefaultSite.PolicySpecialType != EnumPolicySpecialType.DynamicSpecial) ? Visibility.Visible : Visibility.Collapsed; } if (!(value is Site)) return Visibility.Visible; var site = value as Site;//更多舱位舱位价 if (site.PolicySpecialType == EnumPolicySpecialType.Normal) return Visibility.Visible; return (site.PolicySpecialType == EnumPolicySpecialType.DynamicSpecial && site.IsGotSpecial && site.IsReceivedSpecial) || (site.PolicySpecialType != EnumPolicySpecialType.Normal && site.PolicySpecialType != EnumPolicySpecialType.DynamicSpecial) ? Visibility.Visible : Visibility.Collapsed; #region Past Code //if (value is FlightInfoModel)//默认舱位舱位价 //{ // var model = value as FlightInfoModel; // if (model.DefaultSite.PolicySpecialType == EnumPolicySpecialType.Normal) return Visibility.Visible; // return (model.DefaultSite.PolicySpecialType == EnumPolicySpecialType.DynamicSpecial && model.DefaultSite.IsGotSpecial) // || (model.DefaultSite.PolicySpecialType != EnumPolicySpecialType.Normal && model.DefaultSite.PolicySpecialType != EnumPolicySpecialType.DynamicSpecial) // ? Visibility.Visible // : Visibility.Collapsed; //} //if (!(value is Site)) return Visibility.Visible; //var site = value as Site;//更多舱位舱位价 //if (site.PolicySpecialType == EnumPolicySpecialType.Normal) return Visibility.Visible; //return (site.PolicySpecialType == EnumPolicySpecialType.DynamicSpecial && site.IsGotSpecial) // || (site.PolicySpecialType != EnumPolicySpecialType.Normal && site.PolicySpecialType != EnumPolicySpecialType.DynamicSpecial) // ? Visibility.Visible // : Visibility.Collapsed; #endregion } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } /// <summary> /// 布尔值 特价转换为可见或隐藏 /// </summary> public class SpecialBooleanToVisibilityConverter : IValueConverter { #region IValueConverter 成员 /// <summary> /// 转换值。 /// </summary> /// <param name="value">绑定源生成的值。</param> /// <param name="targetType">绑定目标属性的类型。</param> /// <param name="parameter">要使用的转换器参数。</param> /// <param name="culture">要用在转换器中的区域性。</param> /// <returns>转换后的值。如果该方法返回 null,则使用有效的 null 值。</returns> public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value is bool) return (bool)value ? Visibility.Visible : Visibility.Collapsed; if (value is EnumPolicySpecialType) return (EnumPolicySpecialType)value == EnumPolicySpecialType.Normal ? Visibility.Collapsed : Visibility.Visible;//特价标识 if (parameter != null) { int param; int.TryParse(parameter.ToString(), out param); if (param != 0) return Visibility.Collapsed; if (value is FlightInfoModel)//无运价按钮 { var model = value as FlightInfoModel; if (model.DefaultSite.PolicySpecialType == EnumPolicySpecialType.Normal) return Visibility.Collapsed; var res = (model.DefaultSite.PolicySpecialType == EnumPolicySpecialType.DynamicSpecial && (model.DefaultSite.IsReceivedSpecial && model.DefaultSite.IsGotSpecial)) || (model.DefaultSite.PolicySpecialType == EnumPolicySpecialType.DynamicSpecial && !model.DefaultSite.IsGotSpecial) || (model.DefaultSite.PolicySpecialType != EnumPolicySpecialType.DynamicSpecial && model.DefaultSite.PolicySpecialType != EnumPolicySpecialType.Normal) ? Visibility.Collapsed : Visibility.Visible; return res; } if (!(value is Site)) return Visibility.Collapsed; var site = value as Site;//无运价按钮 if (site.PolicySpecialType == EnumPolicySpecialType.Normal) return Visibility.Collapsed; return (site.PolicySpecialType == EnumPolicySpecialType.DynamicSpecial && site.IsReceivedSpecial && site.IsGotSpecial) || (site.PolicySpecialType == EnumPolicySpecialType.DynamicSpecial && !site.IsGotSpecial) || (site.PolicySpecialType != EnumPolicySpecialType.DynamicSpecial && site.PolicySpecialType != EnumPolicySpecialType.Normal) ? Visibility.Collapsed : Visibility.Visible; } else { if (value is FlightInfoModel)//默认舱位特价按钮 { var model = value as FlightInfoModel; if (model.DefaultSite.PolicySpecialType == EnumPolicySpecialType.Normal) return Visibility.Collapsed; var res = (model.DefaultSite.PolicySpecialType == EnumPolicySpecialType.DynamicSpecial && !model.DefaultSite.IsGotSpecial) ? Visibility.Visible : Visibility.Collapsed; return res; } if (!(value is Site)) return Visibility.Collapsed; var site = value as Site;//更多舱位特价按钮 if (site.PolicySpecialType == EnumPolicySpecialType.Normal) return Visibility.Collapsed; return site.PolicySpecialType == EnumPolicySpecialType.DynamicSpecial && !site.IsGotSpecial ? Visibility.Visible : Visibility.Collapsed; } //if (value is FlightInfoModel)//默认舱位特价按钮 //{ // var model = value as FlightInfoModel; // if (model.DefaultSite.PolicySpecialType == EnumPolicySpecialType.Normal) return Visibility.Collapsed; // var res = model.DefaultSite.PolicySpecialType == EnumPolicySpecialType.DynamicSpecial && !model.IsGotSpecial // ? Visibility.Visible // : Visibility.Collapsed; // return res; //} //if (!(value is Site)) return Visibility.Collapsed; //var site = value as Site;//更多舱位特价按钮 //if (site.PolicySpecialType == EnumPolicySpecialType.Normal) return Visibility.Collapsed; //return site.PolicySpecialType == EnumPolicySpecialType.DynamicSpecial && !site.IsGotSpecial // ? Visibility.Visible // : Visibility.Collapsed; } /// <summary> /// 转换值。 /// </summary> /// <param name="value">绑定目标生成的值。</param> /// <param name="targetType">要转换到的类型。</param> /// <param name="parameter">要使用的转换器参数。</param> /// <param name="culture">要用在转换器中的区域性。</param> /// <returns>转换后的值。如果该方法返回 null,则使用有效的 null 值。</returns> public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } #endregion } /// <summary> /// --Decimal /// </summary> public class DecimalConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value == null) return ""; if (!(value is decimal)) return "--"; var v = (decimal) value; var i = System.Convert.ToInt32(v); return i > 0 ? i.ToString(CultureInfo.InvariantCulture) : "--"; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } //LocalPolicyBooleanToVisibilityConverter /// <summary> /// 本地政策(本地)字段表示显隐转换 /// </summary> public class LocalPolicyBooleanToVisibilityConverter : IValueConverter { /// <summary> /// 转换值。 /// </summary> /// <param name="value">绑定源生成的值。</param> /// <param name="targetType">绑定目标属性的类型。</param> /// <param name="parameter">要使用的转换器参数。</param> /// <param name="culture">要用在转换器中的区域性。</param> /// <returns> /// 转换后的值。如果该方法返回 null,则使用有效的 null 值。 /// </returns> /// <exception cref="System.NotImplementedException"></exception> public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is string && value.ToString() == "本地") return Visibility.Visible; return Visibility.Collapsed; } /// <summary> /// 转换值。 /// </summary> /// <param name="value">绑定目标生成的值。</param> /// <param name="targetType">要转换到的类型。</param> /// <param name="parameter">要使用的转换器参数。</param> /// <param name="culture">要用在转换器中的区域性。</param> /// <returns> /// 转换后的值。如果该方法返回 null,则使用有效的 null 值。 /// </returns> /// <exception cref="System.NotImplementedException"></exception> public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
using MultiCommentCollector.Models; namespace MultiCommentCollector.Views { /// <summary> /// LogWindow.xaml の相互作用ロジック /// </summary> public partial class LogWindow : SingleMetroWindow { #region Singleton private static LogWindow instance; public static LogWindow Instance => instance ??= new(); #endregion public LogWindow() => InitializeComponent(); } }
using System; using System.Drawing; using System.Collections.Generic; using System.Text; namespace DiscordPoker { public enum Rank { NULL = 0, Two = 2, Three = 3, Four = 4, Five = 5, Six = 6, Seven = 7, Eight = 8, Nine = 9, Ten = 10, Jack = 11, Queen = 12, King = 13, Ace = 14, Joker = 15 }; public enum Suit { NULL, Clubs, Spades, Hearts, Diamonds, Joker }; public class Card { public static Size CardSize = new Size(76, 108); public Rank Rank { get; private set; } public Suit Suit { get; private set; } public Bitmap Back { get; private set; } public Bitmap Front { get; private set; } private static Dictionary<Suit, int> SuitToIndex = new Dictionary<Suit, int>() { { Suit.Spades, 0 }, { Suit.Diamonds, 1 }, { Suit.Hearts, 2 }, { Suit.Clubs, 3 } }; private static Dictionary<Rank, int> RankToIndex = new Dictionary<Rank, int>() { { Rank.Ace, 0 }, { Rank.Two, 1 }, { Rank.Three, 2 }, { Rank.Four, 3 }, { Rank.Five, 4 }, { Rank.Six, 5 }, { Rank.Seven, 6 }, { Rank.Eight, 7 }, { Rank.Nine, 8 }, { Rank.Ten, 9 }, { Rank.Jack, 10 }, { Rank.Queen, 11 }, { Rank.King, 12 } }; private static Dictionary<Rank, Tuple<Rank, Rank>> RankNeighbors = new Dictionary<Rank, Tuple<Rank, Rank>>() { { Rank.Ace, new Tuple<Rank, Rank>(Rank.Two, Rank.King ) }, { Rank.Two, new Tuple<Rank, Rank>(Rank.Ace, Rank.Three ) }, { Rank.Three, new Tuple<Rank, Rank>(Rank.Two, Rank.Four ) }, { Rank.Four, new Tuple<Rank, Rank>(Rank.Three, Rank.Five ) }, { Rank.Five, new Tuple<Rank, Rank>(Rank.Four, Rank.Six ) }, { Rank.Six, new Tuple<Rank, Rank>(Rank.Five, Rank.Seven ) }, { Rank.Seven, new Tuple<Rank, Rank>(Rank.Six, Rank.Eight ) }, { Rank.Eight, new Tuple<Rank, Rank>(Rank.Seven, Rank.Nine ) }, { Rank.Nine, new Tuple<Rank, Rank>(Rank.Eight, Rank.Ten ) }, { Rank.Ten, new Tuple<Rank, Rank>(Rank.Nine, Rank.Jack ) }, { Rank.Jack, new Tuple<Rank, Rank>(Rank.Ten, Rank.Queen ) }, { Rank.Queen, new Tuple<Rank, Rank>(Rank.Jack, Rank.King ) }, { Rank.King, new Tuple<Rank, Rank>(Rank.Queen, Rank.Ace ) }, }; public Card(Rank rank, Suit suit) { Front = new Bitmap(CardSize.Width, CardSize.Height); Back = new Bitmap(CardSize.Width, CardSize.Height); Rank = rank; Suit = suit; DrawCard(); } public void DrawCard() { int index = SuitToIndex[Suit] * 13 + RankToIndex[Rank]; Rectangle src = new Rectangle((index % 10) * 204, (index / 10) * 288, 204, 288); Rectangle dst = new Rectangle(new Point(0, 0), CardSize); Graphics graph = Graphics.FromImage(Front); graph.DrawImage(DiscordPoker.Properties.Resources.Cards, dst, src, GraphicsUnit.Pixel); graph.Dispose(); Rectangle bsrc = new Rectangle(7 * 204, 5 * 288, 204, 288); Graphics bgraph = Graphics.FromImage(Back); bgraph.DrawImage(DiscordPoker.Properties.Resources.Cards, dst, bsrc, GraphicsUnit.Pixel); bgraph.Dispose(); } public Tuple<Rank, Rank> NeighborRanks() { RankNeighbors.TryGetValue(this.Rank, out Tuple<Rank, Rank> ranks); return ranks; } public static bool operator >(Card card1, Card card2) { return card1.Rank > card2.Rank; } public static bool operator <(Card card1, Card card2) { return card1.Rank < card2.Rank; } public static bool operator ==(Card card1, Card card2) { return card1.Rank == card2.Rank; } public static bool operator !=(Card card1, Card card2) { return card1.Rank != card2.Rank; } public static Card Compare(Card card1, Card card2) { return (card1.Rank > card2.Rank) ? card1 : (card2.Rank > card1.Rank) ? card2 : new Card(card1.Rank, Suit.NULL); } public static Bitmap DrawCards(List<Card> cards) { Bitmap canvas = new Bitmap(CardSize.Width * cards.Count, CardSize.Height); Graphics graph = Graphics.FromImage(canvas); Rectangle src = new Rectangle(new Point(0, 0), CardSize); for (int i = 0; i < cards.Count; i++) { Rectangle dst = new Rectangle(i * CardSize.Width, 0, CardSize.Width, CardSize.Height); graph.DrawImage(cards[i].Front, dst, src, GraphicsUnit.Pixel); } graph.Dispose(); return canvas; } public bool IsNull() { return (Rank == Rank.NULL || Suit == Suit.NULL); } } }
using System; using System.ServiceModel; using LosPollosHermanos.Infrastructure; using LosPollosHermanos.ServiceContracts; namespace LosPollosHermanos.Services { class Program { static void Main(string[] args) { //var ordersServiceHost = new ServiceHost(typeof (OrdersService)); //var productsServiceHost = new ServiceHost(typeof(ProductsService)); var helper = ServiceBusTopicHelper.Setup(SubscriptionInitializer.Initialize()); try { //ordersServiceHost.Open(); //productsServiceHost.Open(); helper.Subscribe<OrderRequest>((order) => { var service = new OrdersService(); service.SendOrder(order); helper.Publish<OrderRequest>(order, (m) => { m.Properties["IsOrdered"] = true; m.Properties["Procesing"] = false; m.Properties["IsDelivered"] = false; }); } , "(IsOrdered = false) AND (IsDelivered = false)", "NewOrders" ); helper.Subscribe<OrderRequest>((order) => { var service = new OrdersService(); service.UpdateOrder(new UpdateOrderRequest { OrderId = order.OrderId, Status = OrderStatus.Delivered }); } , "IsDelivered = true", "DeliveredOrders" ); Console.WriteLine("Press intro to exit"); Console.ReadLine(); //ordersServiceHost.Close(); //productsServiceHost.Close(); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } } } }
using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace IoTHubReceiver.Model { public class DocumentType { public static string TelemetryDocument = "Telemetry"; public static string EventDocument = "Event"; } public class TelemetryDocument { /* Each document in DocumentDB has an id property which uniquely identifies * the document but that id field is of type string. * When creating a document, you may choose not to specify a value for this field * and DocumentDB assigns an id automatically but this value is a GUID. */ [JsonProperty(PropertyName = "id")] public string Id { get; set; } public int companyId { get; set; } public string iotDeviceId { get; set; } public int messageCatalogId { get; set; } public string messageType { get; set; } public JObject messageContent { get; set; } public override string ToString() { return JsonConvert.SerializeObject(this); } } public class EventDocument { [JsonProperty(PropertyName = "id")] public string Id { get; set; } public int companyId { get; set; } public string iotDeviceId { get; set; } public int messageCatalogId { get; set; } public string messageType { get; set; } public int eventRuleCatalogId { get; set; } public string eventRuleCatalogName { get; set; } public string eventRuleCatalogDescription { get; set; } public JObject messageContent { get; set; } public string triggeredTime { get; set; } public bool eventSent { get; set; } public string messageDocumentId { get; set; } public override string ToString() { return JsonConvert.SerializeObject(this); } } }
using API.Omorfias.Data.Models; using System; using System.Collections.Generic; using System.Text; namespace API.Omorfias.Data.Interfaces { public interface IAuthRepository { User GetById(int id); User FindUser(User userData); User FindByUserOrEmail(string email); User Register(User userData); } }
using System; using System.Diagnostics; using System.IO; using System.Net; using System.Text; using System.Web; using System.Windows.Forms; namespace DownLoadYoutube { public class UtilClass { public delegate void SetTextCallback(object sender, EventArgs eventArgs); public static WebClient WebClient; public static readonly Stopwatch Sw = new Stopwatch(); public UtilClass(string id) { var info = GetVideoInfo(id); Url = GetUrl(info); VideoName = GetTitle(info); FullPathVideoFileName = FileVideoDir + "\\" + VideoName + ".mp4"; FullPathMp3FileName = FileAudioDir + "\\" + VideoName + ".mp3"; } public UtilClass() { FileAudioDir = Directory.GetCurrentDirectory() + "\\" + "Mp3"; FileVideoDir = Directory.GetCurrentDirectory() + "\\" + "Video"; GreateDir(FileAudioDir); GreateDir(FileVideoDir); } private static string FileVideoDir { get; set; } private static string FileAudioDir { get; set; } public string VideoName { get; } public string Url { get; private set; } public string FullPathVideoFileName { get; private set; } public string FullPathMp3FileName { get; } private static void GreateDir(string dir) { if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } } private static string GetVideoInfo(string id) { var url = @"http://www.youtube.com/get_video_info?video_id=" + id; var proxyRequest = (HttpWebRequest) WebRequest.Create(url); proxyRequest.Method = "GET"; proxyRequest.ContentType = "application/x-www-form-urlencoded"; proxyRequest.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/532.5 (KHTML, like Gecko) Chrome/4.0.249.89 Safari/532.5"; proxyRequest.KeepAlive = true; var resp = proxyRequest.GetResponse() as HttpWebResponse; string html; // ReSharper disable once PossibleNullReferenceException // ReSharper disable once AssignNullToNotNullAttribute using (var sr = new StreamReader(resp.GetResponseStream(), Encoding.GetEncoding(1251))) html = sr.ReadToEnd(); html = html.Trim(); if (html == string.Empty) MessageBox.Show(@"Не получилось получить информацию о файле"); return html; } private static string GetUrl(string html) { var pattern = "url_encoded_fmt_stream_map="; var index = html.LastIndexOf(pattern, StringComparison.Ordinal) + pattern.Length; html = html.Substring(index); // var z = HttpUtility.HtmlDecode(HttpUtility.HtmlDecode(html)); html = HttpUtility.UrlDecode(html); //Console.WriteLine(z);// Выводим в листбокс listbox, но можешь записывать и в файл if (html == null) return null; pattern = "url="; index = html.IndexOf(pattern, StringComparison.Ordinal) + pattern.Length; html = html.Substring(index); index = html.IndexOf("&", StringComparison.Ordinal); html = html.Remove(index); html = HttpUtility.UrlDecode(html); return html; } private static string GetTitle(string html) { var index = html.LastIndexOf("title=", StringComparison.Ordinal) + "title=".Length; html = html.Substring(index); index = html.IndexOf("&", StringComparison.Ordinal); if (index > 0) html = html.Remove(index); html = HttpUtility.UrlDecode(html); return html?.Trim(Path.GetInvalidFileNameChars()); } } }
// Accord Neural Net Library // The Accord.NET Framework // http://accord-framework.net // // Copyright © César Souza, 2009-2015 // cesarsouza at gmail.com // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // namespace Accord.Neuro.Learning { using System; using System.Diagnostics; using System.Threading.Tasks; using Accord.Math; using Accord.Math.Decompositions; /// <summary> /// The Jacobian computation method used by the Levenberg-Marquardt. /// </summary> /// public enum JacobianMethod { /// <summary> /// Computes the Jacobian using approximation by finite differences. This /// method is slow in comparison with back-propagation and should be used /// only for debugging or comparison purposes. /// </summary> /// ByFiniteDifferences, /// <summary> /// Computes the Jacobian using back-propagation for the chain rule of /// calculus. This is the preferred way of computing the Jacobian. /// </summary> /// ByBackpropagation, } /// <summary> /// Levenberg-Marquardt Learning Algorithm with optional Bayesian Regularization. /// </summary> /// /// <remarks> /// <para>This class implements the Levenberg-Marquardt learning algorithm, /// which treats the neural network learning as a function optimization /// problem. The Levenberg-Marquardt is one of the fastest and accurate /// learning algorithms for small to medium sized networks.</para> /// /// <para>However, in general, the standard LM algorithm does not perform as well /// on pattern recognition problems as it does on function approximation problems. /// The LM algorithm is designed for least squares problems that are approximately /// linear. Because the output neurons in pattern recognition problems are generally /// saturated, it will not be operating in the linear region.</para> /// /// <para>The advantages of the LM algorithm decreases as the number of network /// parameters increases. </para> /// /// <example> /// <para>Sample usage (training network to calculate XOR function):</para> /// <code> /// // initialize input and output values /// double[][] input = /// { /// new double[] {0, 0}, new double[] {0, 1}, /// new double[] {1, 0}, new double[] {1, 1} /// }; /// /// double[][] output = /// { /// new double[] {0}, new double[] {1}, /// new double[] {1}, new double[] {0} /// }; /// /// // create neural network /// ActivationNetwork network = new ActivationNetwork( /// SigmoidFunction( 2 ), /// 2, // two inputs in the network /// 2, // two neurons in the first layer /// 1 ); // one neuron in the second layer /// /// // create teacher /// LevenbergMarquardtLearning teacher = new LevenbergMarquardtLearning( network ); /// /// // loop /// while ( !needToStop ) /// { /// // run epoch of learning procedure /// double error = teacher.RunEpoch( input, output ); /// /// // check error value to see if we need to stop /// // ... /// } /// </code> /// /// <para> /// The following example shows how to create a neural network to learn a classification /// problem with multiple classes.</para> /// /// <code> /// // Here we will be creating a neural network to process 3-valued input /// // vectors and classify them into 4-possible classes. We will be using /// // a single hidden layer with 5 hidden neurons to accomplish this task. /// // /// int numberOfInputs = 3; /// int numberOfClasses = 4; /// int hiddenNeurons = 5; /// /// // Those are the input vectors and their expected class labels /// // that we expect our network to learn. /// // /// double[][] input = /// { /// new double[] { -1, -1, -1 }, // 0 /// new double[] { -1, 1, -1 }, // 1 /// new double[] { 1, -1, -1 }, // 1 /// new double[] { 1, 1, -1 }, // 0 /// new double[] { -1, -1, 1 }, // 2 /// new double[] { -1, 1, 1 }, // 3 /// new double[] { 1, -1, 1 }, // 3 /// new double[] { 1, 1, 1 } // 2 /// }; /// /// int[] labels = /// { /// 0, /// 1, /// 1, /// 0, /// 2, /// 3, /// 3, /// 2, /// }; /// /// // In order to perform multi-class classification, we have to select a /// // decision strategy in order to be able to interpret neural network /// // outputs as labels. For this, we will be expanding our 4 possible class /// // labels into 4-dimensional output vectors where one single dimension /// // corresponding to a label will contain the value +1 and -1 otherwise. /// /// double[][] outputs = Accord.Statistics.Tools /// .Expand(labels, numberOfClasses, -1, 1); /// /// // Next we can proceed to create our network /// var function = new BipolarSigmoidFunction(2); /// var network = new ActivationNetwork(function, /// numberOfInputs, hiddenNeurons, numberOfClasses); /// /// // Heuristically randomize the network /// new NguyenWidrow(network).Randomize(); /// /// // Create the learning algorithm /// var teacher = new LevenbergMarquardtLearning(network); /// /// // Teach the network for 10 iterations: /// double error = Double.PositiveInfinity; /// for (int i = 0; i &lt; 10; i++) /// error = teacher.RunEpoch(input, outputs); /// /// // At this point, the network should be able to /// // perfectly classify the training input points. /// /// for (int i = 0; i &lt; input.Length; i++) /// { /// int answer; /// double[] output = network.Compute(input[i]); /// double response = output.Max(out answer); /// /// int expected = labels[i]; /// /// // at this point, the variables 'answer' and /// // 'expected' should contain the same value. /// } /// </code> /// </example> /// /// <para> /// References: /// <list type="bullet"> /// <item><description><a href="http://www.cs.nyu.edu/~roweis/notes/lm.pdf"> /// Sam Roweis. Levenberg-Marquardt Optimization.</a></description></item> /// <item><description><a href="http://www-alg.ist.hokudai.ac.jp/~jan/alpha.pdf"> /// Jan Poland. (2001). On the Robustness of Update Strategies for the Bayesian /// Hyperparameter alpha. Available on: http://www-alg.ist.hokudai.ac.jp/~jan/alpha.pdf </a></description></item> /// <item><description><a href="http://cs.olemiss.edu/~ychen/publications/conference/chen_ijcnn99.pdf"> /// B. Wilamowski, Y. Chen. (1999). Efficient Algorithm for Training Neural Networks /// with one Hidden Layer. Available on: http://cs.olemiss.edu/~ychen/publications/conference/chen_ijcnn99.pdf </a></description></item> /// <item><description><a href="http://www.inference.phy.cam.ac.uk/mackay/Bayes_FAQ.html"> /// David MacKay. (2004). Bayesian methods for neural networks - FAQ. Available on: /// http://www.inference.phy.cam.ac.uk/mackay/Bayes_FAQ.html </a></description></item> /// </list> /// </para> /// </remarks> /// public class LevenbergMarquardtLearning : ISupervisedLearning { private const double lambdaMax = 1e25; // network to teach private ActivationNetwork network; // Bayesian Regularization variables private bool useBayesianRegularization; // Bayesian Regularization Hyperparameters private double gamma; private double alpha; private double beta = 1; // Levenberg-Marquardt variables private float[][] jacobian; private float[][] hessian; private float[] diagonal; private float[] gradient; private float[] weights; private float[] deltas; private double[] errors; private JacobianMethod method; // Levenberg damping factor private double lambda = 0.1; // The amount the damping factor is adjusted // when searching the minimum error surface private double v = 10.0; // Total of weights in the network private int numberOfParameters; private int blocks = 1; private int outputCount; /// <summary> /// Levenberg's damping factor (lambda). This /// value must be positive. Default is 0.1. /// </summary> /// /// <remarks> /// The value determines speed of learning. Default value is <b>0.1</b>. /// </remarks> /// public double LearningRate { get { return lambda; } set { if (lambda <= 0) throw new ArgumentOutOfRangeException("value", "Value must be positive."); lambda = value; } } /// <summary> /// Learning rate adjustment. Default value is 10. /// </summary> /// /// <remarks> /// The value by which the learning rate is adjusted when searching /// for the minimum cost surface. Default value is 10. /// </remarks> /// public double Adjustment { get { return v; } set { v = value; } } /// <summary> /// Gets the total number of parameters /// in the network being trained. /// </summary> /// public int NumberOfParameters { get { return numberOfParameters; } } /// <summary> /// Gets the number of effective parameters being used /// by the network as determined by the Bayesian regularization. /// </summary> /// <remarks> /// If no regularization is being used, the value will be 0. /// </remarks> /// public double EffectiveParameters { get { return gamma; } } /// <summary> /// Gets or sets the importance of the squared sum of network /// weights in the cost function. Used by the regularization. /// </summary> /// /// <remarks> /// This is the first Bayesian hyperparameter. The default /// value is 0. /// </remarks> /// public double Alpha { get { return alpha; } set { alpha = value; } } /// <summary> /// Gets or sets the importance of the squared sum of network /// errors in the cost function. Used by the regularization. /// </summary> /// /// <remarks> /// This is the second Bayesian hyperparameter. The default /// value is 1. /// </remarks> /// public double Beta { get { return beta; } set { beta = value; } } /// <summary> /// Gets or sets whether to use Bayesian Regularization. /// </summary> /// public bool UseRegularization { get { return useBayesianRegularization; } set { useBayesianRegularization = value; } } /// <summary> /// Gets or sets the number of blocks to divide the /// Jacobian matrix in the Hessian calculation to /// preserve memory. Default is 1. /// </summary> /// public int Blocks { get { return blocks; } set { blocks = value; } } /// <summary> /// Gets the approximate Hessian matrix of second derivatives /// generated in the last algorithm iteration. The Hessian is /// stored in the upper triangular part of this matrix. See /// remarks for details. /// </summary> /// /// <remarks> /// <para> /// The Hessian needs only be upper-triangular, since /// it is symmetric. The Cholesky decomposition will /// make use of this fact and use the lower-triangular /// portion to hold the decomposition, conserving memory</para> /// <para> /// Thus said, this property will hold the Hessian matrix /// in the upper-triangular part of this matrix, and store /// its Cholesky decomposition on its lower triangular part.</para> /// </remarks> /// public float[][] Hessian { get { return hessian; } } /// <summary> /// Gets the Jacobian matrix created in the last iteration. /// </summary> /// public float[][] Jacobian { get { return jacobian; } } /// <summary> /// Gets the gradient vector computed in the last iteration. /// </summary> /// public float[] Gradient { get { return gradient; } } /// <summary> /// Initializes a new instance of the <see cref="LevenbergMarquardtLearning"/> class. /// </summary> /// /// <param name="network">Network to teach.</param> /// public LevenbergMarquardtLearning(ActivationNetwork network) : this(network, false, JacobianMethod.ByBackpropagation) { } /// <summary> /// Initializes a new instance of the <see cref="LevenbergMarquardtLearning"/> class. /// </summary> /// /// <param name="network">Network to teach.</param> /// <param name="useRegularization">True to use Bayesian regularization, false otherwise.</param> /// public LevenbergMarquardtLearning(ActivationNetwork network, bool useRegularization) : this(network, useRegularization, JacobianMethod.ByBackpropagation) { } /// <summary> /// Initializes a new instance of the <see cref="LevenbergMarquardtLearning"/> class. /// </summary> /// /// <param name="network">Network to teach.</param> /// <param name="method">The method by which the Jacobian matrix will be calculated.</param> /// public LevenbergMarquardtLearning(ActivationNetwork network, JacobianMethod method) : this(network, false, method) { } /// <summary> /// Initializes a new instance of the <see cref="LevenbergMarquardtLearning"/> class. /// </summary> /// /// <param name="network">Network to teach.</param> /// <param name="useRegularization">True to use Bayesian regularization, false otherwise.</param> /// <param name="method">The method by which the Jacobian matrix will be calculated.</param> /// public LevenbergMarquardtLearning(ActivationNetwork network, bool useRegularization, JacobianMethod method) { this.network = network; this.numberOfParameters = getNumberOfParameters(network); this.outputCount = network.Layers[network.Layers.Length - 1].Neurons.Length; this.useBayesianRegularization = useRegularization; this.method = method; this.weights = new float[numberOfParameters]; this.hessian = new float[numberOfParameters][]; for (int i = 0; i < hessian.Length; i++) hessian[i] = new float[numberOfParameters]; this.diagonal = new float[numberOfParameters]; this.gradient = new float[numberOfParameters]; this.jacobian = new float[numberOfParameters][]; // Will use Backpropagation method for Jacobian computation if (method == JacobianMethod.ByBackpropagation) { // create weight derivatives arrays this.weightDerivatives = new float[network.Layers.Length][][]; this.thresholdsDerivatives = new float[network.Layers.Length][]; // initialize arrays for (int i = 0; i < network.Layers.Length; i++) { ActivationLayer layer = (ActivationLayer)network.Layers[i]; this.weightDerivatives[i] = new float[layer.Neurons.Length][]; this.thresholdsDerivatives[i] = new float[layer.Neurons.Length]; for (int j = 0; j < layer.Neurons.Length; j++) this.weightDerivatives[i][j] = new float[layer.InputsCount]; } } else // Will use finite difference method for Jacobian computation { // create differential coefficient arrays this.differentialCoefficients = createCoefficients(3); this.derivativeStepSize = new double[numberOfParameters]; // initialize arrays for (int i = 0; i < numberOfParameters; i++) this.derivativeStepSize[i] = derivativeStep; } } /// <summary> /// This method should not be called. Use <see cref="RunEpoch"/> instead. /// </summary> /// /// <param name="input">Array of input vectors.</param> /// <param name="output">Array of output vectors.</param> /// /// <returns>Nothing.</returns> /// /// <remarks><para>Online learning mode is not supported by the /// Levenberg Marquardt. Use batch learning mode instead.</para></remarks> /// public double Run(double[] input, double[] output) { throw new InvalidOperationException("Learning can only be done in batch mode."); } /// <summary> /// Runs a single learning epoch. /// </summary> /// /// <param name="input">Array of input vectors.</param> /// <param name="output">Array of output vectors.</param> /// /// <returns>Returns summary learning error for the epoch.</returns> /// /// <remarks><para>The method runs one learning epoch, by calling running necessary /// iterations of the Levenberg Marquardt to achieve an error decrease.</para></remarks> /// public double RunEpoch(double[][] input, double[][] output) { // Initial definitions and memory allocations int N = input.Length; JaggedCholeskyDecompositionF decomposition = null; double sumOfSquaredErrors = 0.0; double sumOfSquaredWeights = 0.0; double trace = 0.0; // Set upper triangular Hessian to zero for (int i = 0; i < hessian.Length; i++) Array.Clear(hessian[i], i, hessian.Length - i); // Set Gradient vector to zero Array.Clear(gradient, 0, gradient.Length); // Divide the problem into blocks. Instead of computing // a single Jacobian and a single error vector, we will // be computing multiple Jacobians for smaller problems // and then sum all blocks into the final Hessian matrix // and gradient vector. int blockSize = input.Length / Blocks; int finalBlock = input.Length % Blocks; int jacobianSize = blockSize * outputCount; // Re-allocate the partial Jacobian matrix only if needed if (jacobian[0] == null || jacobian[0].Length < jacobianSize) { for (int i = 0; i < jacobian.Length; i++) this.jacobian[i] = new float[jacobianSize]; } // Re-allocate error vector only if needed if (errors == null || errors.Length < jacobianSize) errors = new double[jacobianSize]; // For each block for (int s = 0; s <= Blocks; s++) { if (s == Blocks && finalBlock == 0) continue; Trace.TraceInformation("Starting Jacobian block {0}/{1}", s + 1, Blocks); int B = (s == Blocks) ? finalBlock : blockSize; int[] block = Vector.Range(s * blockSize, s * blockSize + B); double[][] inputBlock = input.Submatrix(block); double[][] outputBlock = output.Submatrix(block); // Compute the partial Jacobian matrix if (method == JacobianMethod.ByBackpropagation) sumOfSquaredErrors = JacobianByChainRule(inputBlock, outputBlock); else sumOfSquaredErrors = JacobianByFiniteDifference(inputBlock, outputBlock); if (Double.IsNaN(sumOfSquaredErrors)) throw new ArithmeticException("Jacobian calculation has produced a non-finite number."); Trace.TraceInformation("Jacobian block finished."); // Compute error gradient using Jacobian Trace.TraceInformation("Updating gradient."); for (int i = 0; i < jacobian.Length; i++) { double gsum = 0; for (int j = 0; j < jacobianSize; j++) gsum += jacobian[i][j] * errors[j]; gradient[i] += (float)gsum; } // Compute Quasi-Hessian Matrix approximation // using the outer product Jacobian (H ~ J'J) Trace.TraceInformation("Updating Hessian."); Parallel.For(0, jacobian.Length, i => { float[] ji = jacobian[i]; float[] hi = hessian[i]; for (int j = i; j < hi.Length; j++) { float[] jj = jacobian[j]; double hsum = 0; for (int k = 0; k < jacobianSize; k++) hsum += ji[k] * jj[k]; // The Hessian need only be upper-triangular, since // it is symmetric. The Cholesky decomposition will // make use of this fact and use the lower-triangular // portion to hold the decomposition, conserving memory. hi[j] += (float)(2 * beta * hsum); } }); } Trace.TraceInformation("Hessian computation finished."); // Store the Hessian's diagonal for future computations. The // diagonal will be destroyed in the decomposition, so it can // still be updated on every iteration by restoring this copy. for (int i = 0; i < hessian.Length; i++) diagonal[i] = hessian[i][i]; // Create the initial weights vector sumOfSquaredWeights = saveNetworkToArray(); // Define the objective function: (Bayesian regularization objective) double objective = beta * sumOfSquaredErrors + alpha * sumOfSquaredWeights; double current = objective + 1.0; // (starting value to enter iteration) // Begin of the main Levenberg-Marquardt method lambda /= v; // We'll try to find a direction with less error // (or where the objective function is smaller) while (current >= objective && lambda < lambdaMax) { lambda *= v; // Update diagonal (Levenberg-Marquardt) for (int i = 0; i < diagonal.Length; i++) hessian[i][i] = (float)(diagonal[i] + 2 * lambda + 2 * alpha); Trace.TraceInformation("Decomposition started."); // Decompose to solve the linear system. The Cholesky decomposition // is done in place, occupying the Hessian's lower-triangular part. decomposition = new JaggedCholeskyDecompositionF(hessian, robust: true, inPlace: true); Trace.TraceInformation("Decomposition ended."); // Check if the decomposition exists if (decomposition.IsNotDefined) { // The Hessian is singular. Continue to the next // iteration until the diagonal update transforms // it back to non-singular. continue; } Trace.TraceInformation("Solving linear system."); // Solve using Cholesky decomposition deltas = decomposition.Solve(gradient); Trace.TraceInformation("Updating weights."); // Update weights using the calculated deltas sumOfSquaredWeights = loadArrayIntoNetwork(); // Calculate the new error sumOfSquaredErrors = ComputeError(input, output); // Update the objective function current = beta * sumOfSquaredErrors + alpha * sumOfSquaredWeights; // If the object function is bigger than before, the method // is tried again using a greater damping factor. } // If this iteration caused a error drop, then next // iteration will use a smaller damping factor. lambda /= v; if (lambda < 1e-300) lambda = 1e-300; // If we are using Bayesian regularization, we need to // update the Bayesian hyperparameters alpha and beta if (useBayesianRegularization) { // References: // - http://www-alg.ist.hokudai.ac.jp/~jan/alpha.pdf // - http://www.inference.phy.cam.ac.uk/mackay/Bayes_FAQ.html // Compute the trace for the inverse Hessian in place. The // Hessian which was still being hold together with the L // factorization will be destroyed after this computation. trace = decomposition.InverseTrace(destroy: true); // Poland update's formula: gamma = numberOfParameters - (alpha * trace); alpha = numberOfParameters / (2 * sumOfSquaredWeights + trace); beta = System.Math.Abs((N - gamma) / (2 * sumOfSquaredErrors)); //beta = (N - gamma) / (2.0 * sumOfSquaredErrors); // Original MacKay's update formula: // gamma = (double)networkParameters - (alpha * trace); // alpha = gamma / (2.0 * sumOfSquaredWeights); // beta = (gamma - N) / (2.0 * sumOfSquaredErrors); } return sumOfSquaredErrors; } /// <summary> /// Compute network error for a given data set. /// </summary> /// /// <param name="input">The input points.</param> /// <param name="output">The output points.</param> /// /// <returns>The sum of squared errors for the data.</returns> /// public double ComputeError(double[][] input, double[][] output) { double sumOfSquaredErrors = 0; #if NET35 for (int i = 0; i < input.Length; i++) { // Compute network answer double[] y = network.Compute(input[i]); for (int j = 0; j < y.Length; j++) { double e = (y[j] - output[i][j]); sumOfSquaredErrors += e * e; } } #else Object lockSum = new Object(); Parallel.For(0, input.Length, // Initialize () => 0.0, // Map (i, loopState, partialSum) => { // Compute network answer double[] y = network.Compute(input[i]); for (int j = 0; j < y.Length; j++) { double e = (y[j] - output[i][j]); partialSum += e * e; } return partialSum; }, // Reduce (partialSum) => { lock (lockSum) sumOfSquaredErrors += partialSum; } ); #endif return sumOfSquaredErrors / 2.0; } /// <summary> /// Update network's weights. /// </summary> /// /// <returns>The sum of squared weights divided by 2.</returns> /// private double loadArrayIntoNetwork() { double w, sumOfSquaredWeights = 0.0; // For each layer in the network for (int li = 0, cur = 0; li < network.Layers.Length; li++) { ActivationLayer layer = network.Layers[li] as ActivationLayer; // for each neuron in the layer for (int ni = 0; ni < layer.Neurons.Length; ni++, cur++) { ActivationNeuron neuron = layer.Neurons[ni] as ActivationNeuron; // for each weight in the neuron for (int wi = 0; wi < neuron.Weights.Length; wi++, cur++) { neuron.Weights[wi] = w = weights[cur] + deltas[cur]; sumOfSquaredWeights += w * w; } // for each threshold value (bias): neuron.Threshold = w = weights[cur] + deltas[cur]; sumOfSquaredWeights += w * w; } } return sumOfSquaredWeights / 2.0; } /// <summary> /// Creates the initial weight vector w /// </summary> /// /// <returns>The sum of squared weights divided by 2.</returns> /// private double saveNetworkToArray() { double w, sumOfSquaredWeights = 0.0; // for each layer in the network for (int li = 0, cur = 0; li < network.Layers.Length; li++) { ActivationLayer layer = network.Layers[li] as ActivationLayer; // for each neuron in the layer for (int ni = 0; ni < network.Layers[li].Neurons.Length; ni++, cur++) { ActivationNeuron neuron = layer.Neurons[ni] as ActivationNeuron; // for each weight in the neuron for (int wi = 0; wi < neuron.InputsCount; wi++, cur++) { // We copy it to the starting weights vector w = weights[cur] = (float)neuron.Weights[wi]; sumOfSquaredWeights += w * w; } // and also for the threshold value (bias): w = weights[cur] = (float)neuron.Threshold; sumOfSquaredWeights += w * w; } } return sumOfSquaredWeights / 2.0; } /// <summary> /// Gets the number of parameters in a network. /// </summary> private static int getNumberOfParameters(ActivationNetwork network) { int sum = 0; for (int i = 0; i < network.Layers.Length; i++) { for (int j = 0; j < network.Layers[i].Neurons.Length; j++) { // number of weights plus the bias value sum += network.Layers[i].Neurons[j].InputsCount + 1; } } return sum; } #region Jacobian Calculation By Chain Rule private float[][][] weightDerivatives; private float[][] thresholdsDerivatives; /// <summary> /// Calculates the Jacobian matrix by using the chain rule. /// </summary> /// <param name="input">The input vectors.</param> /// <param name="output">The desired output vectors.</param> /// <returns>The sum of squared errors for the last error divided by 2.</returns> /// private double JacobianByChainRule(double[][] input, double[][] output) { double e, sumOfSquaredErrors = 0.0; // foreach input training sample for (int i = 0, row = 0; i < input.Length; i++) { // Compute a forward pass network.Compute(input[i]); // for each output of for the input sample for (int j = 0; j < output[i].Length; j++, row++) { // Calculate the derivatives for the input/output // pair by computing a backpropagation chain pass e = errors[row] = CalculateDerivatives(input[i], output[i], j); sumOfSquaredErrors += e * e; // Create the Jacobian matrix row: for each layer in the network for (int li = 0, col = 0; li < weightDerivatives.Length; li++) { float[][] layerDerivatives = weightDerivatives[li]; float[] layerThresoldDerivatives = thresholdsDerivatives[li]; // for each neuron in the layer for (int ni = 0; ni < layerDerivatives.Length; ni++, col++) { float[] neuronWeightDerivatives = layerDerivatives[ni]; // for each weight of the neuron, copy the derivative for (int wi = 0; wi < neuronWeightDerivatives.Length; wi++, col++) jacobian[col][row] = neuronWeightDerivatives[wi]; // also copy the neuron threshold jacobian[col][row] = layerThresoldDerivatives[ni]; } } } } return sumOfSquaredErrors / 2.0; } /// <summary> /// Calculates partial derivatives for all weights of the network. /// </summary> /// /// <param name="input">The input vector.</param> /// <param name="desiredOutput">Desired output vector.</param> /// <param name="outputIndex">The current output location (index) in the desired output vector.</param> /// /// <returns>Returns summary squared error of the last layer.</returns> /// private double CalculateDerivatives(double[] input, double[] desiredOutput, int outputIndex) { // Assume all network neurons have the same activation function var function = (network.Layers[0].Neurons[0] as ActivationNeuron).ActivationFunction; // Start by the output layer first int outputLayerIndex = network.Layers.Length - 1; ActivationLayer outputLayer = network.Layers[outputLayerIndex] as ActivationLayer; double[] previousLayerOutput; // If we have only one single layer, the previous layer outputs is given by the input layer previousLayerOutput = (outputLayerIndex == 0) ? input : network.Layers[outputLayerIndex - 1].Output; // Clear derivatives for other output's neurons for (int i = 0; i < thresholdsDerivatives[outputLayerIndex].Length; i++) thresholdsDerivatives[outputLayerIndex][i] = 0; for (int i = 0; i < weightDerivatives[outputLayerIndex].Length; i++) for (int j = 0; j < weightDerivatives[outputLayerIndex][i].Length; j++) weightDerivatives[outputLayerIndex][i][j] = 0; // Retrieve current desired output neuron ActivationNeuron outputNeuron = outputLayer.Neurons[outputIndex] as ActivationNeuron; float[] neuronWeightDerivatives = weightDerivatives[outputLayerIndex][outputIndex]; double output = outputNeuron.Output; double error = desiredOutput[outputIndex] - output; double derivative = function.Derivative2(output); // Set derivative for each weight in the neuron for (int i = 0; i < neuronWeightDerivatives.Length; i++) neuronWeightDerivatives[i] = (float)(derivative * previousLayerOutput[i]); // Set derivative for the current threshold (bias) term thresholdsDerivatives[outputLayerIndex][outputIndex] = (float)derivative; // Now, proceed to the next hidden layers for (int li = network.Layers.Length - 2; li >= 0; li--) { int nextLayerIndex = li + 1; ActivationLayer layer = network.Layers[li] as ActivationLayer; ActivationLayer nextLayer = network.Layers[nextLayerIndex] as ActivationLayer; // If we are in the first layer, the previous layer is just the input layer previousLayerOutput = (li == 0) ? input : network.Layers[li - 1].Output; // Now, we will compute the derivatives for the current layer applying the chain // rule. To apply the chain-rule, we will make use of the previous derivatives // computed for the inner layers (forming a calculation chain, hence the name). // So, for each neuron in the current layer: for (int ni = 0; ni < layer.Neurons.Length; ni++) { ActivationNeuron neuron = layer.Neurons[ni] as ActivationNeuron; neuronWeightDerivatives = weightDerivatives[li][ni]; float[] layerDerivatives = thresholdsDerivatives[li]; float[] nextLayerDerivatives = thresholdsDerivatives[li + 1]; double sum = 0; // The chain-rule can be stated as (f(w*g(x))' = f'(w*g(x)) * w*g'(x) // // We will start computing the second part of the product. Since the g' // derivatives have already been computed in the previous computation, // we will be summing all previous function derivatives and weighting // them using their connection weight (synapses). // // So, for each neuron in the next layer: for (int nj = 0; nj < nextLayerDerivatives.Length; nj++) { // retrieve the weight connecting the output of the current // neuron and the activation function of the next neuron. double weight = nextLayer.Neurons[nj].Weights[ni]; // accumulate the synapse weight * next layer derivative sum += weight * nextLayerDerivatives[nj]; } // Continue forming the chain-rule statement derivative = sum * function.Derivative2(neuron.Output); // Set derivative for each weight in the neuron for (int wi = 0; wi < neuronWeightDerivatives.Length; wi++) neuronWeightDerivatives[wi] = (float)(derivative * previousLayerOutput[wi]); // Set derivative for the current threshold layerDerivatives[ni] = (float)(derivative); // The threshold derivatives also gather the derivatives for // the layer, and thus can be re-used in next calculations. } } // return error return error; } #endregion #region Jacobian Calculation by Finite Differences // References: // - Trent F. Guidry, http://www.trentfguidry.net/ private double[] derivativeStepSize; private const double derivativeStep = 1e-2; private double[][,] differentialCoefficients; /// <summary> /// Calculates the Jacobian Matrix using Finite Differences /// </summary> /// /// <returns>Returns the sum of squared errors of the network divided by 2.</returns> /// private double JacobianByFiniteDifference(double[][] input, double[][] desiredOutput) { double e, sumOfSquaredErrors = 0; // for each input training sample for (int i = 0, row = 0; i < input.Length; i++) { // Compute a forward pass double[] networkOutput = network.Compute(input[i]); // for each output respective to the input for (int j = 0; j < networkOutput.Length; j++, row++) { // Calculate network error to build the residuals vector e = errors[row] = desiredOutput[i][j] - networkOutput[j]; sumOfSquaredErrors += e * e; // Computation of one of the Jacobian Matrix rows by numerical differentiation: // for each weight w_j in the network, we have to compute its partial derivative // to build the Jacobian matrix. // So, for each layer: for (int li = 0, col = 0; li < network.Layers.Length; li++) { ActivationLayer layer = network.Layers[li] as ActivationLayer; // for each neuron: for (int ni = 0; ni < layer.Neurons.Length; ni++, col++) { ActivationNeuron neuron = layer.Neurons[ni] as ActivationNeuron; // for each weight: for (int wi = 0; wi < neuron.InputsCount; wi++, col++) { // Compute its partial derivative jacobian[col][row] = (float)ComputeDerivative(input[i], li, ni, wi, ref derivativeStepSize[col], networkOutput[j], j); } // and also for each threshold value (bias) jacobian[col][row] = (float)ComputeDerivative(input[i], li, ni, -1, ref derivativeStepSize[col], networkOutput[j], j); } } } } // returns the sum of squared errors / 2 return sumOfSquaredErrors / 2.0; } /// <summary> /// Creates the coefficients to be used when calculating /// the approximate Jacobian by using finite differences. /// </summary> /// private static double[][,] createCoefficients(int points) { double[][,] coefficients = new double[points][,]; for (int i = 0; i < coefficients.Length; i++) { double[,] delts = new double[points, points]; for (int j = 0; j < points; j++) { double delt = (double)(j - i); double hterm = 1.0; for (int k = 0; k < points; k++) { delts[j, k] = hterm / Accord.Math.Special.Factorial(k); hterm *= delt; } } coefficients[i] = Matrix.Inverse(delts); double fac = Accord.Math.Special.Factorial(points); for (int j = 0; j < points; j++) for (int k = 0; k < points; k++) coefficients[i][j, k] = (System.Math.Round(coefficients[i][j, k] * fac, MidpointRounding.AwayFromZero)) / fac; } return coefficients; } /// <summary> /// Computes the derivative of the network in /// respect to the weight passed as parameter. /// </summary> /// private double ComputeDerivative(double[] inputs, int layer, int neuron, int weight, ref double stepSize, double networkOutput, int outputIndex) { int numPoints = differentialCoefficients.Length; double originalValue; // Saves a copy of the original value in the neuron if (weight >= 0) originalValue = network.Layers[layer].Neurons[neuron].Weights[weight]; else originalValue = (network.Layers[layer].Neurons[neuron] as ActivationNeuron).Threshold; double[] points = new double[numPoints]; if (originalValue != 0.0) stepSize = derivativeStep * System.Math.Abs(originalValue); else stepSize = derivativeStep; int centerPoint = (numPoints - 1) / 2; for (int i = 0; i < numPoints; i++) { if (i != centerPoint) { double newValue = originalValue + ((double)(i - centerPoint)) * stepSize; if (weight >= 0) network.Layers[layer].Neurons[neuron].Weights[weight] = newValue; else (network.Layers[layer].Neurons[neuron] as ActivationNeuron).Threshold = newValue; points[i] = network.Compute(inputs)[outputIndex]; } else { points[i] = networkOutput; } } double ret = 0.0; for (int i = 0; i < differentialCoefficients.Length; i++) ret += differentialCoefficients[centerPoint][1, i] * points[i]; ret /= System.Math.Pow(stepSize, 1); // Changes back the modified value if (weight >= 0) network.Layers[layer].Neurons[neuron].Weights[weight] = originalValue; else (network.Layers[layer].Neurons[neuron] as ActivationNeuron).Threshold = originalValue; return ret; } #endregion } }
using System; namespace SparamTestLib { public class SparamChannel_Avg : SparamTestCase.TestCaseAbstract { private int iStartCnt, iStopCnt; private bool blnInterStart, blnInterStop; public override void Initialize() { _Result = new SResult(); for (int seg = 0; seg < tmpSparamRaw[ChannelNumber - 1].Freq.Length; seg++) { if (StartFreq >= tmpSparamRaw[ChannelNumber - 1].Freq[seg] && StartFreq < tmpSparamRaw[ChannelNumber - 1].Freq[seg + 1]) { iStartCnt = seg; blnInterStart = true; if (StartFreq == tmpSparamRaw[ChannelNumber - 1].Freq[seg]) blnInterStart = false; } if (StopFreq >= tmpSparamRaw[ChannelNumber - 1].Freq[seg] && StopFreq < tmpSparamRaw[ChannelNumber - 1].Freq[seg + 1]) { iStopCnt = seg; blnInterStop = true; if (StopFreq == tmpSparamRaw[ChannelNumber - 1].Freq[seg]) blnInterStop = false; } } Array.Resize(ref _Result.Result, 1); Array.Resize(ref _Result.Header, 1); _Result.Enable = true; _Result.Header[0] = TcfHeader + "_C" + ChannelNumber + "_" + SParam + "_" + StartFreq / 1e6 + "_M_" + StopFreq / 1e6 + "_M"; _Result.Result[0] = -9999; } public override void RunTest() { int pointNo = iStopCnt - iStartCnt + 1; double total_magnitude=0; if (childErrorRaise == true) { tmpResult[TestNo].Result[0] = -999; return; } //Start adding the magnitude base on the freq range specified earlier for (int iArr = iStartCnt; iArr <= iStopCnt; iArr++) { //Mag_SParam.MagAng = Math_Func.Conversion.conv_RealImag_to_MagAngle(SParamData[Channel_Number - 1].sParam_Data[SParam].sParam[iArr].ReIm); total_magnitude = total_magnitude + tmpSparamRaw[ChannelNumber - 1].SParamData[GetSparamIndex()].SParam[iArr].DB; //Mag_SParam.MagAng.Mag; } //Calculate the channel averaging _Result.Result[0] = total_magnitude / pointNo; } } }
using SFML.Graphics; using SFML.Window; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LD30 { class Tree : GameObject { Sprite sprite; public Vector2f Position { get { return sprite.Position; } set { sprite.Position = value + new Vector2f(0f, -Game.TileSize * 2); } } public override float Depth { get { return Position.Y + Game.TileSize * 3; } } public override FloatRect? VisibleRect { get { return new FloatRect(Position.X, Position.Y, Game.TileSize * 2, Game.TileSize * 3); } } public Tree(Game game, Sprite spr) : base(game) { this.sprite = spr; } public override void Draw(RenderTarget target) { target.Draw(sprite); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using dk.via.ftc.dataTier_v2_C.Persistence; namespace dk.via.ftc.dataTier_v2_C.Data { public class DispensaryService : IDispensaryService { private List<Dispensary> dispensaries; private List<DispensaryAdmin> dispensaryAdmins; private FTCDBContext fTCDBContext; public DispensaryService(FTCDBContext context) { fTCDBContext = context; } public async Task<IList<Dispensary>> GetDispensariesAsync() { List<Dispensary> dispensaries; dispensaries = fTCDBContext.Dispensaries.ToList(); await fTCDBContext.SaveChangesAsync(); return dispensaries; } public async Task AddDispensary(Dispensary dispensary) { await fTCDBContext.Dispensaries.AddAsync(dispensary); Console.WriteLine("Registering A Dispensary"+dispensary.DispensaryName); await fTCDBContext.SaveChangesAsync(); } public async Task<DispensaryAdmin> GetDispensaryByUsername(string username) { IQueryable<DispensaryAdmin> da = fTCDBContext.DispensaryAdmins.Where(d => d.Username.Equals(username)); await fTCDBContext.SaveChangesAsync(); return da.FirstOrDefault(); } public async Task AddDispensaryAdmin(DispensaryAdmin dispensaryAdmin) { await fTCDBContext.DispensaryAdmins.AddAsync(dispensaryAdmin); Console.WriteLine(dispensaryAdmin.DispensaryId); await fTCDBContext.SaveChangesAsync(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Threadmill : MonoBehaviour { public bool direction = false; public float speed = 3; private List<GameObject> objectsInTrigger = new List<GameObject>(); private void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.GetComponent<ThreadmillMovable>()) { objectsInTrigger.Add(collision.gameObject); } } private void OnTriggerExit2D(Collider2D collision) { if (collision.gameObject.GetComponent<ThreadmillMovable>()) { objectsInTrigger.Remove(collision.gameObject); } } private void Update() { if (objectsInTrigger.Count > 0) { for (int i = 0; i < objectsInTrigger.Count; i++) { if (!direction) { objectsInTrigger[i].transform.Translate(Vector3.left * speed * Time.deltaTime); }else { objectsInTrigger[i].transform.Translate(Vector3.right * speed * Time.deltaTime); } } } } }
/* * Bungie.Net API * * These endpoints constitute the functionality exposed by Bungie.net, both for more traditional website functionality and for connectivity to Bungie video games and their related functionality. * * OpenAPI spec version: 2.1.1 * Contact: support@bungie.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = BungieNetPlatform.Client.SwaggerDateConverter; namespace BungieNetPlatform.Model { /// <summary> /// Items can have objectives and progression. When you request this block, you will obtain information about any Objectives and progression tied to this item. /// </summary> [DataContract] public partial class DestinyEntitiesItemsDestinyItemObjectivesComponent : IEquatable<DestinyEntitiesItemsDestinyItemObjectivesComponent>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="DestinyEntitiesItemsDestinyItemObjectivesComponent" /> class. /// </summary> /// <param name="Objectives">If the item has a hard association with objectives, your progress on them will be defined here. Objectives are our standard way to describe a series of tasks that have to be completed for a reward..</param> public DestinyEntitiesItemsDestinyItemObjectivesComponent(List<DestinyQuestsDestinyObjectiveProgress> Objectives = default(List<DestinyQuestsDestinyObjectiveProgress>)) { this.Objectives = Objectives; } /// <summary> /// If the item has a hard association with objectives, your progress on them will be defined here. Objectives are our standard way to describe a series of tasks that have to be completed for a reward. /// </summary> /// <value>If the item has a hard association with objectives, your progress on them will be defined here. Objectives are our standard way to describe a series of tasks that have to be completed for a reward.</value> [DataMember(Name="objectives", EmitDefaultValue=false)] public List<DestinyQuestsDestinyObjectiveProgress> Objectives { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class DestinyEntitiesItemsDestinyItemObjectivesComponent {\n"); sb.Append(" Objectives: ").Append(Objectives).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as DestinyEntitiesItemsDestinyItemObjectivesComponent); } /// <summary> /// Returns true if DestinyEntitiesItemsDestinyItemObjectivesComponent instances are equal /// </summary> /// <param name="input">Instance of DestinyEntitiesItemsDestinyItemObjectivesComponent to be compared</param> /// <returns>Boolean</returns> public bool Equals(DestinyEntitiesItemsDestinyItemObjectivesComponent input) { if (input == null) return false; return ( this.Objectives == input.Objectives || this.Objectives != null && this.Objectives.SequenceEqual(input.Objectives) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Objectives != null) hashCode = hashCode * 59 + this.Objectives.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
using UnityEngine; using DragonBones; public class ReplaceDisplayTextureTest : MonoBehaviour { public string dragonBonesName,armatureName,slotName,displayName; [Space] public Texture2D replaceTex; public string replaceSlot; // Use this for initialization void Start () { UnityArmatureComponent unityArmature = GetComponent<UnityArmatureComponent>(); UnityFactory.factory.autoSearch = true; UnityFactory.factory.ReplaceSlotDisplay( dragonBonesName,armatureName,slotName,displayName,unityArmature.armature.GetSlot(replaceSlot), replaceTex,new Material(Shader.Find("Sprites/Default")) ); } // Update is called once per frame void Update () { } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using System.Web; using Umbraco.Web.Mvc; namespace GlobalDevelopment.Controllers { public class RequestSurfaceController : SurfaceController { public void MakeRequest() { } } }
using System.Runtime.Serialization; namespace SearchFoodServer.CompositeClass { [DataContract] public class CompositeCategories { int _idCategorie; string _nomCategorie; [DataMember] public int IdCategorieValue { get { return _idCategorie; } set { _idCategorie = value; } } [DataMember] public string NomCategorieValue { get { return _nomCategorie; } set { _nomCategorie = value; } } } }
using System; namespace iCopy.Model.Response { public class Copier { public string ID { get; set; } public bool Active { get; set; } public string Name { get; set; } public string Description { get; set; } public TimeSpan StartWorkingTime { get; set; } public TimeSpan EndWorkingTime { get; set; } public string Url { get; set; } public string PhoneNumber { get; set; } public int CityId { get; set; } public City City { get; set; } public int CompanyId { get; set; } public Company Company { get; set; } public ApplicationUser User { get; set; } public ProfilePhoto ProfilePhoto { get; set; } public int ApplicationUserId { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AdventureWorks.Services.Common { public interface IFileLoader { Task UploadFile(byte[] bytes); } }
using System; using Android.App; using Android.Content; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; using BoardGamedia.Shared; using BoardGamedia.Adapters; namespace BoardGamedia { [Activity(Label = "BoardGamedia.Android", Icon = "@drawable/icon")] public class SearchActivity : ListActivity { EditText searchQuery; Button searchButton; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); searchQuery = FindViewById<EditText>(Resource.Id.SearchQuery); searchButton = FindViewById<Button>(Resource.Id.SearchButton); searchButton.Click += SearchButtonClick; } private async void SearchButtonClick(object sender, EventArgs e) { var result = await AppController.Instance.Search(searchQuery.Text); ListAdapter = new GameListAdapter(this, result); } } }
using MKModel; using MKService.Messages; using MKService.ModelFactories; using MKService.Updates; using System; using MKService.DefaultModel; namespace MKService.ModelUpdaters { internal class UserSignUpUpdater : ModelUpdaterBase<IUpdatableUserCollection, UserSignUp> { public UserSignUpUpdater( IModelFactoryResolver modelFactoryResolver, IDefaultModel defaultMode) : base(modelFactoryResolver, defaultMode) { } protected override bool UpdateInternal(IUpdatableUserCollection model, UserSignUp message) { UserModel newUserData; try { UserData data = new UserData(); data.UserName = message.UserName; data.Password = message.Password; data.Id = message.Id; newUserData = UserDataDBService.SignUp(data); var newUser = this.ModelFactoryResolver.GetFactory<IUpdatableUser>().Create(); newUser.UserName = newUserData.UserName; newUser.Id = newUserData.Id; model.Users.Add(newUser); } catch (Exception ex) { return false; } return true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Windows.Input; using City_Center.Clases; using City_Center.Models; using City_Center.Page; using City_Center.Services; using GalaSoft.MvvmLight.Command; using Plugin.Share; using Xamarin.Forms; using static City_Center.Models.DestacadosResultado; using static City_Center.Models.GuardaFavoritosResultado; namespace City_Center.ViewModels { public class DestacadosItemViewModel: DestacadosDetalle { #region Services private ApiService apiService; #endregion #region Commands public ICommand VerDetalleCommand { get { return new RelayCommand(VerDetalle); } } private async void VerDetalle() { MainViewModel.GetInstance().DestacadosDetalle = new DetalleDestacadosViewModel(this); await ((MasterPage)Application.Current.MainPage).Detail.Navigation.PushAsync(new DetalleDestacados()); } public ICommand CompartirCommand { get { return new RelayCommand(CompartirUrl); } } private async void CompartirUrl() { Plugin.Share.Abstractions.ShareMessage Compartir = new Plugin.Share.Abstractions.ShareMessage(); Compartir.Text = this.des_descripcion; Compartir.Title = this.des_nombre; Compartir.Url = "https://citycenter-rosario.com.ar/es/show-detail/" + this.des_id + "/" + this.des_nombre; await CrossShare.Current.Share(Compartir); } public ICommand GuardaFavoritoCommand { get { return new RelayCommand(GuardaFavorito); } } private async void GuardaFavorito() { try { bool isLoggedIn = Application.Current.Properties.ContainsKey("IsLoggedIn") ? (bool)Application.Current.Properties["IsLoggedIn"] : false; if (isLoggedIn) { if (this.des_guardado == false) { var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("gua_id_usuario", Application.Current.Properties["IdUsuario"].ToString()), new KeyValuePair<string, string>("gua_id_destacado", Convert.ToString(this.des_id)), }); var response = await this.apiService.Get<GuardaFavoritosReturn>("/guardados", "/store", content); if (!response.IsSuccess) { await Mensajes.Alerta("Ha habido un error en tu solicitud, por favor volvé a intentarlo"); return; } var list = (GuardaFavoritosReturn)response.Result; this.des_guardado = true; this.oculta = false; this.des_id_guardado = list.resultado.gua_id; var actualiza = MainViewModel.GetInstance().listDestacados.resultado.Where(l => l.des_id == this.des_id).FirstOrDefault(); actualiza.des_guardado = true; actualiza.oculta = false; actualiza.des_id_guardado = list.resultado.gua_id; await Mensajes.Alerta("Guardado con éxito"); } else { EliminaFavoritos(); } } else { await Mensajes.Alerta("Es necesario que te registres para completar esta acción"); } } catch (Exception) { await Mensajes.Alerta("Es necesario que te registres para completar esta acción"); } } public ICommand EliminaFavoritosCommand { get { return new RelayCommand(EliminaFavoritos); } } private async void EliminaFavoritos() { try { bool isLoggedIn = Application.Current.Properties.ContainsKey("IsLoggedIn") ? (bool)Application.Current.Properties["IsLoggedIn"] : false; if (isLoggedIn) { if (this.des_guardado == true) { var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("gua_id",Convert.ToString(this.des_id_guardado)), }); var response = await this.apiService.Get<GuardadoGenerico>("/guardados", "/destroy", content); if (!response.IsSuccess) { await Mensajes.Alerta("Ha habido un error en tu solicitud, por favor volvé a intentarlo"); return; } this.des_guardado = false; this.oculta = true; var actualiza = MainViewModel.GetInstance().listDestacados.resultado.Where(l => l.des_id == this.des_id).FirstOrDefault(); actualiza.des_guardado = false; actualiza.oculta = true; // var list = (GuardadoGenerico)response.Result; await Mensajes.Alerta("Guardado eliminado con éxito"); } else { GuardaFavorito(); } } else { await Mensajes.Alerta("Es necesario que te registres para completar esta acción"); } } catch (Exception) { await Mensajes.Alerta("Es necesario que te registres para completar esta acción"); } } #endregion #region Contructors public DestacadosItemViewModel() { this.apiService = new ApiService(); } #endregion } }
namespace PhotographerSystem.Migrations { using Models; using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; internal sealed class Configuration : DbMigrationsConfiguration<PhotographerSystem.PhotographerContext> { public Configuration() { AutomaticMigrationsEnabled = false; } protected override void Seed(PhotographerSystem.PhotographerContext context) { Photographer pesho = new Photographer() { Username = "Pesho", Password = "sdwsfwd", Email = "pesho@pesho.com", RegisterDate = DateTime.Now, Birthday = new DateTime(2001, 01, 02), }; context.Photographers.AddOrUpdate(p => p.Username, pesho); context.SaveChanges(); Picture picture = new Picture() { Title = "demo", Caption = "demo", FileSystemPath = "c::" }; context.Pictures.AddOrUpdate(p => p.Title ,picture); Album plovdiv = new Album() { Name = "Plovdiv", BackgroundColor = "Blue", IsPublic = true, }; plovdiv.Photographers.Add(pesho); context.Albums.AddOrUpdate(a => a.Name, plovdiv); plovdiv.Pictures.Add(picture); Tag town = new Tag() { Name = "#town" }; context.Tags.AddOrUpdate(t => t.Name ,town); town.Albums.Add(plovdiv); context.SaveChanges(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; namespace Ast.Common { public class XmlHelper { public static string ReadXmlValue(string strXml, string node) { string value = ""; try { XmlDocument xmlDocument = new XmlDocument(); xmlDocument.LoadXml(strXml); XmlNode xmlNode = xmlDocument.SelectSingleNode(node); value = xmlNode.InnerText; } catch (Exception ex) { throw ex; } return value; } } }
using System; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using Sample.Domain.Shared; namespace Sample.Tests { public abstract class EventSourcedTestCase<T> where T : AggregateRoot { protected IGiven Given(Guid id, params DomainEvent[] events) { var instance = (T)Activator.CreateInstance(typeof(T), id, events.ToList()); return new TestHelper(instance); } private class TestHelper : IGiven, IWhen, IAndWhen { private readonly T instance; private Exception exception; public TestHelper(T instance) { this.instance = instance; } public IWhen When(Action<T> action) { try { action(instance); } catch (Exception ex) { exception = ex; } return this; } IAndWhen IWhen.Then(params DomainEvent[] events) { Assert.IsNull(exception, "Expected no exception"); Assert.AreEqual(events.Length, instance.UncommittedEvents.Count(), "Expected {0} events", events.Length); Assert.IsTrue(events.Select(e => e.GetType()).SequenceEqual(instance.UncommittedEvents.Select(e => e.GetType()))); return this; } public IAndWhen Then(Action<T> action) { action.Invoke(instance); return this; } public IAndWhen ThenItThrows<T>() { Assert.IsNotNull(exception, "Expected an exception"); Assert.AreEqual(typeof(T), exception.GetType()); return this; } public void And(params DomainEvent[] events) { Assert.IsNull(exception, "Expected no exception"); Assert.AreEqual(events.Length, instance.UncommittedEvents.Count(), "Expected {0} events", events.Length); Assert.IsTrue(events.SequenceEqual(instance.UncommittedEvents)); } public void And(Action<T> action) { action.Invoke(instance); } public void AndItThrows<T1>() { Assert.IsNotNull(exception, "Expected an exception"); Assert.AreEqual(typeof(T), exception.GetType()); } } protected interface IGiven { IWhen When(Action<T> action); } protected interface IWhen { IAndWhen Then(params DomainEvent[] events); IAndWhen Then(Action<T> action); IAndWhen ThenItThrows<T>(); } protected interface IAndWhen { void And(params DomainEvent[] events); void And(Action<T> action); void AndItThrows<T>(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace ReportesCLIN2.Reports { public class Controls { private List<string> resultado { get; set; } public Controls() { this.resultado = new List<string>(); } /// <summary> /// Agrega control tipo fecha /// </summary> /// <param name="Properties"></param> public void AddDate(dynamic Properties) { string control = @"<div class='form-group'><label>{1}</label>&nbsp;<input class='param form-control' type='date' name='{0}'/></div>"; this.resultado.Add(string.Format(control, Properties.name, Properties.label)); } /// <summary> /// Agrega control tipo texto /// </summary> /// <param name="Properties"></param> public void AddTextBox(dynamic Properties) { string control = @"<div class='form-group'><label>{1}</label>&nbsp;<input class='param form-control' type='textbox' name='{0}' value='{2}'/></div>"; this.resultado.Add(string.Format(control, Properties.name, Properties.label, Properties.value)); } /// <summary> /// Retorna todos los controles /// </summary> /// <returns></returns> public string Render() { string render = ""; foreach (var item in this.resultado) { render += string.Format("<div>{0}</div>", item); } return render; } } }
// ===== Enhanced Editor - https://github.com/LucasJoestar/EnhancedEditor ===== // // // Notes: // // ============================================================================ // using System; using UnityEngine; namespace EnhancedEditor { /// <summary> /// <see cref="ScriptableObject"/> used for editor purposes, allowing to write and share /// nicely displayed documents across the project. /// </summary> [CreateAssetMenu(fileName = "DOC_Document", menuName = InternalUtility.MenuPath + "Document", order = InternalUtility.MenuOrder)] public class Document : ScriptableObject { #region Section [Serializable] public class Section { public string Name = string.Empty; public float Spacing = 0f; [Space(10f)] public string Header = string.Empty; [Enhanced, EnhancedTextArea] public string Text = string.Empty; [Enhanced, EnhancedTextArea] public string InfoText = string.Empty; public Texture2D Image = null; [Space(10f)] public string LinkText = string.Empty; public string URL = string.Empty; } #endregion #region Global Members [Section("Document Title")] public string Title = "Document"; public bool _useBuiltInIcon = false; [Enhanced, ShowIf("_useBuiltInIcon", ConditionType.True)] public string IconContent = "UnityLogo"; [Enhanced, ShowIf("_useBuiltInIcon", ConditionType.False), Required] public Texture2D Icon = null; [Section("Sections")] public Section[] Sections = new Section[] { }; #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Erwine.Leonard.T.ExampleWebApplication { public partial class SiteMasterPage : System.Web.UI.MasterPage { private string _defaultTitle = null; public string DefaultTitle { get { if (this._defaultTitle == null) { System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly(); this._defaultTitle = assembly.GetCustomAttributes(typeof(System.Reflection.AssemblyTitleAttribute), false).OfType<System.Reflection.AssemblyTitleAttribute>() .Where(a => !String.IsNullOrWhiteSpace(a.Title)).Select(a => a.Title).DefaultIfEmpty(assembly.FullName).First(); } return this._defaultTitle; } } public string PageTitle { get { if (String.IsNullOrWhiteSpace(this.PageTitleLiteral.Text)) this.PageTitleLiteral.Text = (String.IsNullOrWhiteSpace(this.Page.Title)) ? this.DefaultTitle : this.Page.Title; return this.PageTitleLiteral.Text; } set { this.PageTitleLiteral.Text = (value == null) ? "" : value.Trim(); } } public string MainHeading { get { if (String.IsNullOrWhiteSpace(this.MainHeadingLiteral.Text)) this.MainHeadingLiteral.Text = (String.IsNullOrWhiteSpace(this.Page.Title)) ? this.DefaultTitle : this.Page.Title; return this.MainHeadingLiteral.Text; } set { this.MainHeadingLiteral.Text = (value == null) ? "" : value.Trim(); } } public string SubHeading { get { return this.SubHeadingLiteral.Text; } set { this.SubHeadingLiteral.Text = (value == null) ? "" : value.Trim(); } } public string FooterText { get { return this.FooterTextLiteral.Text; } set { this.FooterTextLiteral.Text = (value == null) ? "" : value.Trim(); } } protected void Page_Load(object sender, EventArgs e) { this.SubHeadingH2.Visible = true; this.FooterTextPanel.Visible = true; } protected void TitleTextLiteral_PreRender(object sender, EventArgs e) { Literal literal = sender as Literal; if (String.IsNullOrWhiteSpace(literal.Text)) literal.Text = (String.IsNullOrWhiteSpace(this.Page.Title)) ? this.DefaultTitle : this.Page.Title; } protected void SubHeadingLiteral_PreRender(object sender, EventArgs e) { this.SubHeadingH2.Visible = !String.IsNullOrWhiteSpace(this.SubHeadingLiteral.Text); } protected void FooterTextLiteral_PreRender(object sender, EventArgs e) { if (!String.IsNullOrWhiteSpace(this.FooterTextLiteral.Text)) return; System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly(); string copyright = assembly.GetCustomAttributes(typeof(System.Reflection.AssemblyCopyrightAttribute), false).OfType<System.Reflection.AssemblyCopyrightAttribute>() .Where(a => !String.IsNullOrWhiteSpace(a.Copyright)).Select(a => a.Copyright).FirstOrDefault(); if (copyright == null) this.FooterTextPanel.Visible = false; else this.FooterTextLiteral.Text = Server.HtmlEncode(copyright); } } }
using System; using System.Diagnostics; using System.Threading.Tasks; using CitizenFX.Core; using ZentryAnticheat.Client.Controller; using ZentryAnticheat.Client.Scans; namespace ZentryAnticheat.Client { class Main : BaseScript { public Main() { this.EventHandlers.Add("scanEntitys", (Delegate) new Action(new ScanEntitys(ScanEnum.full).Scan)); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GrabCloth : MonoBehaviour { public Cloth cloth; Mesh clothMesh; int grabVertex; bool isGrabbing; Vector3 lastMousePos; // Use this for initialization void Start () { Debug.Assert(cloth != null); clothMesh = cloth.GetComponent<SkinnedMeshRenderer>().sharedMesh; Debug.Assert(clothMesh != null); } // Update is called once per frame void Update () { float minDist = Mathf.Infinity; int minVertex = -1; Vector3 mouseScreen = Input.mousePosition; for(int i = 0; i < clothMesh.vertexCount; i++) { // Find closest point to mouse Vector3 vertex = cloth.transform.TransformPoint(clothMesh.vertices[i]); Vector3 vertexScreen = Camera.main.WorldToScreenPoint(vertex); float dist = Vector3.SqrMagnitude(vertexScreen - mouseScreen); if(dist < minDist) { minDist = dist; minVertex = i; } } Debug.LogFormat("Closest vertex: {0} ({1}m)", minVertex, minDist); Debug.DrawRay(Camera.main.transform.position, cloth.transform.TransformPoint(clothMesh.vertices[minVertex]) - Camera.main.transform.position, Color.red); Color[] colors = new Color[clothMesh.vertexCount]; for(int i = 0; i < clothMesh.vertexCount; i++) { colors[i] = Color.black; } colors[minVertex] = Color.red; clothMesh.colors = colors; if (Input.GetMouseButtonDown(0)) { isGrabbing = true; grabVertex = minVertex; } if (Input.GetMouseButtonUp(0)) { isGrabbing = false; grabVertex = -1; } Vector3 mouseWorld = Camera.main.ScreenToWorldPoint(mouseScreen); if(isGrabbing) { Vector3 dmouse = mouseWorld - lastMousePos; Vector3[] verts = clothMesh.vertices; verts[grabVertex] += dmouse; clothMesh.vertices = verts; } lastMousePos = mouseWorld; } }
namespace Triton.Game.Mapping { using ns25; using ns26; using System; using System.Collections.Generic; using Triton.Game; using Triton.Game.Mono; [Attribute38("Downloader")] public class Downloader : MonoBehaviour { public Downloader(IntPtr address) : this(address, "Downloader") { } public Downloader(IntPtr address, string className) : base(address, className) { } public bool AllLocalizedAudioBundlesDownloaded() { return base.method_11<bool>("AllLocalizedAudioBundlesDownloaded", Array.Empty<object>()); } public void Awake() { base.method_8("Awake", Array.Empty<object>()); } public List<string> BundlesMissing() { Class268 class2 = base.method_14<Class268>("BundlesMissing", Array.Empty<object>()); if (class2 != null) { return class2.method_25(); } return null; } public List<string> BundlesToDownloadForLocale() { Class268 class2 = base.method_14<Class268>("BundlesToDownloadForLocale", Array.Empty<object>()); if (class2 != null) { return class2.method_25(); } return null; } public static string BundleURL(string fileName) { object[] objArray1 = new object[] { fileName }; return MonoClass.smethod_12(TritonHs.MainAssemblyPath, "", "Downloader", "BundleURL", objArray1); } public void DeleteLocalizedBundles() { base.method_8("DeleteLocalizedBundles", Array.Empty<object>()); } public void DownloadLocalizedBundles() { base.method_9("DownloadLocalizedBundles", new Class272.Enum20[0], Array.Empty<object>()); } public void DownloadNextFile() { base.method_8("DownloadNextFile", Array.Empty<object>()); } public static Downloader Get() { return MonoClass.smethod_15<Downloader>(TritonHs.MainAssemblyPath, "", "Downloader", "Get", Array.Empty<object>()); } public static int GetTryCount() { return MonoClass.smethod_14<int>(TritonHs.MainAssemblyPath, "", "Downloader", "GetTryCount", Array.Empty<object>()); } public static string NextBundleURL(string fileName) { object[] objArray1 = new object[] { fileName }; return MonoClass.smethod_12(TritonHs.MainAssemblyPath, "", "Downloader", "NextBundleURL", objArray1); } public void OnDestroy() { base.method_8("OnDestroy", Array.Empty<object>()); } public void Start() { base.method_8("Start", Array.Empty<object>()); } public void WillReset() { base.method_8("WillReset", Array.Empty<object>()); } public List<string> m_bundlesToDownload { get { Class268 class2 = base.method_3<Class268>("m_bundlesToDownload"); if (class2 != null) { return class2.method_25(); } return null; } } public float m_downloadStartTime { get { return base.method_2<float>("m_downloadStartTime"); } } public bool m_hasShownInternalFailureAlert { get { return base.method_2<bool>("m_hasShownInternalFailureAlert"); } } public bool m_isDownloading { get { return base.method_2<bool>("m_isDownloading"); } } public static string m_remoteUri { get { return MonoClass.smethod_8(TritonHs.MainAssemblyPath, "", "Downloader", "m_remoteUri"); } } public static string m_remoteUriCN { get { return MonoClass.smethod_8(TritonHs.MainAssemblyPath, "", "Downloader", "m_remoteUriCN"); } } public static int m_remoteUriCNIndex { get { return MonoClass.smethod_6<int>(TritonHs.MainAssemblyPath, "", "Downloader", "m_remoteUriCNIndex"); } } } }
using Newtonsoft.Json; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace SkillsGardenApi.Models { public class WorkoutExercise { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } public int ExerciseId { get; set; } public int WorkoutId { get; set; } [JsonIgnore] public virtual Workout Workout { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Navigation; using Microsoft.Phone.Controls; using Microsoft.Phone.Shell; using Microsoft.Phone.BackgroundTransfer; using System.IO.IsolatedStorage; using System.Collections.ObjectModel; namespace AudioBookBeta { public partial class LoadFile : PhoneApplicationPage { IEnumerable<BackgroundTransferRequest> transferRequests; ObservableCollection<AudioBookTransfer> audioBookTransfers; // Booleans for tracking if any transfers are waiting for user // action. bool WaitingForExternalPower; bool WaitingForExternalPowerDueToBatterySaverMode; bool WaitingForNonVoiceBlockingNetwork; bool WaitingForWiFi; public LoadFile() { audioBookTransfers = new ObservableCollection<AudioBookTransfer>(); using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication()) { if (!isoStore.DirectoryExists("/shared/transfers")) { isoStore.CreateDirectory("/shared/transfers"); } } InitializeComponent(); } private void UpdateUI() { // Update the list of transfer requests UpdateRequestsList(); foreach (var transfer in transferRequests) { } // Update the TransferListBox with the list of transfer requests. TransferListBox.ItemsSource = audioBookTransfers; // If there are 1 or more transfers, hide the "no transfers" // TextBlock. IF there are zero transfers, show the TextBlock. if (TransferListBox.Items.Count > 0) { EmptyTextBlock.Visibility = Visibility.Collapsed; } else { EmptyTextBlock.Visibility = Visibility.Visible; } LoadForTextBlock.Text = "Loading for: " + App.player.selectedBook.BookTitle; } private void InitialTransferStatusCheck() { UpdateRequestsList(); foreach (var transfer in transferRequests) { transfer.TransferStatusChanged += new EventHandler<BackgroundTransferEventArgs>(transfer_TransferStatusChanged); transfer.TransferProgressChanged += new EventHandler<BackgroundTransferEventArgs>(transfer_TransferProgressChanged); ProcessTransfer(transfer); } /* if (WaitingForExternalPower) { MessageBox.Show("You have one or more file transfers waiting for external power. Connect your device to external power to continue transferring."); } if (WaitingForExternalPowerDueToBatterySaverMode) { MessageBox.Show("You have one or more file transfers waiting for external power. Connect your device to external power or disable Battery Saver Mode to continue transferring."); } if (WaitingForNonVoiceBlockingNetwork) { MessageBox.Show("You have one or more file transfers waiting for a network that supports simultaneous voice and data."); } if (WaitingForWiFi) { MessageBox.Show("You have one or more file transfers waiting for a WiFi connection. Connect your device to a WiFi network to continue transferring."); }*/ } private void ProcessTransfer(BackgroundTransferRequest transfer) { switch (transfer.TransferStatus) { case TransferStatus.Completed: // If the status code of a completed transfer is 200 or 206, the // transfer was successful if (transfer.StatusCode == 200 || transfer.StatusCode == 206) { // Remove the transfer request in order to make room in the // queue for more transfers. Transfers are not automatically // removed by the system. RemoveTransferRequest(transfer.RequestId); string filename = transfer.Tag.Substring(transfer.Tag.LastIndexOf("#") + 1); // In this example, the downloaded file is moved into the root // Isolated Storage directory using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication()) { if (isoStore.FileExists(filename)) { isoStore.DeleteFile(filename); } isoStore.MoveFile(transfer.DownloadLocation.OriginalString, filename); } App.player.selectedBook.addFile(filename, true); } else { // This is where you can handle whatever error is indicated by the // StatusCode and then remove the transfer from the queue. RemoveTransferRequest(transfer.RequestId); if (transfer.TransferError != null) { // Handle TransferError if one exists. } } break; case TransferStatus.WaitingForExternalPowerDueToBatterySaverMode: WaitingForExternalPowerDueToBatterySaverMode = true; break; case TransferStatus.WaitingForWiFi: WaitingForWiFi = true; break; } } void transfer_TransferStatusChanged(object sender, BackgroundTransferEventArgs e) { ProcessTransfer(e.Request); UpdateUI(); } void transfer_TransferProgressChanged(object sender, BackgroundTransferEventArgs e) { UpdateUI(); } private void CancelAllButton_Click(object sender, EventArgs e) { // Loop through the list of transfer requests foreach (var transfer in BackgroundTransferService.Requests) { RemoveTransferRequest(transfer.RequestId); } // Refresh the list of file transfer requests. UpdateUI(); } private Boolean validURL(string url) { if (url == null || url == "") return false; if (url == "http://") return false; Uri uriResult; bool result = Uri.TryCreate(url, UriKind.Absolute, out uriResult) && uriResult.Scheme == Uri.UriSchemeHttp; if (!result) return false; return true; } private string createUniqueFilename(string url) { string file = url.Substring(url.LastIndexOf("/") + 1); string ext = file.Substring(file.LastIndexOf(".") + 1); string toHash = url + DateTime.UtcNow; //combine URL and datetime int hash = toHash.GetHashCode(); //hash it return hash + "." + ext; //{hash}.{ext} => like abcdef1234567890.mp3 } private void addButton_Click(object sender, RoutedEventArgs e) { // Check to see if the maximum number of requests per app has been exceeded. if (BackgroundTransferService.Requests.Count() >= 25) { // Note: Instead of showing a message to the user, you could store the // requested file URI in isolated storage and add it to the queue later. MessageBox.Show("The maximum number of background file transfer requests for this application has been exceeded. "); return; } // Get the URI of the file to be transferred from the Tag property // of the button that was clicked. string transferFileName = UrlTextBox.Text; if (!validURL(transferFileName)) { MessageBox.Show("Invalid URL"); return; } Uri transferUri = new Uri(Uri.EscapeUriString(transferFileName), UriKind.RelativeOrAbsolute); // Create the new transfer request, passing in the URI of the file to // be transferred. BackgroundTransferRequest transferRequest = new BackgroundTransferRequest(transferUri); transferRequest.TransferStatusChanged += new EventHandler<BackgroundTransferEventArgs>(transfer_TransferStatusChanged); transferRequest.TransferProgressChanged += new EventHandler<BackgroundTransferEventArgs>(transfer_TransferProgressChanged); // Set the transfer method. GET and POST are supported. transferRequest.Method = "GET"; // Get the file name from the end of the transfer URI and create a local URI // in the "transfers" directory in isolated storage. string downloadFile = createUniqueFilename(transferFileName); Uri downloadUri = new Uri("shared/transfers/" + downloadFile, UriKind.RelativeOrAbsolute); transferRequest.DownloadLocation = downloadUri; // Pass custom data with the Tag property. In this example, the friendly name // is passed. transferRequest.Tag = transferFileName.Substring(transferFileName.LastIndexOf("/") + 1) + "#" + downloadFile; transferRequest.TransferPreferences = TransferPreferences.AllowBattery; // If the Wi-Fi-only check box is not checked, then set the TransferPreferences // to allow transfers over a cellular connection. /*if (wifiOnlyCheckbox.IsChecked == false) { transferRequest.TransferPreferences = TransferPreferences.AllowCellular; } if (externalPowerOnlyCheckbox.IsChecked == false) { transferRequest.TransferPreferences = TransferPreferences.AllowBattery; } if (wifiOnlyCheckbox.IsChecked == false && externalPowerOnlyCheckbox.IsChecked == false) { transferRequest.TransferPreferences = TransferPreferences.AllowCellularAndBattery; } */ // Add the transfer request using the BackgroundTransferService. Do this in // a try block in case an exception is thrown. try { BackgroundTransferService.Add(transferRequest); } catch (InvalidOperationException ex) { MessageBox.Show("Unable to add background transfer request. " + ex.Message); } catch (Exception) { MessageBox.Show("Unable to add background transfer request."); } UpdateUI(); } private void RemoveTransferRequest(string transferID) { // Use Find to retrieve the transfer request with the specified ID. BackgroundTransferRequest transferToRemove = BackgroundTransferService.Find(transferID); // Try to remove the transfer from the background transfer service. try { BackgroundTransferService.Remove(transferToRemove); } catch (Exception e) { // Handle the exception. } } private void CancelButton_Click(object sender, EventArgs e) { // The ID for each transfer request is bound to the // Tag property of each Remove button. string transferID = ((Button)sender).Tag as string; // Delete the transfer request RemoveTransferRequest(transferID); // Refresh the list of file transfers UpdateUI(); } protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) { // Reset all of the user action Booleans on page load. WaitingForExternalPower = false; WaitingForExternalPowerDueToBatterySaverMode = false; WaitingForNonVoiceBlockingNetwork = false; WaitingForWiFi = false; // When the page loads, refresh the list of file transfers. InitialTransferStatusCheck(); UpdateUI(); } private void UpdateRequestsList() { // The Requests property returns new references, so make sure that // you dispose of the old references to avoid memory leaks. if (transferRequests != null) { foreach (var request in transferRequests) { request.Dispose(); } } audioBookTransfers.Clear(); transferRequests = BackgroundTransferService.Requests; foreach (var v in transferRequests) { AudioBookTransfer t = new AudioBookTransfer(v); audioBookTransfers.Add(t); } } } }
using System; using System.Collections.Generic; using System.Data.SQLite; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace SmartClass { class Util { public static bool checkId(string id) { if (id.Length == 0 || id.Length > 10) return false; try { int.Parse(id); } catch (Exception) { return false; } return true; } public static bool checkName(string name) { if (name.Length == 0 || name.Length > 10) return false; return true; } public static bool checkGender(string gender) { if (gender != "男" && gender != "女") return false; return true; } public static bool checkPhonenum(string phone_num) { if (phone_num.Length != 11) return false; try { Int64.Parse(phone_num); } catch (Exception) { return false; } return true; } public static bool checkBalance(string balance) { try { int.Parse(balance); } catch (Exception) { return false; } return true; } public static bool checkWorkyear(string workyear) { try { int.Parse(workyear); } catch (Exception) { return false; } return true; } public static bool checkSubject(string subject) { if (subject != "语文" && subject != "数学" && subject != "英语" && subject != "物理" && subject != "化学" && subject != "生物" && subject != "政治" && subject != "地理" && subject != "历史") return false; return true; } public static bool checkExpense(string expense) { try { int.Parse(expense); } catch (Exception) { return false; } return true; } public static bool checkMaxcnt(string maxcnt) { try { int.Parse(maxcnt); } catch (Exception) { return false; } return true; } public static bool checkTime(string time) { //todo return true; } public static bool checkRecharge(string recharge) { try { int.Parse(recharge); } catch (Exception) { return false; } return true; } public static void createDb() { SQLiteConnection conn = new SQLiteConnection("Data Source =" + Environment.CurrentDirectory + "/" + "xxoo.db"); try { conn.Open(); string sql = "CREATE TABLE IF NOT EXISTS kv_tbl(key varchar(64) primary key, value varchar(64));";//建表语句 SQLiteCommand cmdCreateTable = new SQLiteCommand(sql, conn); cmdCreateTable.ExecuteNonQuery(); } catch (System.Data.SQLite.SQLiteException ex) { MessageBox.Show(ex.ToString()); } conn.Close(); } public static string getValue(string key) { string val = ""; SQLiteConnection conn = new SQLiteConnection("Data Source =" + Environment.CurrentDirectory + "/" + "xxoo.db"); try { conn.Open(); string sql = "select * from kv_tbl where key='" + key + "';"; SQLiteCommand cmdQ = new SQLiteCommand(sql, conn); SQLiteDataReader reader = cmdQ.ExecuteReader(); if (reader.HasRows) { reader.Read(); val = reader.GetString(1); } } catch (System.Data.SQLite.SQLiteException ex) { MessageBox.Show(ex.ToString()); } conn.Close(); return val; } public static bool saveValue(string key, string val) { SQLiteConnection conn = new SQLiteConnection("Data Source =" + Environment.CurrentDirectory + "/" + "xxoo.db"); try { SQLiteCommand cmdInsert = new SQLiteCommand(conn); if (getValue(key) == "") { cmdInsert.CommandText = "INSERT INTO kv_tbl VALUES('" + key + "', '" + val + "')"; } else { cmdInsert.CommandText = "UPDATE kv_tbl SET value='" + val + "' where key='" + key + "'"; } conn.Open(); cmdInsert.ExecuteNonQuery(); } catch (System.Data.SQLite.SQLiteException ex) { conn.Close(); MessageBox.Show(ex.ToString()); return false; } conn.Close(); return true; } } }
/****************************************************************************** * * HL7SDK Base object/interface definitions * *****************************************************************************/ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; using System.Runtime.InteropServices; using System.ComponentModel; using System.Xml.Serialization; using System.IO; namespace HL7SDK { [Guid("263A5B3F-E6D4-4001-91BA-B74AE3AC4D5B")] public interface IHL73Object { [DispId(0)] string ToString(); [DispId(1000)] bool Equals([MarshalAs(UnmanagedType.IDispatch)] Object obj); [DispId(1001)] [Browsable(false)] string Xml { get; } [DispId(1002)] [Browsable(false)] bool Lazy { get; set; } [DispId(2000)] [Browsable(false)] IHL73ObjectCollection ChildObjects { get; } [ComVisible(false)] IHL73Object Clone(); [ComVisible(false)] [Browsable(false)] IHL73Object Parent { get; } } [Guid("47FC5972-E951-433A-A68C-5FC5E84E0E01")] public interface IHL73ObjectCollection : IEnumerable { [DispId(1)] int Count { get; } [DispId(0)] IHL73Object this[int index] { get; } [DispId(-4)] new IEnumerator GetEnumerator(); } [Guid("7806A891-1FED-48D9-B072-33C071F0D732")] [ClassInterface(ClassInterfaceType.None)] public abstract class HL73Object : IHL73Object, INotifyPropertyChanged { internal protected Object element; internal protected HL73Object parent; bool lazy = true; protected HL73Object() { OnCreate(); } public virtual IHL73Object Clone() { if (element == null) throw new InvalidOperationException("Element is unassigned."); if (element.GetType().IsAbstract) throw new InvalidOperationException("HL7 data type is abstract and cannot be cloned."); var myType = this.GetType(); var myCopy = Activator.CreateInstance(myType); Object elementCopy = null; XmlSerializer ser = new XmlSerializer(this.element.GetType(), Constants.URN_HL7); using (var stream = new MemoryStream()) { ser.Serialize(stream, this.element); stream.Position = 0; elementCopy = ser.Deserialize(stream); } ((HL73Object)myCopy).element = elementCopy; ((HL73Object)myCopy).parent = null; return myCopy as IHL73Object; } internal protected virtual void Attach(HL73Object parent) { this.parent = parent; } internal protected virtual void Detach() { this.parent = null; } public event PropertyChangedEventHandler PropertyChanged; [Browsable(false)] public virtual IHL73ObjectCollection ChildObjects { get { return new HL73ObjectCollection(new IHL73Object[0]); } } [Browsable(false)] public virtual bool Lazy { get { if (parent == null) return this.lazy; return parent.Lazy; } set { lazy = value; } } [Browsable(false)] public abstract string Xml { get; } [Browsable(false)] protected Object Element { get { return element; } } public override int GetHashCode() { return base.GetHashCode(); } public override bool Equals(object obj) { if (obj is HL73Object) return Object.ReferenceEquals(((HL73Object)obj).element, this.element); return base.Equals(obj); } protected virtual void OnCreate() { } protected void RaisePropertyChanged(object sender, PropertyChangedEventArgs e) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged != null)) { propertyChanged(this, e); } } [Browsable(false)] public virtual IHL73Object Parent { get { return this.parent; } } } internal class HL73ObjectCollection : IHL73ObjectCollection { internal HL73ObjectCollection(IEnumerable<IHL73Object> elements) { this.elements = elements; } private IEnumerable<IHL73Object> elements; public int Count { get { return elements.Count(); } } public IHL73Object this[int index] { get { return elements.ToArray()[index]; } } public IEnumerator GetEnumerator() { return elements.GetEnumerator(); } } }
using System; using System.Collections.Generic; using System.Text; namespace Telephony { public interface IBrowseable { public string Browse(string website); } }
using UnityEngine; using System.Collections; using UnityEngine.SceneManagement; public class LogoTransition : MonoBehaviour { public GameObject target; private float moveSpeed = 6.0f; private bool canLoading = true; void Update() { if (canLoading) { Vector3 pos = target.gameObject.transform.position; pos.x += moveSpeed * Time.deltaTime; target.gameObject.transform.position = new Vector3(pos.x, pos.y, pos.z); if (pos.x >= 15.0f) { LoadNextScene(); canLoading = false; } } if (SceneManager.sceneCount > 1) { // SceneManager.UnloadScene("Logo"); } } public void LoadNextScene() { SceneManager.LoadSceneAsync("StageSelect"); // SceneManager.LoadSceneAsync("GamePlay", LoadSceneMode.Additive); } }
/******************************************************************** * FulcrumWeb RAD Framework - Fulcrum of your business * * Copyright (c) 2002-2010 FulcrumWeb, ALL RIGHTS RESERVED * * * * THE SOURCE CODE CONTAINED WITHIN THIS FILE AND ALL RELATED * * FILES OR ANY PORTION OF ITS CONTENTS SHALL AT NO TIME BE * * COPIED, TRANSFERRED, SOLD, DISTRIBUTED, OR OTHERWISE MADE * * AVAILABLE TO OTHER INDIVIDUALS WITHOUT EXPRESS WRITTEN CONSENT * * AND PERMISSION FROM FULCRUMWEB. CONSULT THE END USER LICENSE * * AGREEMENT FOR INFORMATION ON ADDITIONAL RESTRICTIONS. * ********************************************************************/ using System.Collections.Generic; using System.Xml; using System.Data; using Framework.Utils; namespace Framework.Metadata { /// <summary> /// Class to read and hold information about application main menu. /// </summary> public class CxMainMenuMetadata : CxMetadataCollection { //---------------------------------------------------------------------------- protected IList<CxMainMenuItemMetadata> m_Items = new List<CxMainMenuItemMetadata>(); // First-level menu items protected Dictionary<string, CxMainMenuItemMetadata> m_AllItems = new Dictionary<string, CxMainMenuItemMetadata>(); // All menu items (with IDs as keys) protected DataTable m_DataTable = null; // Data table for grid lookups //---------------------------------------------------------------------------- /// <summary> /// Constructor. /// </summary> /// <param name="holder">metadata holder</param> /// <param name="doc">XML doc to read metadata from</param> public CxMainMenuMetadata(CxMetadataHolder holder, XmlDocument doc) : base(holder, doc) { } //---------------------------------------------------------------------------- /// <summary> /// Loads metadata collection from the XML document. /// </summary> /// <param name="doc">document to load data from</param> override protected void Load(XmlDocument doc) { base.Load(doc); XmlElement menuItemsElement = (XmlElement) doc.DocumentElement.SelectSingleNode("menu_items"); ReadMenuLevel(menuItemsElement, m_Items); } //------------------------------------------------------------------------- /// <summary> /// Reads menu items lying under the given node and adds them into the given list. /// Then tries to deep menu structure recursively. /// </summary> /// <param name="itemsElement">"menu_items" element menu items are lying under</param> /// <param name="items">list to all created menu items</param> protected void ReadMenuLevel(XmlElement itemsElement, IList<CxMainMenuItemMetadata> items) { foreach (XmlElement element in itemsElement.SelectNodes("menu_item")) { CxMainMenuItemMetadata item = new CxMainMenuItemMetadata(Holder, element); items.Add(item); m_AllItems.Add(item.Id, item); XmlElement subItemsElement = (XmlElement) element.SelectSingleNode("menu_items"); if (subItemsElement != null) { ReadMenuLevel(subItemsElement, item.Items); } } } //---------------------------------------------------------------------------- /// <summary> /// First-level menu items. /// </summary> public IList<CxMainMenuItemMetadata> Items { get { return m_Items; } } //---------------------------------------------------------------------------- /// <summary> /// Menu item with the given ID. /// </summary> public CxMainMenuItemMetadata this[string id] { get { if (m_AllItems.ContainsKey(id.ToUpper())) return m_AllItems[id.ToUpper()]; else throw new ExMetadataException(string.Format("Main menu item with ID=\"{0}\" not defined", id)); } } //---------------------------------------------------------------------------- /// <summary> /// Finds menu item that represents the given entity usage. /// </summary> /// <param name="entityUsageId">ID of the entity usage to find</param> /// <returns>menu item that represents the given entity usage or null if not found</returns> public CxMainMenuItemMetadata FindItemForEntityUsage(string entityUsageId) { CxEntityUsageMetadata entityUsage = Holder.EntityUsages[entityUsageId]; foreach (string key in m_AllItems.Keys) { CxMainMenuItemMetadata menuItem = m_AllItems[key]; if (CxUtils.NotEmpty(menuItem.EntityUsageId) && (menuItem.EntityUsageId == entityUsageId || menuItem.EntityUsageId == entityUsage.MainMenuEntityUsageId)) { return menuItem; } } return null; } //---------------------------------------------------------------------------- /// <summary> /// Returns data table for grid lookups. /// </summary> /// <returns>data table for grid lookups</returns> public DataTable GetDataTable() { if (m_DataTable == null) { m_DataTable = new DataTable(); m_DataTable.Columns.Add("ID", typeof(string)); m_DataTable.Columns.Add("Name", typeof(string)); foreach (string id in m_AllItems.Keys) { CxMainMenuItemMetadata menuItem = m_AllItems[id]; m_DataTable.Rows.Add(new object[] {id, menuItem.Caption}); } } return m_DataTable; } //---------------------------------------------------------------------------- } }
using TQVaultAE.Domain.Entities; namespace TQVaultAE.Domain.Contracts.Providers { public interface IArzFileProvider { /// <summary> /// Gets the DBRecord for a particular ID. /// </summary> /// <param name="recordId">string ID of the record will be normalized internally</param> /// <returns>DBRecord corresponding to the string ID.</returns> DBRecordCollection GetItem(ArzFile file, RecordId recordId); /// <summary> /// Gets the list of keys from the recordInfo dictionary. /// </summary> /// <returns>string array holding the sorted list</returns> RecordId[] GetKeyTable(ArzFile file); /// <summary> /// Gets a database record without adding it to the cache. /// </summary> /// <remarks> /// The Item property caches the DBRecords, which is great when you are only using a few 100 (1000?) records and are requesting /// them many times. Not great if you are looping through all the records as it eats alot of memory. This method will create /// the record on the fly if it is not in the cache so when you are done with it, it can be reclaimed by the garbage collector. /// Great for when you want to loop through all the records for some reason. It will take longer, but use less memory. /// </remarks> /// <param name="recordId">String ID of the record. Will be normalized internally.</param> /// <returns>Decompressed RecordInfo record</returns> DBRecordCollection GetRecordNotCached(ArzFile file, RecordId recordId); /// <summary> /// Reads the ARZ file. /// </summary> /// <returns>true on success</returns> bool Read(ArzFile file); } }
using System; using System.Collections.Generic; namespace SheMediaConverterClean.Infra.Data.Models { public partial class BurnMedia { public int BurnMediaId { get; set; } public string DiscSize { get; set; } public string Name { get; set; } } }
using System.IO; namespace FlWaspMigrator.Support { public class FileSystem : IFileSystem { public Stream OpenRead(string fileName) => File.OpenRead(fileName); public Stream OpenWrite(string fileName) => File.OpenWrite(fileName); } }
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using WebAPI_GraphQL_DotNetCore.Relation; namespace WebAPI_GraphQL_DotNetCore.Model { public class ApplicationContext : DbContext { public ApplicationContext() { } public ApplicationContext(DbContextOptions<ApplicationContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { #region FIELDMAP //modelBuilder.Entity<FieldMap>().HasKey(x => new { x.SourceEntityID, x.TargetEntityID, x.SourceField, x.TargetField }); //modelBuilder.Entity<FieldMap>().HasOne(x => x.SourceEntity).WithMany().HasForeignKey(p => new { p.SourceEntityID }); //modelBuilder.Entity<FieldMap>().HasOne(x => x.TargetEntity).WithMany().HasForeignKey(p => new { p.TargetEntityID }); //modelBuilder.Entity<FieldMap>().HasOne(x => x.SourceFields).WithMany().HasForeignKey(p => new { p.SourceField }); //modelBuilder.Entity<FieldMap>().HasOne(x => x.TargetFields).WithMany().HasForeignKey(p => new { p.TargetField }); #endregion } public virtual DbSet<Artist> Artist { get; set; } } }
namespace Checkout.Payment.Processor.Seedwork.Models { public enum DomainNotificationType { Error, BusinessViolation } }
using System; using PbStore.Domain.Pedidos; using PbStore.Domain.Pedidos.ObjetosValor; using PbStore.Domain.Pedidos.Repositorios; namespace UnitTestProject1.Mocks { public class RepositorioCliente : IRepositorioCliente { public Cliente Obter(Guid id) { var nome = new Nome("André", "Baltieri"); var email = new Email("contato@andrebaltieri.net"); var documento= new CPF("12345678901"); var cliente = new Cliente(nome, email, documento, null, "", DateTime.Now); return cliente; } } }
// Copyright (c) Microsoft Corporation. All Rights Reserved. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text.RegularExpressions; namespace Microsoft.DataPipeline.Deployment.Workflow.Services { public class ServiceMappings { readonly string deploymentType; readonly string location; readonly string clusterName; readonly string useraliasPrivateDeployment; public const string BaseNamePostfix = "-base"; const string DefaultLocation = "WestUS"; const string DefaultClusterName = "adfgated"; const string DefaultLabAccount = "_sqlbld"; static readonly Dictionary<string, string> deploymentType2BaseConfig = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { { "dev", "MonitoringDev" }, { "dev2","MonitoringDev2" }, { "bvt", "MonitoringBVT" }, { "int", "MonitoringIntCommon" }, { "prod", "MonitoringProdCommon" }, }; static readonly HashSet<string> locations = new HashSet<string>(new string[] { "WestUS", "EastUS", }, StringComparer.OrdinalIgnoreCase); static readonly string[] devSubscriptions = new string[] { "dev", "dev2", }; static readonly HashSet<string> bvtSubscriptions = new HashSet<string>(new string[] { "bvt", }, StringComparer.OrdinalIgnoreCase); public static IEnumerable<string> AvailableBaseConfigs { get { foreach (var config in deploymentType2BaseConfig.Values) { if (config.Contains("{0}")) { foreach (var loc in locations) { yield return FormatConfig(config, loc); } } else { yield return config; } } } } public string BaseConfigName { get { var adjustedDeplType = SpreadDevSubscriptions(this.deploymentType, this.UserAlias); string baseConfig = ValidateDeploymentType(adjustedDeplType); if (baseConfig.Contains("{0}")) { baseConfig = FormatConfig(baseConfig, this.location); } return baseConfig + BaseNamePostfix; } } public string DeploymentName { get { return IsPrivateDeployment ? UserAlias + this.clusterName : this.clusterName; } } public bool IsPrivateDeployment { get { return !string.IsNullOrEmpty(this.useraliasPrivateDeployment); } } public string UserAlias { get { var normalizedAlias = this.IsPrivateDeployment ? this.useraliasPrivateDeployment : DefaultLabAccount; // user alias is also used to construct hosted service and storage account names, remove invalid characters return normalizedAlias.Replace("_", "").Replace("-", "").ToLower(CultureInfo.CurrentCulture).Trim(); } } public ServiceMappings(string deploymentType, string location = DefaultLocation, string clusterName = DefaultClusterName, string userAliasPrivateDeployment = null) { if (!locations.Contains(location)) { throw Error.ArgumentException("location", "{0} is not a valid location: {1}", location, string.Join(", ", locations)); } ValidateDeploymentType(deploymentType); this.deploymentType = deploymentType; this.location = location; this.clusterName = clusterName; this.useraliasPrivateDeployment = userAliasPrivateDeployment; ValidateResultingReploymentName(); } void ValidateResultingReploymentName() { var deploymentName = DeploymentName; // storage name rules are more restrictive than hosted service naming rules // see https://msdn.microsoft.com/en-us/library/hh264518.aspx // 3 to 24 char in length; numbers and lowercase letters only if (!Regex.IsMatch(deploymentName, @"^[a-z0-9]{3,24}$")) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Resulting DeploymentName is not a valid storage and hosted service name: {0}")); } } string ValidateDeploymentType(string deploymentType) { string baseConfig; if (!deploymentType2BaseConfig.TryGetValue(deploymentType, out baseConfig)) { throw Error.ArgumentException("deploymentType", "{0} is not a valid deploymentType", deploymentType); } return baseConfig; } static string FormatConfig(string baseConfig, string location) { return string.Format(CultureInfo.CurrentCulture, baseConfig, location.Trim()); } static string SpreadDevSubscriptions(string deploymentType, string userAlias) { var alias = userAlias.Trim(); if (devSubscriptions.Contains(deploymentType, StringComparer.OrdinalIgnoreCase)) { // very simple algorithm: split based on starting letter of alias. Our team aliases divide pretty well // around the middle of the alphabet, subject to periodic review. return (alias.First() <= 'j') ? devSubscriptions[0] : devSubscriptions[1]; } else { return deploymentType; } } } }
using System; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using System.Xml.Linq; using System.Linq; using System.Windows.Resources; using System.Collections.Generic; using Tff.Panzer.Models.Army; namespace Tff.Panzer.Factories.Army { public class EquipmentGroupFactory { public List<EquipmentGroup> EquipmentGroup { get; private set; } public EquipmentGroupFactory() { EquipmentGroup = new List<EquipmentGroup>(); Uri uri = new Uri(Constants.EquipmentGroupDataPath, UriKind.Relative); XElement applicationXml; StreamResourceInfo xmlStream = Application.GetResourceStream(uri); applicationXml = XElement.Load(xmlStream.Stream); var data = from wz in applicationXml.Descendants("EquipmentGroup") select wz; EquipmentGroup equipmentGroup = null; foreach (var d in data) { equipmentGroup = new EquipmentGroup(); equipmentGroup.EquipmentGroupId = (Int32)d.Element("EquipmentGroupId"); equipmentGroup.EquipmentGroupDescription = (String)d.Element("EquipmentGroupDesc"); EquipmentGroup.Add(equipmentGroup); } } public EquipmentGroup GetEquipmentGroup(int equipmentGroupId) { EquipmentGroup equipmentGroup = (from ec in this.EquipmentGroup where ec.EquipmentGroupId == equipmentGroupId select ec).First(); return equipmentGroup; } } }
namespace OmniSharp.Extensions.LanguageServer.Protocol { public static class TextDocumentNames { public const string CodeAction = "textDocument/codeAction"; public const string CodeActionResolve = "codeAction/resolve"; public const string CodeLens = "textDocument/codeLens"; public const string CodeLensResolve = "codeLens/resolve"; public const string ColorPresentation = "textDocument/colorPresentation"; public const string Completion = "textDocument/completion"; public const string CompletionResolve = "completionItem/resolve"; public const string Definition = "textDocument/definition"; public const string Declaration = "textDocument/declaration"; public const string DidChange = "textDocument/didChange"; public const string DidClose = "textDocument/didClose"; public const string DidOpen = "textDocument/didOpen"; public const string DidSave = "textDocument/didSave"; public const string DocumentColor = "textDocument/documentColor"; public const string DocumentHighlight = "textDocument/documentHighlight"; public const string DocumentFormatting = "textDocument/formatting"; public const string DocumentLink = "textDocument/documentLink"; public const string DocumentLinkResolve = "documentLink/resolve"; public const string OnTypeFormatting = "textDocument/onTypeFormatting"; public const string RangeFormatting = "textDocument/rangeFormatting"; public const string DocumentSymbol = "textDocument/documentSymbol"; public const string Hover = "textDocument/hover"; public const string Implementation = "textDocument/implementation"; public const string References = "textDocument/references"; public const string Rename = "textDocument/rename"; public const string PrepareRename = "textDocument/prepareRename"; public const string SelectionRange = "textDocument/selectionRange"; public const string SignatureHelp = "textDocument/signatureHelp"; public const string TypeDefinition = "textDocument/typeDefinition"; public const string WillSave = "textDocument/willSave"; public const string WillSaveWaitUntil = "textDocument/willSaveWaitUntil"; public const string PublishDiagnostics = "textDocument/publishDiagnostics"; public const string FoldingRange = "textDocument/foldingRange"; public const string PrepareCallHierarchy = "textDocument/prepareCallHierarchy"; public const string CallHierarchyIncoming = "callHierarchy/incomingCalls"; public const string CallHierarchyOutgoing = "callHierarchy/outgoingCalls"; public const string SemanticTokensRegistration = "textDocument/semanticTokens"; public const string SemanticTokensFull = "textDocument/semanticTokens/full"; public const string SemanticTokensFullDelta = "textDocument/semanticTokens/full/delta"; public const string SemanticTokensRange = "textDocument/semanticTokens/range"; public const string Moniker = "textDocument/moniker"; public const string LinkedEditingRange = "textDocument/linkedEditingRange"; } }
// // - PropertyNode.Helpers.cs - // // Copyright 2013 Carbonfrost Systems, Inc. (http://carbonfrost.com) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; namespace Carbonfrost.Commons.PropertyTrees { partial class PropertyNode { // TODO This is a IPropertyTreeClient (futures) public bool GetBoolean(string path) { return Convert.ToBoolean(GetValue(path)); } public bool GetBoolean(PropertyTreePath path) { return Convert.ToBoolean(GetValue(path)); } public byte GetByte(string path) { return Convert.ToByte(GetValue(path)); } public byte GetByte(PropertyTreePath path) { return Convert.ToByte(GetValue(path)); } public char GetChar(string path) { return Convert.ToChar(GetValue(path)); } public char GetChar(PropertyTreePath path) { return Convert.ToChar(GetValue(path)); } public DateTime GetDateTime(string path) { return Convert.ToDateTime(GetValue(path)); } public DateTime GetDateTime(PropertyTreePath path) { return Convert.ToDateTime(GetValue(path)); } public DateTimeOffset GetDateTimeOffset(string path) { throw new NotImplementedException(); } public DateTimeOffset GetDateTimeOffset(PropertyTreePath path) { throw new NotImplementedException(); } public decimal GetDecimal(string path) { return Convert.ToDecimal(GetValue(path)); } public decimal GetDecimal(PropertyTreePath path) { return Convert.ToDecimal(GetValue(path)); } public double GetDouble(string path) { return Convert.ToDouble(GetValue(path)); } public double GetDouble(PropertyTreePath path) { return Convert.ToDouble(GetValue(path)); } public Guid GetGuid(string path) { throw new NotImplementedException(); } public Guid GetGuid(PropertyTreePath path) { throw new NotImplementedException(); } public short GetInt16(string path) { return Convert.ToInt16(GetValue(path)); } public short GetInt16(PropertyTreePath path) { return Convert.ToInt16(GetValue(path)); } public int GetInt32(string path) { return Convert.ToInt32(GetValue(path)); } public int GetInt32(PropertyTreePath path) { return Convert.ToInt32(GetValue(path)); } public long GetInt64(string path) { return Convert.ToInt64(GetValue(path)); } public long GetInt64(PropertyTreePath path) { return Convert.ToInt64(GetValue(path)); } [CLSCompliant(false)] public sbyte GetSByte(string path) { return Convert.ToSByte(GetValue(path)); } [CLSCompliant(false)] public sbyte GetSByte(PropertyTreePath path) { return Convert.ToSByte(GetValue(path)); } public float GetSingle(string path) { return Convert.ToSingle(GetValue(path)); } public float GetSingle(PropertyTreePath path) { return Convert.ToSingle(GetValue(path)); } public string GetString(string path) { return Convert.ToString(GetValue(path)); } public string GetString(PropertyTreePath path) { return Convert.ToString(GetValue(path)); } public TimeSpan GetTimeSpan(string path) { throw new NotImplementedException(); } public TimeSpan GetTimeSpan(PropertyTreePath path) { throw new NotImplementedException(); } public PropertyTree GetPropertyTree(string path) { throw new NotImplementedException(); } public PropertyTree GetPropertyTree(PropertyTreePath path) { throw new NotImplementedException(); } [CLSCompliant(false)] public ushort GetUInt16(string path) { return Convert.ToUInt16(GetValue(path)); } [CLSCompliant(false)] public ushort GetUInt16(PropertyTreePath path) { return Convert.ToUInt16(GetValue(path)); } [CLSCompliant(false)] public uint GetUInt32(string path) { return Convert.ToUInt32(GetValue(path)); } [CLSCompliant(false)] public uint GetUInt32(PropertyTreePath path) { return Convert.ToUInt32(GetValue(path)); } [CLSCompliant(false)] public ulong GetUInt64(string path) { return Convert.ToUInt64(GetValue(path)); } [CLSCompliant(false)] public ulong GetUInt64(PropertyTreePath path) { return Convert.ToUInt64(GetValue(path)); } public Uri GetUri(string path) { return new Uri(Convert.ToString(GetValue(path))); } public Uri GetUri(PropertyTreePath path) { return new Uri(Convert.ToString(GetValue(path))); } // TODO Correctly handle paths public void SetValue(string path, object value) { PropertyNode node = this.Children[path]; bool prop = Utility.IsProperty(value); if (value == null && node != null) { this.RemoveChild(node); } else if (node == null || prop != node.IsProperty) { if (prop) { this.AppendProperty(path, value); } else { PropertyTree tree = AppendPropertyTree(path); tree.Value = value; } } else { node.Value = value; } } public void SetValue(PropertyTreePath path, object value) { throw new NotImplementedException(); } private object GetValue(PropertyTreePath path) { throw new NotImplementedException(); } private object GetValue(string path) { PropertyNode node = this.Children[path]; if (node == null) return null; else return node.Value; } } }
using UnityEngine; using System.Collections; using UnityEngine.UI; public class GUImanager : MonoBehaviour { public AudioClip AUGameOver; public AudioSource AUBG; public GameObject Player; public GameObject Main; public GameObject Begin; public GameObject Over; public Text Score; public Text Kehuishou_Score; public Text Bukehuishou_Score; public Text XKehuishou_Score; public Text XBukehuishou_Score; private int kehuishou_score; private int bukehuishou_score; private int xkehuishou_score; private int xbukehuishou_score; public GameObject Pingjia_jiayou; public GameObject Pingjia_biaoyang; public static bool bOkToRestart=false; public Image kuQi; public Image[] pingJia; //Return the Instance // Use this for initialization void Start() { Time.timeScale = 0; } // Update is called once per frame void Update() { if (pengzhuang.hp == 0) { playerMovement.RunDet = false; Time.timeScale = 0; bOkToRestart = true; kehuishou_score = pengzhuang.kehuishou_number * 100; bukehuishou_score = pengzhuang.bukehuishou_number * 100; xkehuishou_score = pengzhuang.xkehuishou_number * 100; xbukehuishou_score = pengzhuang.xbukehuishou_number * 100; Kehuishou_Score.text = kehuishou_score.ToString(); Bukehuishou_Score.text = bukehuishou_score.ToString(); XKehuishou_Score.text = xkehuishou_score.ToString(); XBukehuishou_Score.text = xbukehuishou_score.ToString(); Score.text = pengzhuang.score.ToString(); if (pengzhuang.score <= 0) kuQi.gameObject.SetActive(true); else { int i = pengzhuang.score / 500; for (int j = 0; j <= i; j++) { pingJia[j].gameObject.SetActive(true); } } DisPlayGameOver(); } else { bOkToRestart = false; kuQi.gameObject.SetActive(false); for (int i = 0; i < 5; i++) { if(pingJia[i].gameObject.activeSelf) pingJia[i].gameObject.SetActive(false); } } } public void DisPlayMain()//当点击开始按钮的时候触发这个事件 { Begin.SetActive(false); Main.SetActive(true); Time.timeScale = 1; } void DisPlayGameOver() { Main.SetActive(false); Over.SetActive(true); AUBG.Stop(); AudioSource.PlayClipAtPoint(AUGameOver, Player.transform.position); } public void Quit() { Debug.Log("Quit"); Application.Quit(); } }
using System; using Application.Common.Mappings; using Domain.Entities; namespace Application.Common.Dtos { public class AllProductDto : IMapFrom<ProductGL> { public Guid IdProduct { get; set; } public string ProductName { get; set; } } }
using UnityEngine; using System.Collections; // TODO: Rename to player sprite manager or something public class SpriteFollowPlayer : MonoBehaviour { private GameObject hunterSprite; private GameObject seekerSprite; private float hunterOffset; private float seekerOffset; private Renderer hunterRenderer; private Renderer seekerRenderer; private PlayerIdentity id; private bool inWater = false; void Start() { id = GetComponent<PlayerIdentity>(); hunterSprite = GameObject.Find("Hunter Sprite"); seekerSprite = GameObject.Find("Seeker Sprite"); if (!hunterSprite) { return; } hunterRenderer = hunterSprite.GetComponent<Renderer>(); seekerRenderer = seekerSprite.GetComponent<Renderer>(); hunterOffset = hunterRenderer.bounds.size.y / 2; seekerOffset = seekerRenderer.bounds.size.y / 2; } void Update() { if (id.IsHunter() && hunterSprite) { if (inWater) { // TODO: Lerp getting in and out of the water hunterSprite.transform.position = transform.position + new Vector3(0, hunterOffset/2, 0); } else { hunterSprite.transform.position = transform.position + new Vector3(0, hunterOffset, 0); } } else if (seekerSprite) { if (inWater) { seekerSprite.transform.position = transform.position + new Vector3(0, seekerOffset/2, 0); } else { seekerSprite.transform.position = transform.position + new Vector3(0, seekerOffset, 0); } } } public void MakeSpriteInvisible() { if (id.IsHunter()) { hunterRenderer.enabled = false; } else { seekerRenderer.enabled = false; } } public void MakeSpriteVisible() { if (id.IsHunter()) { hunterRenderer.enabled = true; } else { seekerRenderer.enabled = true; } } public void EnterWater() { inWater = true; } public void ExitWater() { inWater = false; } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AutoMapper; using SchoolDiary.Controllers; using SchoolDiary.Data.Entities; using SchoolDiary.Models; using Microsoft.EntityFrameworkCore; using Moq; using NUnit.Framework; namespace SchoolDiary.Tests.Controllers { public class TeachersControllerTest : ControllerTestBase { private static TeacherDto ComposeTestTeacherDto(IEnumerable<Subject> subjects) => new TeacherDto { LastName = "TestTeacherLastName", FirstName = "TestTeacherFirstName", MiddleName = "TestTeacherMiddleName", Phone = "TestTeacherPhone", SubjectsIds = subjects.Select(subject => subject.Id) }; private static void AssertAreEqual(TeacherDto teacherDto, Teacher teacher) { Assert.AreEqual(teacherDto.LastName, teacher.LastName); Assert.AreEqual(teacherDto.FirstName, teacher.FirstName); Assert.AreEqual(teacherDto.MiddleName, teacher.MiddleName); Assert.AreEqual(teacherDto.Phone, teacher.Phone); Assert.AreEqual(teacherDto.SubjectsIds, teacher.Subjects.Select(subject => subject.Id)); } [Test] public async Task ShouldGetAllTeachersProperly() { var teachers = EntitiesGenerationRange.Select(_ => new Teacher()).ToList(); var context = ComposeEmptyDataContext(); await context.Teachers.AddRangeAsync(teachers); await context.SaveChangesAsync(); var mapperMock = new Mock<IMapper>(); teachers.ForEach(teacher => mapperMock.Setup(mapper => mapper.Map<TeacherMinDto>(teacher)).Verifiable()); foreach (var _ in await new TeachersController(context, mapperMock.Object).GetAllAsync()) { } teachers.ForEach(teacher => mapperMock.Verify(mapper => mapper.Map<TeacherMinDto>(teacher), Times.Once)); } [Test] public async Task ShouldPostTeacherProperly() { var subjects = EntitiesGenerationRange.Select(_ => new Subject()).ToList(); var context = ComposeEmptyDataContext(); await context.Subjects.AddRangeAsync(subjects); await context.SaveChangesAsync(); var teacherDto = ComposeTestTeacherDto(subjects); await new TeachersController(context, null).PostAsync(teacherDto); var teacher = await context.Teachers.SingleAsync(); AssertAreEqual(teacherDto, teacher); } [Test] public async Task ShouldGetTeacherProperly() { var teacher = new Teacher(); var context = ComposeEmptyDataContext(); await context.Teachers.AddAsync(teacher); await context.SaveChangesAsync(); var mapperMock = new Mock<IMapper>(); mapperMock.Setup(mapper => mapper.Map<TeacherDto>(teacher)).Verifiable(); await new TeachersController(context, mapperMock.Object).GetAsync(teacher.Id); mapperMock.Verify(mapper => mapper.Map<TeacherDto>(teacher), Times.Once); } [Test] public void ShouldThrowExceptionWhenTryingToGetTeacherThatDoesNotExist() { var context = ComposeEmptyDataContext(); Assert.ThrowsAsync<InvalidOperationException>( () => new TeachersController(context, null).GetAsync(ComposeRandomId()) ); } [Test] public async Task ShouldPutTeacherProperly() { var teacher = new Teacher(); var subjects = EntitiesGenerationRange.Select(_ => new Subject()).ToList(); var context = ComposeEmptyDataContext(); await context.Teachers.AddAsync(teacher); await context.Subjects.AddRangeAsync(subjects); await context.SaveChangesAsync(); var teacherDto = ComposeTestTeacherDto(subjects); await new TeachersController(context, null).PutAsync(teacher.Id, teacherDto); AssertAreEqual(teacherDto, teacher); } [Test] public void ShouldThrowExceptionWhenTryingToPutTeacherThatDoesNotExist() { var context = ComposeEmptyDataContext(); Assert.ThrowsAsync<InvalidOperationException>( () => new TeachersController(context, null).PutAsync(ComposeRandomId(), new TeacherDto()) ); } [Test] public async Task ShouldDeleteTeacherProperly() { var teacher = new Teacher(); var context = ComposeEmptyDataContext(); await context.Teachers.AddAsync(teacher); await context.SaveChangesAsync(); await new TeachersController(context, null).DeleteAsync(teacher.Id); Assert.IsEmpty(context.Teachers); } [Test] public void ShouldThrowExceptionWhenTryingToDeleteTeacherThatDoesNotExist() { var context = ComposeEmptyDataContext(); Assert.ThrowsAsync<InvalidOperationException>( () => new TeachersController(context, null).DeleteAsync(ComposeRandomId()) ); } } }
namespace ZSharp.Framework.Configurations { public interface IStartupConfiguration { IModuleConfigurations Modules { get; } T Get<T>(); } }
using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Hl7.Fhir.Rest; using Hl7.Fhir.Model; using System.Collections.Generic; using LockStepBlazor.Application.Fhir.Queries; namespace LockStepBlazor.Handlers { public class GetPatientListHandler : GetPatientList.IHandler { private readonly FhirClient client; public GetPatientListHandler(FhirClient client) { this.client = client; } public async Task<GetPatientList.Model> Handle(GetPatientList.Query request, CancellationToken cancellationToken) { var paramsList = new List<string>(); var queryNames = new SearchParams(); if (!string.IsNullOrEmpty(request.FirstName)) { request.FirstName = request.FirstName?.ToLower(); request.FirstName = request.FirstName?.Trim(); queryNames.Where($"given={request.FirstName}").SummaryOnly(SummaryType.Text); paramsList.Add($"given:contains={request.FirstName}"); // queryNames.Where($"given={request.FirstName}").SummaryOnly(SummaryType.Count); //use this for a execute batch but for Medicaions } if (!string.IsNullOrEmpty(request.LastName)) { request.LastName = request.LastName?.ToLower(); request.LastName = request.LastName?.Trim(); queryNames.Where($"family={request.LastName}").SummaryOnly(SummaryType.Text); //var p = queryNames.ToParameters().; paramsList.Add($"name:contains={request.LastName}"); } // var trans = new TransactionBuilder(client.Endpoint); // trans = trans.Search(q, "MedicationRequest").Search(t, "MedicationStatement"); // //var result = await _client.SearchAsync<MedicationRequest>(q); // var tResult = _client.TransactionAsync(trans.ToBundle()); // var result = // PatientList // .Where(x => // x.GivenNames.Select(n=> n.ToLower()).Contains(term) || // x.LastName.ToLower().Contains(term) // ) // .ToList(); //these shpuld be identical // var pats = await client.SearchAsync<Patient>(paramsList.ToArray(), default, 10/*, SummaryType.Text*/); var pats = await client.SearchAsync<Patient>(queryNames.LimitTo(10)); return new GetPatientList.Model() { Patients = pats }; } // var queryNames = new SearchParams() // .LimitTo(10); // var searchCall = await client.SearchAsync<Patient>(queryNames); // List<Patient> patients = new List<Patient>(); // var res = new GetPatientList.Model(); // // while (searchCall != null) // // { // foreach (var e in searchCall.Entry) // { // Patient p = (Patient)e.Resource; // patients.Add(p); // } // //TODO: How is this used? // // searchCall = client.Continue(searchCall, PageDirection.Next); // // } // res.Requests = patients; // return res; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class MoveHistoryHandler : MonoBehaviour { /// <summary> /// Max history list length. /// </summary> public int maxSize; /// <summary> /// Move list. /// </summary> private Queue<GameObject> moves; /// <summary> /// Start this instance. /// </summary> void Start() { moves = new Queue<GameObject>(); } /// <summary> /// Adds a move to the list of moves and removes the ends if it exceeds the max size /// </summary> /// <param name="move">Move.</param> public void addMove(PieceMove move) { #region shifting list to accomidate new move // remove end if (moves.Count >= maxSize) { GameObject last = moves.Dequeue(); Destroy(last); } // move everything else down foreach (GameObject o in moves) { SmoothMoveUI smuiCur = o.GetComponent<SmoothMoveUI>(); smuiCur.target.y -= 50f; } #endregion #region adding new move // add new one GameObject display = Instantiate(Resources.Load("Prefabs/UI/PastMoveDisplay")) as GameObject; display.transform.SetParent(transform, false); SmoothMoveUI smui = display.GetComponent<SmoothMoveUI>(); smui.target += display.transform.localPosition; smui.target.x -= 50f; AdjustDisplay(move, display); MoveHistoryHover mhh = display.GetComponent<MoveHistoryHover>(); mhh.src = move.src; mhh.dest = move.dest; moves.Enqueue(display); #endregion } /// <summary> /// Adjusts the display icons and colours /// </summary> /// <param name="move">Move.</param> private void AdjustDisplay(PieceMove move, GameObject display) { // Rolled a zero on the way if (move.firstTower == null) { return; } // find both hexagon images Image firstHex = display.transform.Find("FirstHex").GetComponent<Image>(); Image secHex = display.transform.Find("SecHex").GetComponent<Image>(); MultiSpriteChanger msc = display.transform.Find("ActionArrow").GetComponent<MultiSpriteChanger>(); // action maker colour (left) firstHex.color = move.firstTower.owningPlayer.getRealColor(); switch (move.Type) { case PieceMove.MoveType.Move: secHex.enabled = false; msc.ChangeSprite(0); break; case PieceMove.MoveType.Attack: secHex.color = move.secondTower.owningPlayer.getRealColor(); msc.ChangeSprite(1); break; case PieceMove.MoveType.Way: secHex.enabled = false; msc.ChangeSprite(2); break; case PieceMove.MoveType.WayAttack: secHex.color = move.secondTower.owningPlayer.getRealColor(); msc.ChangeSprite(3); break; } } }
using ALM.Empresa.Entidades; using System; using System.Collections.Generic; using System.Data; using MySql.Data.MySqlClient; using ALM.Empresa.AccesoDatos; namespace ALM.Empresa.Datos { public class DForma : Conexion { public List<EFormas> ObtenerListaFormasPorUsuario(int idUsuario, int idEmpresa) { try { AbrirConexion(); accesoDatos.LimpiarParametros(); accesoDatos.TipoComando = CommandType.StoredProcedure; accesoDatos.Consulta = accesoDatos.ObtenerConsultaXml(Constante.RutaSP, "SPObtFormasRolesPrivilegiosPorUsuario"); accesoDatos.ListaParametros.Add(new MySqlParameter("pIdUsuario", idUsuario)); accesoDatos.ListaParametros.Add(new MySqlParameter("pIdEmpresa", idEmpresa)); return accesoDatos.CargarTabla().DataTableMapToList<EFormas>(); } finally { CerrarConexion(); accesoDatos.LimpiarParametros(); } } public List<EFormas> ObtenerListaFormasAdministrador(int idEmpresa, bool esSuperAdministrador) { try { AbrirConexion(); accesoDatos.LimpiarParametros(); accesoDatos.TipoComando = CommandType.StoredProcedure; accesoDatos.Consulta = accesoDatos.ObtenerConsultaXml(Constante.RutaSP, "SPObtFormasRolesPrivilegiosPorAdministrador"); accesoDatos.ListaParametros.Add(new MySqlParameter("pIdEmpresa", idEmpresa)); accesoDatos.ListaParametros.Add(new MySqlParameter("pEsSuperAdministrador", esSuperAdministrador)); return accesoDatos.CargarTabla().DataTableMapToList<EFormas>(); } finally { CerrarConexion(); accesoDatos.LimpiarParametros(); } } public List<EFormas> ObtenerListaFormasPorRol(int idRol, string nombreForma, int idEmpresa) { try { AbrirConexion(); accesoDatos.LimpiarParametros(); accesoDatos.TipoComando = CommandType.StoredProcedure; accesoDatos.Consulta = accesoDatos.ObtenerConsultaXml(Constante.RutaSP, "SPObtFormasRolesPrivilegiosPorRol"); accesoDatos.ListaParametros.Add(new MySqlParameter("pIdRol", idRol)); accesoDatos.ListaParametros.Add(new MySqlParameter("pNombreForma", nombreForma)); accesoDatos.ListaParametros.Add(new MySqlParameter("pIdEmpresa", idEmpresa)); return accesoDatos.CargarTabla().DataTableMapToList<EFormas>(); } finally { CerrarConexion(); accesoDatos.LimpiarParametros(); } } public List<EFormas> ObtenerListaFormas(int idEmpresa) { try { AbrirConexion(); accesoDatos.LimpiarParametros(); accesoDatos.TipoComando = CommandType.StoredProcedure; accesoDatos.Consulta = accesoDatos.ObtenerConsultaXml(Constante.RutaSP, "SPObtFormas"); accesoDatos.ListaParametros.Add(new MySqlParameter("pIdEmpresa", idEmpresa)); return accesoDatos.CargarTabla().DataTableMapToList<EFormas>(); } finally { CerrarConexion(); accesoDatos.LimpiarParametros(); } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Linq; using System.Windows.Forms; using DevExpress.XtraEditors; using System.Text.RegularExpressions; using HalconDotNet; using ChoiceTech.Halcon.Control; using SagensSdk; using System.IO; using ViewWindow.Model; using System.Collections; using System.Diagnostics; using System.Drawing.Imaging; using System.Globalization; namespace SagensVision.VisionTool { public partial class FitLineSet : DevExpress.XtraEditors.XtraForm { int CurrentIndex = 0; HWindow_Final hwindow_final1 = new HWindow_Final(); HWindow_Final hwindow_final2 = new HWindow_Final(); //public FitProfileParam[] fpTool.fParam = new FitProfileParam[4]; ROIController roiController; ROIController roiController2; //List<ROI>[] fpTool.roiList = new List<ROI>[4]; //List<ROI>[] fpTool.fpTool.roiList2 = new List<ROI>[4]; List<ROI> tempList = new List<ROI>(); //List<ROI>[] fpTool.roiList3 = new List<ROI>[4];//校准区域 HObject HeightImage = new HObject(); HObject IntensityImage = new HObject(); HObject RGBImage = new HObject(); HObject OriginImage = new HObject(); //public IntersetionCoord[] intersectCoordList = new IntersetionCoord[4]; //计算输出交点 IntersetionCoord intersection = new IntersetionCoord(); public FindPointTool fpTool = new FindPointTool(); bool isRight = true; List<HTuple> _lines = new List<HTuple>(); public List<HTuple> H_Lines { get { return _lines; } } /// <summary> /// "工具类型 Calib or GlueGuide" /// </summary> public string ToolType = ""; /// <summary> /// 找线方式 "Fix" or "FitLineSet" /// </summary> public string FindType = ""; public FitLineSet(string text = "") { InitializeComponent(); if (text != "") { this.Text = text; } } private void FitLineSet_Load(object sender, EventArgs e) { RoiParam.isInvoke = false; isLoading = true; isRight = MyGlobal.IsRight; //string ok = fpTool.Init(FindType, isRight, ToolType); //if (ok != "OK") //{ // MessageBox.Show(ok); //} this.MaximizeBox = true; CurrentSide = "Side1"; isSave = true; isCloing = false; splitContainerControl4.Panel1.Controls.Add(hwindow_final2); splitContainerControl6.Panel1.Controls.Add(hwindow_final1); hwindow_final1.Dock = DockStyle.Fill; hwindow_final2.Dock = DockStyle.Fill; trackBarControl1.Properties.Minimum = 1; //LoadToUI(0); roiController = hwindow_final1.viewWindow._roiController; roiController.NotifyRCObserver = new IconicDelegate(ROiMove); roiController2 = hwindow_final2.viewWindow._roiController; roiController2.NotifyRCObserver = new IconicDelegate(ROiMove2); comboBox2.SelectedIndex = 0; comboBox1.SelectedIndex = 0; CurrentSide = "Side1"; SideName = CurrentSide; hwindow_final1.viewWindow.setEditModel(true); hwindow_final2.viewWindow.setEditModel(true); checkBoxRoi.Checked = true; ChangeSide(); hwindow_final2.hWindowControl.MouseDown += Hwindow_final2_MouseDown; isLoading = false; RoiParam.isInvoke = true; RoiParam.ChangeSection += RoiParam_ChangeSection; isSave = true; } private void RoiParam_ChangeSection(ValueChangedType obj, double value) { try { if (isLoading || RoiIsMoving) { return; } if (RoiParam.isInvoke) { RoiParam.isInvoke = false; } isSave = false; int SideId = Convert.ToInt32(SideName.Substring(4, 1)) - 1; int roiID = dataGridView1.CurrentCell.RowIndex; roiID = CurrentRowIndex; int count = dataGridView1.SelectedCells.Count; List<int> rowInd = new List<int>(); for (int i = 0; i < count; i++) { int Ind = dataGridView1.SelectedCells[i].RowIndex; if (!rowInd.Contains(Ind)) { rowInd.Add(Ind); } } //for (int i = 0; i < rowInd.Count; i++) //{ // roiID = rowInd[i]; // HTuple[] lineCoord = new HTuple[1]; //} bool roiUpdate = false; for (int i = 0; i < rowInd.Count; i++) { roiID = rowInd[i]; HTuple[] lineCoord = new HTuple[1]; switch (obj) { case ValueChangedType.数量: fpTool.fParam[SideId].roiP[roiID].NumOfSection = (int)value; fpTool.DispSection((ROIRectangle2)fpTool.roiList2[SideId][roiID], SideId, roiID, out lineCoord, hwindow_final2); roiUpdate = true; break; case ValueChangedType.长度: HTuple temp = new HTuple(); List<ROI> temproi = new List<ROI>(); temp = fpTool.roiList2[SideId][roiID].getModelData(); fpTool.fParam[SideId].roiP[roiID].Len1 = value; hwindow_final2.viewWindow.genRect2(fpTool.fParam[SideId].roiP[roiID].CenterRow, fpTool.fParam[SideId].roiP[roiID].CenterCol, fpTool.fParam[SideId].roiP[roiID].phi, fpTool.fParam[SideId].roiP[roiID].Len1, fpTool.fParam[SideId].roiP[roiID].Len2, ref temproi); fpTool.roiList2[SideId][roiID] = temproi[0]; roiUpdate = true; break; case ValueChangedType.宽度: HTuple temp3 = new HTuple(); temp3 = fpTool.roiList2[SideId][roiID].getModelData(); List<ROI> temproi3 = new List<ROI>(); fpTool.fParam[SideId].roiP[roiID].Len2 = value; hwindow_final2.viewWindow.genRect2(fpTool.fParam[SideId].roiP[roiID].CenterRow, fpTool.fParam[SideId].roiP[roiID].CenterCol, fpTool.fParam[SideId].roiP[roiID].phi, fpTool.fParam[SideId].roiP[roiID].Len1, fpTool.fParam[SideId].roiP[roiID].Len2, ref temproi3); fpTool.roiList2[SideId][roiID] = temproi3[0]; roiUpdate = true; break; case ValueChangedType.角度: HTuple temp6 = new HTuple(); temp3 = fpTool.roiList2[SideId][roiID].getModelData(); List<ROI> temproi6 = new List<ROI>(); fpTool.fParam[SideId].roiP[roiID].phi = value; hwindow_final2.viewWindow.genRect2(fpTool.fParam[SideId].roiP[roiID].CenterRow, fpTool.fParam[SideId].roiP[roiID].CenterCol, fpTool.fParam[SideId].roiP[roiID].phi, fpTool.fParam[SideId].roiP[roiID].Len1, fpTool.fParam[SideId].roiP[roiID].Len2, ref temproi6); fpTool.roiList2[SideId][roiID] = temproi6[0]; roiUpdate = true; break; case ValueChangedType.行坐标: HTuple temp4 = new HTuple(); temp4 = fpTool.roiList2[SideId][roiID].getModelData(); List<ROI> temproi4 = new List<ROI>(); fpTool.fParam[SideId].roiP[roiID].CenterRow = value; hwindow_final2.viewWindow.genRect2(fpTool.fParam[SideId].roiP[roiID].CenterRow, fpTool.fParam[SideId].roiP[roiID].CenterCol, fpTool.fParam[SideId].roiP[roiID].phi, fpTool.fParam[SideId].roiP[roiID].Len1, fpTool.fParam[SideId].roiP[roiID].Len2, ref temproi4); fpTool.roiList2[SideId][roiID] = temproi4[0]; roiUpdate = true; break; case ValueChangedType.列坐标: HTuple temp5 = new HTuple(); temp3 = fpTool.roiList2[SideId][roiID].getModelData(); List<ROI> temproi5 = new List<ROI>(); fpTool.fParam[SideId].roiP[roiID].CenterCol = value; hwindow_final2.viewWindow.genRect2(fpTool.fParam[SideId].roiP[roiID].CenterRow, fpTool.fParam[SideId].roiP[roiID].CenterCol, fpTool.fParam[SideId].roiP[roiID].phi, fpTool.fParam[SideId].roiP[roiID].Len1, fpTool.fParam[SideId].roiP[roiID].Len2, ref temproi5); fpTool.roiList2[SideId][roiID] = temproi5[0]; roiUpdate = true; break; case ValueChangedType.Roi方向偏移: fpTool.fParam[SideId].roiP[roiID].offset = value; break; case ValueChangedType.X方向偏移: fpTool.fParam[SideId].roiP[roiID].Xoffset = value; break; case ValueChangedType.Y方向偏移: fpTool.fParam[SideId].roiP[roiID].Yoffset = value; break; case ValueChangedType.Z方向偏移: fpTool.fParam[SideId].roiP[roiID].Zoffset = value; break; case ValueChangedType.X方向距离: fpTool.fParam[SideId].roiP[roiID].xDist = value; break; case ValueChangedType.取最近点还是最远点: fpTool.fParam[SideId].roiP[roiID].useNear = value ==1 ? true : false; break; case ValueChangedType.取轮廓区域中心点: fpTool.fParam[SideId].roiP[roiID].useCenter = value == 1 ? true : false; break; case ValueChangedType.是否取中间点: fpTool.fParam[SideId].roiP[roiID].useMidPt = value == 1 ? true : false; break; case ValueChangedType.是否取左侧值: fpTool.fParam[SideId].roiP[roiID].useLeft = value == 1 ? true : false; break; case ValueChangedType.是否启用Z向缩放: fpTool.fParam[SideId].roiP[roiID].useZzoom = value == 1 ? true : false; break; case ValueChangedType.找线方式设置: fpTool.fParam[SideId].roiP[roiID].TypeOfFindLine = value == 0 ? "极值" : "最大值"; break; case ValueChangedType.最高点下降距离: fpTool.fParam[SideId].roiP[roiID].TopDownDist = value ; break; case ValueChangedType.直线滤波系数: fpTool.fParam[SideId].roiP[roiID].SmoothCont = value ; break; case ValueChangedType.轮廓Z向拉伸: fpTool.fParam[SideId].roiP[roiID].ClippingPer = value; break; case ValueChangedType.高度方向滤波最大百分比: fpTool.fParam[SideId].roiP[roiID].ZftMax = value; break; case ValueChangedType.高度方向滤波最小百分比: fpTool.fParam[SideId].roiP[roiID].ZftMin = value; break; case ValueChangedType.高度方向滤波半径: fpTool.fParam[SideId].roiP[roiID].ZftRad = value; break; case ValueChangedType.轮廓平滑: fpTool.fParam[SideId].roiP[roiID].Sigma = value; break; case ValueChangedType.轮廓旋转角度: fpTool.fParam[SideId].roiP[roiID].AngleOfProfile = (int) value; break; default: break; } } if (roiUpdate) { hwindow_final2.viewWindow.notDisplayRoi(); hwindow_final2.viewWindow.displayROI(ref fpTool.roiList2[SideId]); hwindow_final2.viewWindow.selectROI(roiID); } RoiParam.isInvoke = true; } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void Hwindow_final2_MouseDown(object sender, MouseEventArgs e) { int Id = Convert.ToInt32(SideName.Substring(4, 1)) - 1; ArrayList array = roiController2.ROIList; int currentId = -1; string Name = ""; if (dataGridView1.CurrentCell == null || CurrentRowIndex == -1) { currentId = 0; } else { currentId = dataGridView1.CurrentCell.RowIndex; currentId = CurrentRowIndex; //ID Name = dataGridView1.Rows[currentId].Cells[1].Value.ToString(); } int ActiveId = roiController2.getActiveROIIdx(); if (!SelectAll) { if (ActiveId != currentId) { roiController2.EditModel = false; } else { roiController2.EditModel = true; } } } public void ROiMove(int value) { try { switch (value) { //case ROIController.EVENT_CHANGED_ROI_SIGN: //case ROIController.EVENT_DELETED_ACTROI: //case ROIController.EVENT_DELETED_ALL_ROIS: case ROIController.EVENT_UPDATE_ROI: isSave = false; int Id = Convert.ToInt32(SideName.Substring(4, 1)); if (dataGridView1.CurrentCell == null) { return; } int RowId = dataGridView1.CurrentCell.RowIndex; RowId = CurrentRowIndex; if (RowId < 0 || FindPointTool.RArray == null) { return; } fpTool.roiList[Id - 1][RowId] = temp[0]; //记录当前锚定点坐标 HTuple row, col; fpTool.FindFirstAnchor(Id, out row, out col, CurrentIndex); if (row.Length==0) { return; } fpTool.fParam[Id - 1].roiP[RowId].AnchorRow = row.D; fpTool.fParam[Id - 1].roiP[RowId].AnchorCol = col.D; ROI pt = roiController.getActiveROI(); if (pt.Type == "ROIPoint") { HTuple PointTemp = pt.getModelData(); HTuple row1, col1; fpTool.FindMaxPt(Id, CurrentIndex - 1, out row1, out col1, out row, out col, null, ShowSection, false, null); switch (PtOrder) { case 0: fpTool.fParam[Id - 1].roiP[RowId].StartOffSet1.Y = (int)(PointTemp[0].D - row.D); fpTool.fParam[Id - 1].roiP[RowId].StartOffSet1.X = (int)(PointTemp[1].D - col.D); PtOrder = -1; break; case 1: fpTool.fParam[Id - 1].roiP[RowId].EndOffSet1.Y = (int)(PointTemp[0].D - row.D); fpTool.fParam[Id - 1].roiP[RowId].EndOffSet1.X = (int)(PointTemp[1].D - col.D); PtOrder = -1; break; case 2: fpTool.fParam[Id - 1].roiP[RowId].StartOffSet2.Y = (int)(PointTemp[0].D - row.D); fpTool.fParam[Id - 1].roiP[RowId].StartOffSet2.X = (int)(PointTemp[1].D - col.D); PtOrder = -1; break; case 3: fpTool.fParam[Id - 1].roiP[RowId].EndOffSet2.Y = (int)(PointTemp[0].D - row.D); fpTool.fParam[Id - 1].roiP[RowId].EndOffSet2.X = (int)(PointTemp[1].D - col.D); PtOrder = -1; break; } } break; //case HWndCtrl.ERR_READING_IMG: // MessageBox.Show("Problem occured while reading file! \n", "Profile ", // MessageBoxButtons.OK, MessageBoxIcon.Information); // break; default: break; } } catch (Exception ex) { MessageBox.Show("RoiMove-->" + ex.Message); } } bool RoiIsMoving = false; public void ROiMove2(int value) { try { switch (value) { //case ROIController.EVENT_CHANGED_ROI_SIGN: //case ROIController.EVENT_DELETED_ACTROI: //case ROIController.EVENT_DELETED_ALL_ROIS: case ROIController.EVENT_UPDATE_ROI: if (isLoading) { return; } RoiIsMoving = true; int Id = Convert.ToInt32(SideName.Substring(4, 1)) - 1; ArrayList array = roiController2.ROIList; int currentId = -1; string Name = ""; if (dataGridView1.CurrentCell == null || CurrentRowIndex == -1) { currentId = 0; } else { //currentId = dataGridView1.CurrentCell.RowIndex; currentId = CurrentRowIndex; //ID Name = dataGridView1.Rows[currentId].Cells[1].Value.ToString(); } if (fpTool.roiList2[Id].Count != array.Count) { fpTool.roiList2[Id].Add(new ROIRectangle2()); //每个区域单独设置Roi hwindow_final1.viewWindow.notDisplayRoi(); hwindow_final1.viewWindow.genRect1(400, 400, 600, 600, ref fpTool.roiList[Id]); } int ActiveId = roiController2.getActiveROIIdx(); if (!SelectAll && !isGenSection) { if (ActiveId != currentId) { currentId = ActiveId; //RoiIsMoving = false; //return; } } if (array.Count == 1) { ROI te = (ROI)array[0]; if (te.Type != "ROIRectangle2") { return; } } if (fpTool.roiList2[Id].Count == 0) { return; } //if ( isInsert) //{ // currentId = currentId; //} //if (!isInsert) //{ // currentId = ActiveId; //} //if (currentId != -1 && isInsert) //{ // isInsert = false; // fpTool.fpTool.roiList2[Id][currentId] = (ROI)array[ActiveId]; // RoiParam RP = new RoiParam(); // RP = fpTool.fParam[Id].roiP[currentId].Clone(); // fpTool.fParam[Id].roiP.Insert(currentId, RP); // fpTool.fParam[Id].roiP[currentId].LineOrCircle = comboBox2.SelectedItem.ToString(); // //insert // dataGridView1.Rows.Insert(currentId); // dataGridView1.Rows[currentId].Cells[0].Value = currentId; // dataGridView1.Rows[currentId].Cells[1].Value = "Default"; // dataGridView1.Rows[currentId].Cells[2].Value = fpTool.fParam[Id].roiP[currentId].LineOrCircle; // fpTool.fParam[Id].DicPointName.Insert(currentId, "Default"); // //排序 // for (int i = 0; i < dataGridView1.Rows.Count; i++) // { // dataGridView1.Rows[i].Cells[0].Value = i; // } //} //else //{ //if (isInsert) //{ // isInsert = false; // //fpTool.fpTool.roiList2[Id][currentId] = (ROI)array[ActiveId]; //} //else //{ // fpTool.fpTool.roiList2[Id][ActiveId] = (ROI)array[ActiveId]; //} fpTool.roiList2[Id][ActiveId] = (ROI)array[ActiveId]; //} string key = "L"; if (fpTool.fParam[Id].roiP.Count != array.Count) { RoiParam RP = new RoiParam(); //RP.AngleOfProfile = Convert.ToInt32(textBox_Deg.Text); //RP.NumOfSection = Convert.ToInt32(textBox_Num.Text); fpTool.fParam[Id].roiP.Add(RP); fpTool.fParam[Id].roiP[ActiveId].LineOrCircle = comboBox2.SelectedItem.ToString(); switch (fpTool.fParam[Id].roiP[ActiveId].LineOrCircle) { case "连接段": key = "LC"; break; case "直线段": key = "L"; break; case "圆弧段": key = "C"; break; } key = key + (ActiveId + 1).ToString(); if (isGenSection) { isGenSection = false; AddToDataGrid(key, fpTool.fParam[Id].roiP[ActiveId].LineOrCircle); fpTool.fParam[Id].DicPointName.Add(key); } //操作DicPointName } HTuple[] lineCoord = new HTuple[1]; ////全选 //if (SelectAll) //{ // for (int i = 0; i < fpTool.fParam[Id].roiP.Count; i++) // { // DispSection((ROIRectangle2)fpTool.fpTool.roiList2[Id][i], Id, i, out lineCoord, hwindow_final2); // } //} //else //{ // if (currentId != -1 && isInsert) // { // isInsert = false; // DispSection((ROIRectangle2)fpTool.fpTool.roiList2[Id][currentId], Id, currentId, out lineCoord, hwindow_final2); // } // else // { // DispSection((ROIRectangle2)fpTool.fpTool.roiList2[Id][ActiveId], Id, ActiveId, out lineCoord, hwindow_final2); // } //} //listBox1.SelectedItem = ActiveId; HTuple ModelData = fpTool.roiList2[Id][ActiveId].getModelData(); fpTool.fParam[Id].roiP[ActiveId].Len1 = ModelData[3]; fpTool.fParam[Id].roiP[ActiveId].Len2 = ModelData[4]; fpTool.fParam[Id].roiP[ActiveId].CenterRow = ModelData[0]; fpTool.fParam[Id].roiP[ActiveId].CenterCol = ModelData[1]; //HTuple phi = ModelData[2]; fpTool.fParam[Id].roiP[ActiveId].phi = ModelData[2]; propertyGrid1.SelectedObject = fpTool.fParam[Id].roiP[ActiveId]; //textBox_Len.Text = ((int)fpTool.fParam[Id].roiP[ActiveId].Len1).ToString(); //textBox_Width.Text = ((int)fpTool.fParam[Id].roiP[ActiveId].Len2).ToString(); //textBox_Row.Text = ((int)fpTool.fParam[Id].roiP[ActiveId].CenterRow).ToString(); //textBox_Col.Text = ((int)fpTool.fParam[Id].roiP[ActiveId].CenterCol).ToString(); //HTuple deg = new HTuple(); //HOperatorSet.TupleDeg(ModelData[2], out deg); //textBox_phi.Text = ((int)deg.D).ToString(); PreSelect = Name; //刷新界面roi // if (fpTool.roiList2[Id].Count > 0) { if (SelectAll) { hwindow_final2.viewWindow.notDisplayRoi(); roiController2.viewController.ShowAllRoiModel = -1; hwindow_final2.viewWindow.displayROI(ref fpTool.roiList2[Id]); } else { roiController2.viewController.ShowAllRoiModel = ActiveId; roiController2.viewController.repaint(ActiveId); } } hwindow_final2.viewWindow.selectROI(ActiveId); dataGridView1.ClearSelection(); dataGridView1.Rows[ActiveId].Selected = true; CurrentRowIndex = ActiveId; //记录当前锚定点坐标 RoiIsMoving = false; isSave = false; break; //case HWndCtrl.ERR_READING_IMG: // MessageBox.Show("Problem occured while reading file! \n", "Profile ", // MessageBoxButtons.OK, MessageBoxIcon.Information); // break; default: break; } } catch (Exception ex) { isInsert = false; MessageBox.Show(ex.Message); } } bool isLoading = false; void LoadToUI(int Index = 0) { try { RoiIsMoving = true; //isLoading = true; //刷新Roi参数 UpdateRoiParam(); ParamPath.ToolType = ToolType; ParamPath.ParaName = FindType + "_" + comboBox1.SelectedItem.ToString(); ParamPath.IsRight = isRight; if (isRight) { comboBox3.SelectedIndex = 0; comboBox3.BackColor = Color.LimeGreen; } else { comboBox3.SelectedIndex = 1; comboBox3.BackColor = Color.Yellow; } string[] keys = fpTool.fParam[Index].DicPointName.ToArray(); dataGridView1.Rows.Clear(); cb_x1.Items.Clear(); cb_y1.Items.Clear(); for (int i = 0; i < keys.Length; i++) { AddToDataGrid(keys[i], fpTool.fParam[Index].roiP[i].LineOrCircle); //添加到锚定设置 if (FindType== MyGlobal.FindPointType_Fix) { cb_x1.Items.Add(keys[i]); cb_y1.Items.Add(keys[i]); } } if (keys.Length > 0) { propertyGrid1.SelectedObject = fpTool.fParam[Index].roiP[0]; //textBox_Num.Text = ((int)fpTool.fParam[Index].roiP[0].NumOfSection).ToString(); //textBox_Len.Text = ((int)fpTool.fParam[Index].roiP[0].Len1).ToString(); //textBox_Width.Text = ((int)fpTool.fParam[Index].roiP[0].Len2).ToString(); //textBox_Row.Text = ((int)fpTool.fParam[Index].roiP[0].CenterRow).ToString(); //textBox_Col.Text = ((int)fpTool.fParam[Index].roiP[0].CenterCol).ToString(); //textBox_Offset.Text = ((int)fpTool.fParam[Index].roiP[0].offset).ToString(); //textBox_OffsetX.Text = ((int)fpTool.fParam[Index].roiP[0].Xoffset).ToString(); //textBox_OffsetY.Text = ((int)fpTool.fParam[Index].roiP[0].Yoffset).ToString(); //textBox_OffsetZ.Text = ((int)fpTool.fParam[Index].roiP[0].Zoffset).ToString(); //textBox_ZFtMax.Text = (fpTool.fParam[Index].roiP[0].ZftMax).ToString(); //textBox_ZFtMin.Text = (fpTool.fParam[Index].roiP[0].ZftMin).ToString(); //textBox_ZFtRad.Text = (fpTool.fParam[Index].roiP[0].ZftRad).ToString(); //HTuple deg = new HTuple(); //HOperatorSet.TupleDeg(fpTool.fParam[Index].roiP[0].phi, out deg); //textBox_phi.Text = ((int)deg.D).ToString(); //textBox_Deg.Text = fpTool.fParam[Index].roiP[0].AngleOfProfile.ToString(); //checkBox_useLeft.Checked = fpTool.fParam[Index].roiP[0].useLeft; //checkBox_midPt.Checked = fpTool.fParam[Index].roiP[0].useMidPt; //checkBox_Far.Checked = !fpTool.fParam[Index].roiP[0].useNear; //checkBox_center.Checked = fpTool.fParam[Index].roiP[0].useCenter; //checkBox_zZoom.Checked = fpTool.fParam[Index].roiP[0].useZzoom; //textBox_downDist.Text = fpTool.fParam[Index].roiP[0].TopDownDist.ToString(); //textBox_xDist.Text = fpTool.fParam[Index].roiP[0].xDist.ToString(); //textBox_Clipping.Text = fpTool.fParam[Index].roiP[0].ClippingPer.ToString(); //textBox_SmoothCont.Text = fpTool.fParam[Index].roiP[0].SmoothCont.ToString(); //comboBox_GetPtType.SelectedIndex = 0; } RoiIsMoving = false; //isLoading = false; } catch (Exception) { throw; } } void AddToDataGrid(string ID, string Type) { dataGridView1.Rows.Add(); int count = dataGridView1.Rows.Count; dataGridView1.Rows[count - 1].Cells[0].Value = count; dataGridView1.Rows[count - 1].Cells[1].Value = ID; dataGridView1.Rows[count - 1].Cells[2].Value = Type; } private void trackBarControl1_ValueChanged(object sender, EventArgs e) { CurrentIndex = trackBarControl1.Value; textBox_Current.Text = CurrentIndex.ToString(); if (FindPointTool.RArray != null && FindPointTool.RArray.GetLength(0) > 0) { //button11_Click(sender, e); int Id = Convert.ToInt32(SideName.Substring(4, 1)); HTuple row, col; HTuple anchor, anchorc; int roiID = -1; for (int i = 0; i < fpTool.fParam[Id - 1].roiP.Count; i++) { for (int j = 0; j < fpTool.fParam[Id - 1].roiP[i].NumOfSection; j++) { roiID++; if (roiID == CurrentIndex - 1) { break; } } if (roiID == CurrentIndex - 1) { roiID = i; break; } } if (fpTool.fParam[Id - 1].roiP[roiID].SelectedType == 0) { if (fpTool.fParam[Id - 1].roiP[roiID].TopDownDist != 0 && fpTool.fParam[Id - 1].roiP[roiID].xDist != 0) { //极值点下降 fpTool.FindMaxPtFallDown(Id, CurrentIndex - 1, out row, out col, out anchor, out anchorc, hwindow_final1, ShowSection, false, hwindow_final2); } else { fpTool.FindMaxPt(Id, CurrentIndex - 1, out row, out col, out anchor, out anchorc, hwindow_final2, ShowSection, false, hwindow_final1); } } else { fpTool.FindMaxPtFallDown(Id, CurrentIndex - 1, out row, out col, out anchor, out anchorc, hwindow_final1, ShowSection, false, hwindow_final2); } } } private void textBox_Current_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode != Keys.Enter) { return; } string index = textBox_Current.Text.ToString(); bool ok = Regex.IsMatch(index, @"(?i)^[0-9]+$"); if (CurrentIndex == 0 || index == "0") { return; } if (ok) { int num = int.Parse(index); CurrentIndex = num; trackBarControl1.Value = CurrentIndex; } } private void btn_open_Click(object sender, EventArgs e) { MyGlobal.GoSDK.EnableProfle = true; string error = ""; if (!MyGlobal.GoSDK.IsConnected(ref error)) { MessageBox.Show("请先连接Sensor!"); return; } bool ok = MyGlobal.GoSDK.Start(ref error); if (ok != true) { MessageBox.Show(error); } else { MessageBox.Show("打开成功!"); } } ///// <summary> /////保存的数据 ///// </summary> //public static double[,] RCAll; //public static double[][] RArray; //public static double[][] CArray; //public static double[][] Row; //public static double[][] Phi; //public static double StartFov = 0; //public static double Resolution; //public static double yResolution; private void simpleButton2_Click(object sender, EventArgs e)//关闭激光 { string error = ""; bool ok = MyGlobal.GoSDK.Stop(ref error); MyGlobal.GoSDK.EnableProfle = false; if (ok != true) { MessageBox.Show(error); return; } try { List<SagensSdk.Profile> profile = MyGlobal.GoSDK.ProfileList; if (profile != null) { //MyGlobal.globalConfig.dataContext = MyGlobal.GoSDK.context; long SurfaceWidth, SurfaceHeight; SurfaceWidth = profile[0].points.Length; SurfaceHeight = profile.Count; float[] SurfacePointZ = new float[SurfaceWidth * SurfaceHeight]; HObject HeightImage = new HObject(); HObject IntensityImage = new HObject(); //fpTool.GenIntesityProfile(profile, out IntensityImage); MyGlobal.GoSDK.ProfileListToArr(profile, SurfacePointZ); MyGlobal.GoSDK.GenHalconImage(SurfacePointZ, SurfaceWidth, SurfaceHeight, out HeightImage); hwindow_final2.HobjectToHimage(IntensityImage); //HOperatorSet.WriteImage(HeightImage, "tiff", 0, MyGlobal.ModelPath + "\\" + SideName + "H.tiff"); //HOperatorSet.WriteImage(IntensityImage, "tiff", 0, MyGlobal.ModelPath + "\\" + SideName + "I.tiff"); MyGlobal.hWindow_Final[0].HobjectToHimage(IntensityImage); } if (MyGlobal.GoSDK.SurfaceDataZ == null) { MessageBox.Show("未收到数据"); return; } //MyGlobal.globalConfig.dataContext = MyGlobal.GoSDK.context; // byte[] SurfacePointZ = MyGlobal.GoSDK.SurfaceDataIntensity; //float[] SufaceHz = MyGlobal.GoSDK.SurfaceDataZ; //long SurfaceWidth, SurfaceHeight; //SurfaceWidth = MyGlobal.GoSDK.surfaceWidth; //SurfaceHeight = MyGlobal.GoSDK.surfaceHeight; //if (SurfacePointZ != null) //{ // MyGlobal.GoSDK.GenHalconImage(SurfacePointZ, SurfaceWidth, SurfaceHeight, out IntensityImage); // hwindow_final2.HobjectToHimage(IntensityImage); // HOperatorSet.WriteImage(IntensityImage, "tiff", 0, MyGlobal.DataPath + "ProfileTemp\\" + SideName + "I.tiff"); //} //else //{ // MessageBox.Show("未收到亮度数据"); // return; //} //if (SufaceHz!=null) //{ // MyGlobal.GoSDK.GenHalconImage(SufaceHz, SurfaceWidth, SurfaceHeight, out HeightImage); // HOperatorSet.WriteImage(HeightImage, "tiff", 0, MyGlobal.DataPath + "ProfileTemp\\" + SideName + "H.tiff"); //} simpleButton3.Enabled = true; simpleButton4.Enabled = true; MessageBox.Show("OK"); } catch (Exception ex) { MessageBox.Show(ex.Message); } } //List<HTuple> RowCoord = new List<HTuple>(); //List<HTuple> ColCoord = new List<HTuple>(); private void simpleButton1_Click(object sender, EventArgs e) { try { FolderBrowserDialog opf = new FolderBrowserDialog(); opf.SelectedPath = "\\"; if (opf.ShowDialog() == DialogResult.OK) { //string file = opf.FileName; //if (!file.Contains(".tiff")) //{ // return; //} SelectedPath = opf.SelectedPath; ChangeSide(); simpleButton3.Enabled = true; simpleButton4.Enabled = true; } } catch (Exception) { throw; } } string SelectedPath = ""; bool NotUseFix = false; private void ChangeSide() { CurrentRowIndex = 0; fpTool.Init(FindType, isRight, ToolType); textBox_Current.Text = "0"; textBox_Total.Text = "0"; CurrentIndex = 0; int Id = Convert.ToInt32(SideName.Substring(4, 1)) - 1; string Path1 = ""; if (MyGlobal.ImageMulti.Count >= Id + 1 && SelectedPath == "") { IntensityImage = MyGlobal.ImageMulti[Id][0]; if (MyGlobal.globalConfig.enableAlign) { if (MyGlobal.ImageMulti[Id].Length < 3) { MessageBox.Show("请重新加载数据"); return; } HeightImage = MyGlobal.ImageMulti[Id][2]; OriginImage = MyGlobal.ImageMulti[Id][1]; } else { HeightImage = MyGlobal.ImageMulti[Id][1]; OriginImage = null; } } else { RoiIsMoving = true; LoadToUI(Id); RoiIsMoving = false; return; //读取指定路径下或选择路径下图片 if (File.Exists(Path1 + "\\" + SideName + "H.tiff")) { //HeightImage.Dispose(); HOperatorSet.ReadImage(out HeightImage, Path1 + "\\" + SideName + "H.tiff"); } if (File.Exists(Path1 + "\\" + SideName + "I.tiff")) { //IntensityImage.Dispose(); HOperatorSet.ReadImage(out IntensityImage, Path1 + "\\" + SideName + "I.tiff"); } } if (!HeightImage.IsInitialized()) { return; } //PseudoColor.GrayToPseudoColor(HeightImage, out RGBImage, true, -20, 10); //PseudoColor.HeightAreaToPseudoColor(HeightImage, out RGBImage, -20, 10, fpTool.fParam[Id].MinZ, fpTool.fParam[Id].MaxZ); //hwindow_final2.HobjectToHimage(RGBImage); hwindow_final2.HobjectToHimage(IntensityImage); if (!NotUseFix && !FindType.Contains("Fix")) { string ok = ""; if (ToolType == MyGlobal.ToolType_GlueGuide) { if (isRight) { ok = MyGlobal.Right_findPointTool_Fix.FindIntersectPoint(Id + 1, HeightImage, out intersection, hwindow_final2, true); } else { ok = MyGlobal.Left_findPointTool_Fix.FindIntersectPoint(Id + 1, HeightImage, out intersection, hwindow_final2, true); } } else { //标定 if (isRight) { ok = MyGlobal.Right_Calib_Fix.FindIntersectPoint(Id + 1, HeightImage, out intersection, hwindow_final2, true); } else { ok = MyGlobal.Left_Calib_Fix.FindIntersectPoint(Id + 1, HeightImage, out intersection, hwindow_final2, true); } } if (ok != "OK") { MessageBox.Show(ok); } HTuple homMaxFix = new HTuple(); double orignalDeg = fpTool.intersectCoordList[Id].Angle; double currentDeg = intersection.Angle; HOperatorSet.VectorAngleToRigid(fpTool.intersectCoordList[Id].Row, fpTool.intersectCoordList[Id].Col, orignalDeg, intersection.Row, intersection.Col, currentDeg, out homMaxFix); //HOperatorSet.VectorAngleToRigid(0, 0, 0, 0, 0, 0, out homMaxFix); //转换Roi if (fpTool.roiList2[Id].Count > 0 && homMaxFix.Length > 0) { for (int i = 0; i < fpTool.roiList2[Id].Count; i++) { List<ROI> temproi = new List<ROI>(); HTuple tempR = new HTuple(); HTuple tempC = new HTuple(); HTuple orignal = fpTool.roiList2[Id][i].getModelData(); HOperatorSet.AffineTransPoint2d(homMaxFix, orignal[0], orignal[1], out tempR, out tempC); roiController2.viewController.ShowAllRoiModel = -1; //角度 //角度 HTuple sx, sy, theta, deltaAngle, tx, ty; HOperatorSet.HomMat2dToAffinePar(homMaxFix, out sx, out sy, out deltaAngle, out theta, out tx, out ty); double tempPhi = orignal[2] + deltaAngle; hwindow_final2.viewWindow.genRect2(tempR, tempC, tempPhi, orignal[3], orignal[4], ref temproi); fpTool.roiList2[Id][i] = temproi[0]; } roiController2.viewController.ShowAllRoiModel = 0; roiController2.viewController.repaint(0); } } else { if (fpTool.roiList2[Id].Count > 0) { fpTool.roiList2[Id].Clear(); fpTool.Init(FindType, isRight, ToolType); hwindow_final2.viewWindow.displayROI(ref fpTool.roiList2[Id]); roiController2.viewController.ShowAllRoiModel = 0; roiController2.viewController.repaint(0); } } RoiIsMoving = true; LoadToUI(Id); RoiIsMoving = false; //textBox_SingleOffset.Text = fpTool.fParam[Id].SigleZoffset.ToString(); //textBox_Total.Text = MyGlobal.globalConfig.TotalZoffset.ToString(); FindPointTool.RArray = null; FindPointTool.CArray = null; FindPointTool.Row = null; //if (fpTool.roiList[Id].Count > 0) //{ // hwindow_final1.viewWindow.displayROI(ref fpTool.roiList[Id]); //} //HSystem.SetSystem("flush_graphic", "true"); } void UpdateRoiParam() { for (int i = 0; i < fpTool.roiList2.Length; i++) { for (int j = 0; j < fpTool.roiList2[i].Count; j++) { HTuple roiData = fpTool.roiList2[i][j].getModelData(); fpTool.fParam[i].roiP[j].CenterRow = roiData[0]; fpTool.fParam[i].roiP[j].CenterCol = roiData[1]; fpTool.fParam[i].roiP[j].phi = roiData[2]; fpTool.fParam[i].roiP[j].Len1 = roiData[3]; fpTool.fParam[i].roiP[j].Len2 = roiData[4]; } } } public void GetCurrentFix() { try { int Id = Convert.ToInt32(SideName.Substring(4, 1)) - 1; IntersetionCoord intersect = new IntersetionCoord(); //string ok = MyGlobal.flset2.FindIntersectPoint(Id + 1, HeightImage, out intersect); HTuple homMaxFix = new HTuple(); HOperatorSet.VectorAngleToRigid(fpTool.intersectCoordList[Id].Row, fpTool.intersectCoordList[Id].Col, 0, intersect.Row, intersect.Col, 0, out homMaxFix); fpTool.intersectCoordList[Id] = intersect; } catch (Exception) { throw; } } int trackBarValue1 = 0; int trackBarValue2 = 0; private void trackBar1_Scroll(object sender, EventArgs e) { try { TrackBar tbar = (TrackBar)sender; //if (tbar.Name == "trackBar1") //{ // label_S.Text = trackBar1.Value.ToString(); // trackBarValue1 = trackBar1.Value; //} //else //{ // label_E.Text = trackBar2.Value.ToString(); // trackBarValue2 = trackBar2.Value; //} //button11_Click(sender, e); int Id = Convert.ToInt32(SideName.Substring(4, 1)); HTuple row, col; HTuple anchor, anchorc; //fpTool.FindMaxPt(Id, CurrentIndex - 1, out row, out col, out anchor, out anchorc, hwindow_final1, ShowSection); int roiID = -1; for (int i = 0; i < fpTool.fParam[Id - 1].roiP.Count; i++) { for (int j = 0; j < fpTool.fParam[Id - 1].roiP[i].NumOfSection; j++) { roiID++; if (roiID == CurrentIndex - 1) { break; } } if (roiID == CurrentIndex - 1) { roiID = i; break; } } if (fpTool.fParam[Id - 1].roiP[roiID].SelectedType == 0) { if (fpTool.fParam[Id - 1].roiP[roiID].TopDownDist != 0 && fpTool.fParam[Id - 1].roiP[roiID].xDist != 0) { fpTool.FindMaxPtFallDown(Id, CurrentIndex - 1, out row, out col, out anchor, out anchorc, hwindow_final1, ShowSection, false, hwindow_final2); } else { fpTool.FindMaxPt(Id, CurrentIndex - 1, out row, out col, out anchor, out anchorc, hwindow_final2, ShowSection, false, hwindow_final1); } } else { fpTool.FindMaxPtFallDown(Id, CurrentIndex - 1, out row, out col, out anchor, out anchorc, hwindow_final1, ShowSection, false, hwindow_final2); } //if (trackBarValue1<trackBarValue2) //{ // HTuple row2, col2; // ShowProfile(out row2,out col2); // HTuple newRow = row2; HTuple newCol = col2; // int start = 0; int end = 0; // if (trackBarValue2 >= row2.Length) // { // trackBarValue2 = row2.Length - 1; // } // start = trackBarValue1; // end = trackBarValue2; // HTuple rowLast = newRow.TupleSelectRange(start, end); // HTuple colLast = newCol.TupleSelectRange(start, end); // HObject ContourSelect = new HObject(); // HOperatorSet.GenRegionPoints(out ContourSelect, rowLast, colLast); // //HOperatorSet.GenContourPolygonXld(out ContourSelect, rowLast, colLast); // hwindow_final1.viewWindow.displayHobject(ContourSelect, "blue"); //} } catch (Exception) { throw; } } private void button11_Click(object sender, EventArgs e) { if (trackBarValue1 < trackBarValue2 && FindPointTool.RArray.GetLength(0) > 0) { if (trackBarValue1 < trackBarValue2) { HTuple row2 = new HTuple(), col2 = new HTuple(); //ShowProfile(CurrentIndex - 1, out row2, out col2); HTuple newRow = row2; HTuple newCol = col2; int start = 0; int end = 0; if (trackBarValue2 >= row2.Length) { trackBarValue2 = row2.Length - 1; } start = trackBarValue1; end = trackBarValue2; HTuple rowLast = newRow.TupleSelectRange(start, end); HTuple colLast = newCol.TupleSelectRange(start, end); HObject ContourSelect = new HObject(); HOperatorSet.GenRegionPoints(out ContourSelect, rowLast, colLast); //HOperatorSet.GenContourPolygonXld(out ContourSelect, rowLast, colLast); if (ShowSection) { hwindow_final1.viewWindow.displayHobject(ContourSelect, "blue"); } } } } private void cb_LorR_CheckedChanged(object sender, EventArgs e) { int Id = Convert.ToInt32(SideName.Substring(4, 1)) - 1; //fpTool.fParam[Id].BeLeft = cb_LorR.Checked; } private void textBox_Start_TextChanged(object sender, EventArgs e) { if (isLoading) { return; } TextBox tb = (TextBox)sender; string Num = tb.Text.ToString(); bool ok = Regex.IsMatch(Num, @"(?i)^(\-[0-9]{1,}[.][0-9]*)+$") || Regex.IsMatch(Num, @"(?i)^(\-[0-9]{1,}[0-9]*)+$") || Regex.IsMatch(Num, @"(?i)^([0-9]{1,}[0-9]*)+$"); if (ok) { int Id = Convert.ToInt32(SideName.Substring(4, 1)) - 1; switch (tb.Name) { case "textBox_Start": //fpTool.fParam[Id].StartPt = int.Parse(Num); break; case "textBox_End": //fpTool.fParam[Id].EndPt = int.Parse(Num); break; case "tb_Updown": //fpTool.fParam[Id].UpDownDist = double.Parse(Num); break; } } } private void button1_Click(object sender, EventArgs e) { HTuple Row = new HTuple(), Col = new HTuple(); int Id = Convert.ToInt32(SideName.Substring(4, 1)); //string ok = Fit(Id ,out Row, out Col,hwindow_final1); for (int i = 0; i < FindPointTool.RArray.GetLength(0); i++) { HTuple row, col; HTuple anchor, anchorc; fpTool.FindMaxPt(Id, i, out row, out col, out anchor, out anchorc, hwindow_final1); Row = Row.TupleConcat(row); Col = Col.TupleConcat(col); } //if (ok!="OK") //{ // MessageBox.Show(ok); //} HObject line = new HObject(); HOperatorSet.GenContourPolygonXld(out line, Row, Col); HTuple Rowbg, Colbg, RowEd, ColEd, Nr, Nc, Dist; HOperatorSet.FitLineContourXld(line, "tukey", -1, 0, 5, 2, out Rowbg, out Colbg, out RowEd, out ColEd, out Nr, out Nc, out Dist); HObject Contourline = new HObject(); HOperatorSet.GenContourPolygonXld(out Contourline, Rowbg.TupleConcat(RowEd), Colbg.TupleConcat(ColEd)); //HOperatorSet.SmoothContoursXld(line, out Contourline, 25); hwindow_final2.viewWindow.displayHobject(line); hwindow_final2.viewWindow.displayHobject(Contourline, "green"); MessageBox.Show("拟合成功!"); } private void simpleButton4_Click(object sender, EventArgs e)//上一帧 { if (CurrentIndex == 0) { return; } if (CurrentIndex == 1) { CurrentIndex = 1; textBox_Current.Text = CurrentIndex.ToString(); return; } if (CurrentIndex > 1) { CurrentIndex--; trackBarControl1.Value = CurrentIndex; textBox_Current.Text = CurrentIndex.ToString(); //button11_Click(sender, e); int Id = Convert.ToInt32(SideName.Substring(4, 1)); HTuple row, col; HTuple anchor, anchorc; //fpTool.FindMaxPt(Id, CurrentIndex - 1, out row, out col, out anchor, out anchorc, hwindow_final1, ShowSection); int roiID = -1; for (int i = 0; i < fpTool.fParam[Id - 1].roiP.Count; i++) { for (int j = 0; j < fpTool.fParam[Id - 1].roiP[i].NumOfSection; j++) { roiID++; if (roiID == CurrentIndex - 1) { break; } } if (roiID == CurrentIndex - 1) { roiID = i; break; } } if (fpTool.fParam[Id - 1].roiP[roiID].SelectedType == 0) { if (fpTool.fParam[Id - 1].roiP[roiID].TopDownDist != 0 && fpTool.fParam[Id - 1].roiP[roiID].xDist != 0) { fpTool.FindMaxPtFallDown(Id, CurrentIndex - 1, out row, out col, out anchor, out anchorc, hwindow_final1, ShowSection, false, hwindow_final2); } else { fpTool.FindMaxPt(Id, CurrentIndex - 1, out row, out col, out anchor, out anchorc, hwindow_final2, ShowSection, false, hwindow_final1); } } else { fpTool.FindMaxPtFallDown(Id, CurrentIndex - 1, out row, out col, out anchor, out anchorc, hwindow_final1, ShowSection, false, hwindow_final2); } } } private void simpleButton3_Click(object sender, EventArgs e)//下一帧 { int Total = Convert.ToInt32(textBox_Total.Text.ToString()); if (CurrentIndex >= Total) { CurrentIndex = Total; textBox_Current.Text = CurrentIndex.ToString(); trackBarControl1.Value = CurrentIndex; return; } CurrentIndex++; trackBarControl1.Value = CurrentIndex; textBox_Current.Text = CurrentIndex.ToString(); //HTuple row, col; //ShowProfile(out row, out col); //button11_Click(sender, e); int Id = Convert.ToInt32(SideName.Substring(4, 1)); HTuple row, col; HTuple anchor, anchorc; int roiID = -1; for (int i = 0; i < fpTool.fParam[Id - 1].roiP.Count; i++) { for (int j = 0; j < fpTool.fParam[Id - 1].roiP[i].NumOfSection; j++) { roiID++; if (roiID == CurrentIndex - 1) { break; } } if (roiID == CurrentIndex - 1) { roiID = i; break; } } if (fpTool.fParam[Id - 1].roiP[roiID].SelectedType == 0) { if (fpTool.fParam[Id - 1].roiP[roiID].TopDownDist != 0 && fpTool.fParam[Id - 1].roiP[roiID].xDist != 0) { fpTool.FindMaxPtFallDown(Id, CurrentIndex - 1, out row, out col, out anchor, out anchorc, hwindow_final1, ShowSection, false, hwindow_final2); } else { fpTool.FindMaxPt(Id, CurrentIndex - 1, out row, out col, out anchor, out anchorc, hwindow_final2, ShowSection, false, hwindow_final1); } } else { fpTool.FindMaxPtFallDown(Id, CurrentIndex - 1, out row, out col, out anchor, out anchorc, hwindow_final1, ShowSection, false, hwindow_final2); } } bool ShowSection = false; private void checkBox1_CheckedChanged(object sender, EventArgs e)//显示 { ShowSection = checkBox1.Checked; } string SideName = "Side1"; public void FitLineParamSave() { int Id = Convert.ToInt32(SideName.Substring(4, 1)) - 1; ParamPath.ToolType = ToolType; ParamPath.ParaName = FindType + "_" + SideName; ParamPath.IsRight = isRight; string Name = ToolType; //if (Name != "Fix") //{ // if (isRight) // { // StaticOperate.WriteXML(fpTool.fParam[Id], ParamPath.ParamDir + SideName + ".xml"); // hwindow_final1.viewWindow.saveROI(fpTool.roiList[Id], ParamPath.ParamDir + SideName + "_Section.roi"); // hwindow_final2.viewWindow.saveROI(fpTool.roiList2[Id], ParamPath.ParamDir + SideName + "_Region.roi"); // } // else // { // StaticOperate.WriteXML(fpTool.fParam[Id], ParamPath.ParamDir + SideName + ".xml"); // hwindow_final1.viewWindow.saveROI(fpTool.roiList[Id], ParamPath.ParamDir + SideName + "_Section.roi"); // hwindow_final2.viewWindow.saveROI(fpTool.roiList2[Id], ParamPath.ParamDir + SideName + "_Region.roi"); // } //} //else //{ StaticOperate.WriteXML(fpTool.fParam[Id], ParamPath.ParamDir + SideName + ".xml"); hwindow_final1.viewWindow.saveROI(fpTool.roiList[Id], ParamPath.ParamDir + SideName + "_Section.roi"); hwindow_final2.viewWindow.saveROI(fpTool.roiList2[Id], ParamPath.ParamDir + SideName + "_Region.roi"); //} isSave = true; if (FindType == "Fix") { if (MessageBox.Show("是否重新写入模板位置?", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes) { fpTool.intersectCoordList[Id] = intersection; if (intersection.Row==0 && intersection.Col==0) { MessageBox.Show("当前模板未运行!请运行成功后再写入!"); } else { StaticOperate.WriteXML(fpTool.intersectCoordList[Id], ParamPath.Path_Param); } } } else { if (intersection.Row == 0 && intersection.Col == 0 && NotUseFix) { MessageBox.Show("保存成功!"); } else { ParamPath.ParaName = "Fix" + "_" + SideName; fpTool.intersectCoordList[Id] = intersection; StaticOperate.WriteXML(fpTool.intersectCoordList[Id], ParamPath.Path_Param); } } //MyGlobal.flset2.Init(); if (ToolType == MyGlobal.ToolType_GlueGuide) { if (isRight) { MyGlobal.Right_findPointTool_Find.Init("FitLineSet", isRight, ToolType); MyGlobal.Right_findPointTool_Fix.Init("Fix", isRight, ToolType); } else { MyGlobal.Left_findPointTool_Find.Init("FitLineSet", isRight, ToolType); MyGlobal.Left_findPointTool_Fix.Init("Fix", isRight, ToolType); } } else { if (isRight) { //MyGlobal.Right_findPointTool_Find.Init("FitLineSet", isRight, ToolType); MyGlobal.Right_Calib_Fix.Init("Fix", isRight, ToolType); } else { //MyGlobal.Left_findPointTool_Find.Init("FitLineSet", isRight, ToolType); MyGlobal.Left_Calib_Fix.Init("Fix", isRight, ToolType); } } MessageBox.Show("保存成功!"); } private void button2_Click(object sender, EventArgs e)//保存参数 { RoiParam.isInvoke = false; if (isRight) { if (MessageBox.Show("是否保存右工位参数", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes) { FitLineParamSave(); } } else { if (MessageBox.Show("是否保存左工位参数", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes) { FitLineParamSave(); } } RoiParam.isInvoke = true; //simpleButton7_Click(sender, e); } string CurrentSide = ""; bool isSave = true; bool NoChange = false; bool isCloing = false; private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)//选择边 { if (isCloing || NoChange || comboBox1.SelectedItem.ToString() == CurrentSide) { isCloing = false; NoChange = false; return; } if (comboBox1.SelectedItem != null) { if (isSave) { //isSave = false; } else { DialogResult result = MessageBox.Show("当前参数未保存,是否切换?", "提示:", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result != DialogResult.Yes) { if (comboBox1.SelectedItem.ToString() != CurrentSide) { NoChange = true; comboBox1.SelectedItem = CurrentSide; NoChange = false; } return; } } SideName = comboBox1.SelectedItem.ToString(); ParamPath.ParaName = FindType + "_" + SideName; ParamPath.IsRight = isRight; hwindow_final1.viewWindow.notDisplayRoi(); hwindow_final2.viewWindow.notDisplayRoi(); hwindow_final1.ClearWindow(); hwindow_final2.ClearWindow(); RoiParam.isInvoke = false; ChangeSide(); RoiParam.isInvoke = true; CurrentSide = comboBox1.SelectedItem.ToString(); if (!HeightImage.IsInitialized()) { return; } //int Id = Convert.ToInt32(SideName.Substring(4, 1)) - 1; //if (File.Exists(MyGlobal.ConfigPath + SideName + ".xml")) //{ // fpTool.fParam[Id] = (FitProfileParam)StaticOperate.ReadXML(MyGlobal.ConfigPath + SideName + ".xml", typeof(FitProfileParam)); // LoadToUI(Id); //} //if (File.Exists(MyGlobal.ConfigPath + SideName[Id] + "_Section.roi")) //{ // hwindow_final1.viewWindow.loadROI(MyGlobal.ConfigPath + SideName[Id] + "_Section.roi", out fpTool.roiList[Id]); //} //if (File.Exists(MyGlobal.ConfigPath + SideName[Id] + "_Region.roi")) //{ // hwindow_final2.viewWindow.loadROI(MyGlobal.ConfigPath + SideName[Id] + "_Region.roi", out fpTool.fpTool.roiList2[Id]); //} } } private void button3_Click(object sender, EventArgs e) { //if (roiCount==1 || RArray.GetLength(0)==0) //{ // hwindow_final1.viewWindow.displayROI(ref fpTool.roiList); // return; //} //roiController.setROIShape(new ROIRectangle1()); //roiCount++; } bool isGenSection = false; private void button4_Click(object sender, EventArgs e)//截图区域 { int Id = Convert.ToInt32(SideName.Substring(4, 1)) - 1; hwindow_final2.viewWindow.notDisplayRoi(); if (fpTool.roiList2[Id].Count > 0) { if (SelectAll) { roiController2.viewController.ShowAllRoiModel = -1; } hwindow_final2.viewWindow.displayROI(ref fpTool.roiList2[Id]); } if (hwindow_final2.Image == null || !hwindow_final2.Image.IsInitialized()) { return; } roiController2.setROIShape(new ROIRectangle2()); isGenSection = true; //fpTool.fpTool.roiList2[Id].Add(new ROIRectangle2()); } private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)//右键删除 { int Id = Convert.ToInt32(SideName.Substring(4, 1)) - 1; if (dataGridView1.CurrentCell == null) { return; } int RowId = dataGridView1.CurrentCell.RowIndex; RowId = CurrentRowIndex; string Name = dataGridView1.Rows[RowId].Cells[1].Value.ToString(); if (fpTool.roiList2[Id].Count > 0 && roiController2.ROIList.Count == fpTool.roiList2[Id].Count) { if (RowId >= 0) { fpTool.roiList2[Id].RemoveAt(RowId); roiController2.setActiveROIIdx(RowId); roiController2.removeActive(); fpTool.fParam[Id].roiP.RemoveAt(RowId); fpTool.roiList[Id].RemoveAt(RowId); fpTool.fParam[Id].DicPointName.RemoveAt(RowId); dataGridView1.Rows.RemoveAt(RowId); //排序 for (int i = 0; i < dataGridView1.Rows.Count; i++) { dataGridView1.Rows[i].Cells[0].Value = i + 1; } //int[] values = DicPointName[Id].Values.ToArray(); //string[] keys = DicPointName[Id].Keys.ToArray(); ////listBox1.Items.CopyTo(keys, 0); //keys = richTextBox1.Lines; //for (int i = Index; i < DicPointName[Id].Count; i++) //{ // int value1 = DicPointName[Id][keys[i]]; // DicPointName[Id][keys[i]] = value1 - 1;//前移 //} } //刷新界面roi hwindow_final2.viewWindow.notDisplayRoi(); if (fpTool.roiList2[Id].Count > 0) { hwindow_final2.viewWindow.displayROI(ref fpTool.roiList2[Id]); } if (fpTool.roiList2[Id].Count > 0) { hwindow_final2.viewWindow.selectROI(0); } if (RowId == CopyId) { CopyId = -1; } } } private void 删除所有ToolStripMenuItem_Click(object sender, EventArgs e)//右键删除所有 { if (dataGridView1.Rows.Count == 0) { return; } if (!(MessageBox.Show("是否删除所有区域", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)) { return; } int Id = Convert.ToInt32(SideName.Substring(4, 1)) - 1; if (fpTool.roiList2[Id].Count > 0) { fpTool.roiList2[Id].Clear(); hwindow_final2.viewWindow.notDisplayRoi(); dataGridView1.Rows.Clear(); fpTool.roiList[Id].Clear(); hwindow_final1.viewWindow.notDisplayRoi(); PreSelect = ""; fpTool.fParam[Id].DicPointName.Clear(); if (Id >= 0) { fpTool.fParam[Id].roiP.Clear(); } } CurrentRowIndex = -1; CopyId = -1; } List<ROI> temp = new List<ROI>(); private void textBox1_TextChanged(object sender, EventArgs e) { int SideId = Convert.ToInt32(SideName.Substring(4, 1)) - 1; TextBox tb = (TextBox)sender; string index = tb.Text.ToString(); bool ok1 = Regex.IsMatch(index, @"^[-]?\d+[.]?\d*$");//是否为数字 bool ok = Regex.IsMatch(index, @"^([-]?)\d*$");//是否为整数 if (!(ok && ok1) || fpTool.roiList2[SideId].Count == 0 || RoiIsMoving) { return; } try { double a = Convert.ToDouble(index); int num = (int)a; int roiID = dataGridView1.CurrentCell.RowIndex; roiID = CurrentRowIndex; int count = dataGridView1.SelectedCells.Count; List<int> rowInd = new List<int>(); for (int i = 0; i < count; i++) { int Ind = dataGridView1.SelectedCells[i].RowIndex; if (!rowInd.Contains(Ind)) { rowInd.Add(Ind); } } for (int i = 0; i < rowInd.Count; i++) { roiID = rowInd[i]; HTuple[] lineCoord = new HTuple[1]; switch (tb.Name) { case "textBox_Num": fpTool.fParam[SideId].roiP[roiID].NumOfSection = num; fpTool.DispSection((ROIRectangle2)fpTool.roiList2[SideId][roiID], SideId, roiID, out lineCoord, hwindow_final2); break; case "textBox_Len": fpTool.fParam[SideId].roiP[roiID].Len1 = num; HTuple temp = new HTuple(); List<ROI> temproi = new List<ROI>(); temp = fpTool.roiList2[SideId][roiID].getModelData(); hwindow_final2.viewWindow.genRect2(fpTool.fParam[SideId].roiP[roiID].CenterRow, fpTool.fParam[SideId].roiP[roiID].CenterCol, fpTool.fParam[SideId].roiP[roiID].phi, fpTool.fParam[SideId].roiP[roiID].Len1, fpTool.fParam[SideId].roiP[roiID].Len2, ref temproi); //hwindow_final2.viewWindow.genRect2(temp[0].D, temp[1].D, temp[2].D, fpTool.fParam[SideId].roiP[roiID].Len1, fpTool.fParam[SideId].roiP[roiID].Len2, ref temproi); fpTool.roiList2[SideId][roiID] = temproi[0]; //hwindow_final2.viewWindow.notDisplayRoi(); //hwindow_final2.viewWindow.displayROI(ref fpTool.roiList2[SideId]); //hwindow_final2.viewWindow.selectROI(roiID); //DispSection((ROIRectangle2)fpTool.roiList2[SideId][roiID], SideId, roiID, out lineCoord, hwindow_final2); break; case "textBox_Width": fpTool.fParam[SideId].roiP[roiID].Len2 = num; HTuple temp3 = new HTuple(); temp3 = fpTool.roiList2[SideId][roiID].getModelData(); List<ROI> temproi3 = new List<ROI>(); hwindow_final2.viewWindow.genRect2(fpTool.fParam[SideId].roiP[roiID].CenterRow, fpTool.fParam[SideId].roiP[roiID].CenterCol, fpTool.fParam[SideId].roiP[roiID].phi, fpTool.fParam[SideId].roiP[roiID].Len1, fpTool.fParam[SideId].roiP[roiID].Len2, ref temproi3); fpTool.roiList2[SideId][roiID] = temproi3[0]; //hwindow_final2.viewWindow.notDisplayRoi(); //hwindow_final2.viewWindow.displayROI(ref fpTool.roiList2[SideId]); //hwindow_final2.viewWindow.selectROI(roiID); //DispSection((ROIRectangle2)fpTool.roiList2[SideId][roiID], SideId, roiID, out lineCoord, hwindow_final2); break; case "textBox_Row": fpTool.fParam[SideId].roiP[roiID].CenterRow = num; HTuple temp4 = new HTuple(); temp4 = fpTool.roiList2[SideId][roiID].getModelData(); List<ROI> temproi4 = new List<ROI>(); hwindow_final2.viewWindow.genRect2(fpTool.fParam[SideId].roiP[roiID].CenterRow, fpTool.fParam[SideId].roiP[roiID].CenterCol, fpTool.fParam[SideId].roiP[roiID].phi, fpTool.fParam[SideId].roiP[roiID].Len1, fpTool.fParam[SideId].roiP[roiID].Len2, ref temproi4); fpTool.roiList2[SideId][roiID] = temproi4[0]; //hwindow_final2.viewWindow.notDisplayRoi(); //hwindow_final2.viewWindow.displayROI(ref fpTool.roiList2[SideId]); //hwindow_final2.viewWindow.selectROI(roiID); //DispSection((ROIRectangle2)fpTool.roiList2[SideId][roiID], SideId, roiID, out lineCoord, hwindow_final2); break; case "textBox_Col": fpTool.fParam[SideId].roiP[roiID].CenterCol = num; HTuple temp5 = new HTuple(); temp3 = fpTool.roiList2[SideId][roiID].getModelData(); List<ROI> temproi5 = new List<ROI>(); hwindow_final2.viewWindow.genRect2(fpTool.fParam[SideId].roiP[roiID].CenterRow, fpTool.fParam[SideId].roiP[roiID].CenterCol, fpTool.fParam[SideId].roiP[roiID].phi, fpTool.fParam[SideId].roiP[roiID].Len1, fpTool.fParam[SideId].roiP[roiID].Len2, ref temproi5); fpTool.roiList2[SideId][roiID] = temproi5[0]; //hwindow_final2.viewWindow.notDisplayRoi(); //hwindow_final2.viewWindow.displayROI(ref fpTool.roiList2[SideId]); //hwindow_final2.viewWindow.selectROI(roiID); //DispSection((ROIRectangle2)fpTool.roiList2[SideId][roiID], SideId, roiID, out lineCoord, hwindow_final2); break; case "textBox_phi": HTuple rad = new HTuple(); HOperatorSet.TupleRad(num, out rad); fpTool.fParam[SideId].roiP[roiID].phi = rad; HTuple temp6 = new HTuple(); temp3 = fpTool.roiList2[SideId][roiID].getModelData(); List<ROI> temproi6 = new List<ROI>(); hwindow_final2.viewWindow.genRect2(fpTool.fParam[SideId].roiP[roiID].CenterRow, fpTool.fParam[SideId].roiP[roiID].CenterCol, fpTool.fParam[SideId].roiP[roiID].phi, fpTool.fParam[SideId].roiP[roiID].Len1, fpTool.fParam[SideId].roiP[roiID].Len2, ref temproi6); fpTool.roiList2[SideId][roiID] = temproi6[0]; //hwindow_final2.viewWindow.notDisplayRoi(); //hwindow_final2.viewWindow.displayROI(ref fpTool.roiList2[SideId]); //hwindow_final2.viewWindow.selectROI(roiID); //DispSection((ROIRectangle2)fpTool.roiList2[SideId][roiID], SideId, roiID, out lineCoord, hwindow_final2); break; case "textBox_Deg": fpTool.fParam[SideId].roiP[roiID].AngleOfProfile = num; break; } } hwindow_final2.viewWindow.notDisplayRoi(); hwindow_final2.viewWindow.displayROI(ref fpTool.roiList2[SideId]); hwindow_final2.viewWindow.selectROI(roiID); } catch (Exception) { throw; } } private int Ignore = 0; bool SelectAll = false; private void checkBox2_CheckedChanged(object sender, EventArgs e)//右键全选 { SelectAll = checkBox2.Checked; } private void simpleButton7_Click(object sender, EventArgs e)//run按钮 { try { if (/*!RGBImage.IsInitialized() || */!HeightImage.IsInitialized()) { return; } int Id = Convert.ToInt32(SideName.Substring(4, 1)); double[][] Rcoord, Ccoord, Zcoord; string[][] Str; hwindow_final2.ClearWindow(); //hwindow_final2.HobjectToHimage(RGBImage); hwindow_final2.HobjectToHimage(IntensityImage); if (ToolType == MyGlobal.ToolType_GlueGuide) { if (FindType == "Fix") { //HObject image = new HObject(); //HOperatorSet.GenImageConst(out image, "byte", 1500, 20000); string ok1 = ""; if (isRight) { ok1 = fpTool.FindIntersectPoint(Id, HeightImage, out intersection, hwindow_final2, true); } else { ok1 = fpTool.FindIntersectPoint(Id, HeightImage, out intersection, hwindow_final2, true); } if (ok1 != "OK") { MessageBox.Show(ok1); } } else { //ChangeSide已定位Roi 不用定位 HTuple[] original = new HTuple[2]; string ok = fpTool.FindPoint(Id, isRight, HeightImage, HeightImage, out Rcoord, out Ccoord, out Zcoord, out Str, out original, null, hwindow_final2, true, null, OriginImage); if (ok != "OK") { MessageBox.Show(ok); } } } else { //标定 if (FindType == "Fix") { string ok1 = ""; ok1 = fpTool.FindIntersectPoint(Id, HeightImage, out intersection, hwindow_final2, true); if (ok1 != "OK") { MessageBox.Show(ok1); } } else { //ChangeSide已定位Roi 不用定位 HTuple[] original = new HTuple[2]; string ok = fpTool.FindPoint(Id, HeightImage, HeightImage, out _lines, hwindow_final2, true, null, OriginImage); if (ok != "OK") { MessageBox.Show(ok); } } } int Total = FindPointTool.RArray.GetLength(0); textBox_Total.Text = Total.ToString(); textBox_Current.Text = "1"; CurrentIndex = 1; trackBarControl1.Properties.Maximum = Total; trackBarControl1.Properties.Minimum = 1; trackBarControl1.Value = 1; trackBarControl1_ValueChanged(sender, e); } catch (Exception) { throw; } } //#region 弃用 //[Obsolete] //public string Init() //{ // try // { // HWindow_Final hwnd = new HWindow_Final(); // string[] SideName = { "Side1", "Side2", "Side3", "Side4" }; // string initError = "OK"; // for (int i = 0; i < 4; i++) // { // fpTool.fParam[i] = new FitProfileParam(); // fpTool.roiList[i] = new List<ROI>(); // fpTool.roiList2[i] = new List<ROI>(); // //fpTool.roiList3[i] = new List<ROI>(); // fpTool.fParam[i].DicPointName = new List<string>(); // //hwindow_final2.viewWindow.genRect1(400, 400, 1000, 1000, ref fpTool.roiList3[i]); // hwindow_final2.viewWindow.notDisplayRoi(); // } // for (int i = 0; i < 4; i++) // { // ParamPath.ParaName = "Side" + (i + 1).ToString(); // if (!Directory.Exists(ParamPath.ParamDir)) // { // Directory.CreateDirectory(ParamPath.ParamDir); // } // } // if (ToolType == "Fix") // { // for (int i = 0; i < 4; i++) // { // ParamPath.ParaName = "Side" + (i + 1).ToString(); // if (File.Exists(ParamPath.ParamDir + SideName[i] + ".xml")) // { // fpTool.fParam[i] = (FitProfileParam)StaticOperate.ReadXML(ParamPath.ParamDir + SideName[i] + ".xml", typeof(FitProfileParam)); // } // else // { // initError = "定位参数加载失败"; // continue; // } // if (File.Exists(ParamPath.ParamDir + SideName[i] + "_Section.roi")) // { // hwnd.viewWindow.loadROI(ParamPath.ParamDir + SideName[i] + "_Section.roi", out fpTool.roiList[i]); // hwnd.viewWindow.notDisplayRoi(); // } // else // { // initError = "截面设置Roi加载失败"; // continue; // } // if (File.Exists(ParamPath.ParamDir + SideName[i] + "_Region.roi")) // { // hwnd.viewWindow.loadROI(ParamPath.ParamDir + SideName[i] + "_Region.roi", out fpTool.roiList2[i]); // hwnd.viewWindow.notDisplayRoi(); // } // else // { // initError = "感兴趣区域加载失败"; // continue; // } // if (File.Exists(ParamPath.Path_Param)) // { // fpTool.intersectCoordList[i] = (IntersetionCoord)StaticOperate.ReadXML(ParamPath.Path_Param, typeof(IntersetionCoord)); // } // else // { // initError = "定位设置参数.xml加载失败"; // continue; // } // } // } // else // { // for (int i = 0; i < 4; i++) // { // if (File.Exists(MyGlobal.ConfigPath + SideName[i] + ".xml")) // { // fpTool.fParam[i] = (FitProfileParam)StaticOperate.ReadXML(MyGlobal.ConfigPath + SideName[i] + ".xml", typeof(FitProfileParam)); // } // else // { // initError = "抓边参数加载失败"; // continue; // } // if (File.Exists(MyGlobal.ConfigPath + SideName[i] + "_Section.roi")) // { // hwnd.viewWindow.loadROI(MyGlobal.ConfigPath + SideName[i] + "_Section.roi", out fpTool.roiList[i]); // hwnd.viewWindow.notDisplayRoi(); // } // else // { // initError = "截面设置Roi加载失败"; // continue; // } // if (File.Exists(MyGlobal.ConfigPath + SideName[i] + "_Region.roi")) // { // hwnd.viewWindow.loadROI(MyGlobal.ConfigPath + SideName[i] + "_Region.roi", out fpTool.roiList2[i]); // hwnd.viewWindow.notDisplayRoi(); // } // else // { // initError = "感兴趣区域加载失败"; // continue; // } // ParamPath.ParaName = "Side" + (i + 1).ToString(); // if (File.Exists(ParamPath.Path_Param)) // { // fpTool.intersectCoordList[i] = (IntersetionCoord)StaticOperate.ReadXML(ParamPath.Path_Param, typeof(IntersetionCoord)); // } // else // { // initError = "定位设置参数.xml加载失败"; // continue; // } // } // } // return initError; // } // catch (Exception ex) // { // return "参数设置加载失败:" + ex.Message; // } //} //[Obsolete] //void GenIntesityProfile(List<SagensSdk.Profile> profile, out HObject Image) //{ // int len = profile.Count; // int width = profile[0].points.Length; // byte[] imageArray = new byte[width * len]; // int k = 0; // for (int i = 0; i < len; i++) // { // for (int j = 0; j < width; j++) // { // imageArray[k] = profile[i].points[j].Intensity; // k++; // } // } // Image = new HObject(); // HOperatorSet.GenEmptyObj(out Image); // MyGlobal.GoSDK.GenHalconImage(imageArray, width, len, out Image); //} //[Obsolete] //void GetRowCol(ProfilePoint[] point, out double[] Row, out double[] Col) //{ // long len = point.Length; // Row = new double[len]; Col = new double[len]; // for (int i = 0; i < len; i++) // { // Row[i] = point[i].z / 0.006; // Col[i] = point[i].x / 0.006; // } //} //[Obsolete] //public static string GetXData(ref Dictionary<string, double[]> dic, out List<HTuple> RowCoord) //{ // try // { // RowCoord = new List<HTuple>(); // if (Resolution == 0) // { // return "No Resolution"; // } // int Index = dic.Count; // for (int i = 0; i < Index; i++) // { // RowCoord.Add(new HTuple()); // string key = i.ToString() + "_" + "0"; // if (dic.Keys.Contains(key)) // { // int n = 0; // for (int j = 0; j < dic[key].Length; j++) // { // if (dic[key][j] == -32768) // { // int BB = 0; // } // else // { // RowCoord[i][n] = ((j) * Resolution + StartFov) * 200; // dic[key][n] = dic[key][j] * 200; // n++; // } // } // } // } // return "OK"; // } // catch (Exception) // { // throw; // } //} //[Obsolete] //public static string GetArryData(List<Profile> Profile, out double[,] rc) //{ // int Num = Profile.Count; // int len = Profile[0].points.Length; // //将 X方向添加到最后; // rc = new double[Num + 1, len]; // try // { // for (int i = 0; i < Profile.Count; i++) // { // for (int j = 0; j < Profile[i].points.Length; j++) // { // rc[i, j] = Profile[i].points[j].z; // } // } // return "OK"; // } // catch (Exception ex) // { // return "ProfileDataToArray error " + ex.Message; // } //} //[Obsolete] //public static string GetRC(List<Profile> Profile, out double[][] rArray, out double[][] cArray) //{ // if (MyGlobal.globalConfig.dataContext.xResolution != 0) // { // MyGlobal.globalConfig.dataContext = MyGlobal.GoSDK.context; // Resolution = MyGlobal.globalConfig.dataContext.xResolution; // } // int Num = Profile.Count; // int len = Profile[0].points.Length; // //将 X方向添加到最后; // //rc = new double[Num + 1, len]; // rArray = new double[Num][]; // cArray = new double[Num][]; // try // { // for (int i = 0; i < Profile.Count; i++) // { // rArray[i] = new double[Profile[i].points.Length]; // cArray[i] = new double[Profile[i].points.Length]; // for (int j = 0; j < Profile[i].points.Length; j++) // { // //rc[i, j] = Profile[i].points[j].z; // if (Profile[i].points[j].z != -30) // { // rArray[i][j] = Profile[i].points[j].z * 200; // } // else // { // rArray[i][j] = -Profile[i].points[j].z * 200; // 取反 // } // //rArray[i][j] = Profile[i].points[j].z * 200; // cArray[i][j] = ((j) * Resolution + StartFov) * 200; // } // } // return "OK"; // } // catch (Exception ex) // { // return "ProfileDataToArray error " + ex.Message; // } //} //[Obsolete] //public static string GetC(double[][] rArray, out double[][] cArray) //{ // int Num = rArray.Rank; // Resolution = MyGlobal.globalConfig.dataContext.xResolution; // cArray = new double[Num][]; // try // { // for (int i = 0; i < Num; i++) // { // cArray[i] = new double[rArray[i].Length]; // for (int j = 0; j < rArray[i].Length; j++) // { // cArray[i][j] = ((j) * Resolution + StartFov) * 200; // } // } // return "OK"; // } // catch (Exception ex) // { // return "ProfileDataToArray error " + ex.Message; // } //} //[Obsolete] //public static float[] ArrayToFArr(double[,] Pots) //{ // float[] potArr = new float[(Pots.GetLength(0) - 1) * Pots.GetLength(1)]; // for (int i = 0; i < Pots.GetLength(0) - 1; i++) // { // int mulIndex = i * Pots.GetLength(1); // for (int j = 0; j < Pots.GetLength(1); j++) // { // if (Pots[i, j] != -32768) // { // potArr[mulIndex + j] = (float)Pots[i, j]; // } // else // { // potArr[mulIndex + j] = 0; // } // } // } // return potArr; //} //[Obsolete] //public string ProfileDataToArray(ref double[,] RCAll, out List<HTuple> RowCoord, out List<HTuple> ColCoord, bool load = false) //{ // RowCoord = new List<HTuple>(); // ColCoord = new List<HTuple>(); // try // { // if (load) // { // double start1 = RCAll[RCAll.GetLength(0) - 1, 0]; // double start2 = RCAll[RCAll.GetLength(0) - 1, 1]; // double sub = Math.Abs((start2 - start1) / 200); // Resolution = Math.Round(sub, 3); // //StartFov = start1 / 200; // } // else // { // MyGlobal.globalConfig.dataContext = MyGlobal.GoSDK.context; // Resolution = MyGlobal.globalConfig.dataContext.xResolution; // } // //IniFileOperater IniOperate = new IniFileOperater(IniPath); // //IniOperate.WriteEntry("GocatorSet", "Resolution", Resolution); // //IniOperate.WriteEntry("GocatorSet", "StartFov", StartFov); // for (int i = 0; i < RCAll.GetLength(0); i++) // { // if (i != RCAll.GetLength(0) - 1) // { // RowCoord.Add(new HTuple()); // ColCoord.Add(new HTuple()); // } // int n = 0; // int k = 0; // for (int j = 0; j < RCAll.GetLength(1); j++) // { // if (RCAll[i, j] != -32768) // { // if (i == RCAll.GetLength(0) - 1) //添加到最后 // { // RCAll[i, n] = ((j) * Resolution + StartFov) * 200; // } // else // { // RowCoord[i][n] = RCAll[i, j] * 200; // ColCoord[i][n] = ((j) * Resolution + StartFov) * 200; // } // n++; // } // k++; // } // } // return "OK"; // } // catch (Exception ex) // { // return "ProfileDataToArray error " + ex.Message; // } //} //[Obsolete] ///// <summary> ///// 由点获取轮廓 ///// </summary> ///// <param name="isLeft">是否在左边</param> ///// <param name="IgnorePoints">起始结束忽略点数</param> ///// <param name="Row">输入轮廓行坐标</param> ///// <param name="Col">输入轮廓列坐标</param> ///// <param name="RowNew">输出转换后轮廓列坐标</param> ///// <param name="ColNew">输出转换后轮廓行坐标</param> ///// <param name="Region">输处转换后轮廓Region</param> ///// <returns></returns> //public string GenProfile(bool isLeft, HTuple Row, HTuple Col, out HTuple RowNew, out HTuple ColNew, out HObject Region, out HObject Contour) //{ // RowNew = new HTuple(); ColNew = new HTuple(); Region = new HObject(); // Contour = new HObject(); // try // { // HTuple Lenr = Row.Length; // HTuple Lenc = Col.Length; // HTuple min = Lenr.TupleMin2(Lenc); // Row = -Row.TupleSelectRange(0, min.I - 1); // Col = Col.TupleSelectRange(0, min.I - 1); // HOperatorSet.GenContourPolygonXld(out Contour, Row, Col); // HTuple hommat2DIdentity = new HTuple(); HTuple Hommat2DRotate = new HTuple(); // HTuple Hommat2DTranslate = new HTuple(); // HOperatorSet.HomMat2dIdentity(out hommat2DIdentity); // HTuple ColMin = Col.TupleMin(); // HOperatorSet.HomMat2dTranslate(hommat2DIdentity, 500, -ColMin + 500, out Hommat2DTranslate); // HOperatorSet.AffineTransContourXld(Contour, out Contour, Hommat2DTranslate); // HOperatorSet.GetContourXld(Contour, out RowNew, out ColNew); // HOperatorSet.GenRegionPoints(out Region, RowNew, ColNew); // if (isLeft == false) // { // //找到最高点进行镜像变换 // HTuple Rowmin = RowNew.TupleMin(); // HTuple minInd = RowNew.TupleFindFirst(Rowmin); // HTuple HomMat2DId = new HTuple(); HTuple HomMat2dReflect = new HTuple(); // HOperatorSet.HomMat2dIdentity(out HomMat2DId); // HOperatorSet.HomMat2dReflect(HomMat2DId, Rowmin, ColNew[minInd] + 50, Rowmin + 100, ColNew[minInd] + 50, out HomMat2dReflect); // HOperatorSet.AffineTransContourXld(Contour, out Contour, HomMat2dReflect); // HOperatorSet.AffineTransRegion(Region, out Region, HomMat2dReflect, "nearest_neighbor"); // HOperatorSet.GetContourXld(Contour, out RowNew, out ColNew); // HOperatorSet.GenRegionPoints(out Region, RowNew, ColNew); // } // return "OK"; // } // catch (Exception ex) // { // return "GenProfile error " + ex.Message; // } //} //[Obsolete] //public void ShowProfile(int ProfileId, out HTuple row, out HTuple col, HWindow_Final hwind = null) //{ // row = new HTuple(); col = new HTuple(); // try // { // //显示截取的轮廓 // if (hwind != null) // { // hwind.viewWindow.ClearWindow(); // HObject image = new HObject(); // HOperatorSet.GenImageConst(out image, "byte", 1000, 1000); // hwind.HobjectToHimage(image); // } // if (RArray == null || RArray.GetLength(0) == 0) // { // return; // } // HTuple row1 = -new HTuple(RArray[ProfileId]); // HTuple col1 = new HTuple(CArray[ProfileId]); // if (row1.Length == 0) // { // return; // } // //分辨率 x 0.007--0.01 y 0.035 -- 0.05 // double xResolution = MyGlobal.globalConfig.dataContext.xResolution; // double yResolution = MyGlobal.globalConfig.dataContext.yResolution; // HTuple SeqC = new HTuple(); // //double s1 = Math.Abs(Math.Cos(Phi[ProfileId][4])); // //double s2 = Math.Abs(Math.Sin(Phi[ProfileId][4])); // double s1 = Math.Cos(Phi[ProfileId][4]); // double s2 = Math.Sin(Phi[ProfileId][4]); // double scale = 0; // scale = xResolution * s1 + yResolution * s2; // //if (s1 >= s2) // //{ // // scale = xResolution / s1; // //} // //else // //{ // // scale = yResolution * s2; // //} // //double scale = xResolution * Math.Cos(Phi[CurrentIndex - 1][4]) + yResolution * Math.Sin(Phi[CurrentIndex - 1][4]); // scale = Math.Abs(scale); // HOperatorSet.TupleGenSequence(scale, (row1.Length + 1) * scale, scale, out col1); // col1 = col1 * 200; // int len1 = row1.Length; // col1 = col1.TupleSelectRange(0, len1 - 1); // HTuple rowmin = row1.TupleMin(); // row = row1 - rowmin + 150; // col = col1; // if (hwind != null) // { // HObject contour = new HObject(); // HOperatorSet.GenRegionPoints(out contour, row, col); // hwindow_final1.viewWindow.displayHobject(contour, "red", true); // } // } // catch (Exception) // { // throw; // } //} //[Obsolete] //public void FindFirstAnchor(int SideId, out HTuple Row, out HTuple Col) //{ // Row = new HTuple(); Col = new HTuple(); // try // { // int Id = SideId - 1; // if (RArray == null) // { // return; // } // HTuple row = new HTuple(RArray[CurrentIndex - 1]); // HTuple col = new HTuple(CArray[CurrentIndex - 1]); // ShowProfile(CurrentIndex - 1, out row, out col); // if (RArray[CurrentIndex - 1].Length == 0) // { // return; // } // //HTuple row1 = -row; // //HTuple col1 = col; // //row = row1 - 0 + 150; // //col = col1; // //除去 -30 *200 的点 // HTuple eq30_1 = row.TupleEqualElem(-6000 - 0 + 150); // HTuple eqId_1 = eq30_1.TupleFind(1); // HTuple temp_1 = row.TupleRemove(eqId_1); // HTuple temp_2 = col.TupleRemove(eqId_1); // //取最左 // HTuple maxZCol = true ? temp_2.TupleMin() : temp_2.TupleMax(); // //HTuple maxZCol = fpTool.fParam[Id].BeLeft ? temp_2.TupleMin() : temp_2.TupleMax(); // HTuple mZRowId = col.TupleFindFirst(maxZCol); // HTuple mZRow = row[mZRowId]; // Row = mZRow; // Col = maxZCol; // } // catch (Exception) // { // throw; // } //} //[Obsolete] ///// <summary> ///// 由轮廓拟合点 ///// </summary> ///// <param name="SideId">边序号 从1 开始</param> ///// <param name="LastR">输出行坐标</param> ///// <param name="LastC">输出列坐标</param> ///// <param name="hwnd">输入窗体(可选)</param> ///// <returns></returns> //public string Fit(int SideId, out HTuple LastR, out HTuple LastC, HWindow_Final hwnd = null) //{ // LastR = new HTuple(); LastC = new HTuple(); // try // { // int Id = SideId - 1; // int k = 0; // for (int i = 0; i < RArray.GetLength(0); i++) // { // HTuple row = new HTuple(RArray[i]); // HTuple col = new HTuple(CArray[i]); // if (RArray[i].Length == 0) // { // continue; // } // HTuple row1 = -row; // HTuple col1 = col; // ////除去 -30 *200 的点 // //HTuple eq30 = row1.TupleEqualElem(-6000); // //HTuple eqId = eq30.TupleFind(1); // //HTuple temp = row1.TupleRemove(eqId); // //HTuple minrow = temp.TupleMin(); // row = row1 - 0 + 150; // col = col1; // //获取截取有效轮廓最大Z // if (fpTool.fParam[Id].EndPt < row.Length) // { // row = row.TupleSelectRange(fpTool.fParam[Id].StartPt, fpTool.fParam[Id].EndPt); // col = col.TupleSelectRange(fpTool.fParam[Id].StartPt, fpTool.fParam[Id].EndPt); // } // //除去 -30 *200 的点 // HTuple eq30_1 = row.TupleEqualElem(-6000 - 0 + 150); // HTuple eqId_1 = eq30_1.TupleFind(1); // HTuple temp_1 = row.TupleRemove(eqId_1); // HTuple temp_2 = col.TupleRemove(eqId_1); // // // //取最上 // //HTuple maxZ = temp_1.TupleMin(); // //HTuple mZColId = row.TupleFindFirst(maxZ); // //HTuple mZCol = col[mZColId]; // //HTuple rowStart = maxZ.D + fpTool.fParam[Id].UpDownDist; // //HTuple rowEnd = rowStart; // //HTuple colStart = mZCol; // //HTuple colEnd = fpTool.fParam[Id].BeLeft ? mZCol - 500 : mZCol + 500; // //取最左 // HTuple maxZ = temp_2.TupleMin(); // //HTuple maxZ = fpTool.fParam[Id].BeLeft ? temp_2.TupleMin() : temp_2.TupleMax(); // HTuple mZRowId = col.TupleFindFirst(maxZ); // HTuple mZRow = row[mZRowId]; // HTuple rowStart = mZRow.D - 500; // HTuple rowEnd = mZRow.D + 500; // HTuple colStart = maxZ.D + fpTool.fParam[Id].UpDownDist; // HTuple colEnd = maxZ.D + fpTool.fParam[Id].UpDownDist; // //求交点 // HObject Line = new HObject(); HObject Profile = new HObject(); HObject Intersect = new HObject(); // HOperatorSet.GenContourPolygonXld(out Line, rowStart.TupleConcat(rowEnd), colStart.TupleConcat(colEnd)); // HOperatorSet.GenContourPolygonXld(out Profile, row, col); // HTuple IntersecR, intersecC, isOver; // HOperatorSet.IntersectionContoursXld(Profile, Line, "mutual", out IntersecR, out intersecC, out isOver); // if (hwnd != null && i == 0) // { // hwnd.viewWindow.displayHobject(Line, "green"); // } // if (IntersecR.Length == 0) // { // //return "Fit Fail " + "无交点"; // continue; // } // if (IntersecR.Length > 1) // { // ////取最上 // //HTuple minC = fpTool.fParam[Id].BeLeft ? intersecC.TupleMax() : intersecC.TupleMin(); // //HTuple minCid = intersecC.TupleFindFirst(minC); // //LastR = LastR.TupleConcat(IntersecR[minCid]); // //LastC = LastC.TupleConcat( minC); // //取最左 // HTuple minR = IntersecR.TupleMin(); // HTuple minRid = IntersecR.TupleFindFirst(minR); // LastR = LastR.TupleConcat(IntersecR[minRid]); // LastC = LastC.TupleConcat(minR); // } // else // { // //取最上 // LastR = LastR.TupleConcat(IntersecR); // LastC = LastC.TupleConcat(intersecC); // //取最左 // } // k++; // HObject cross = new HObject(); // HOperatorSet.GenCrossContourXld(out cross, IntersecR, intersecC, 6, 0); // if (hwnd != null && i == 1) // { // hwnd.viewWindow.displayHobject(cross, "green"); // } // } // if (LastR.Length == 0) // { // return "Fit fail"; // } // HOperatorSet.TupleGenSequence(0, LastR.Length - 1, 1, out LastR); // if (MyGlobal.globalConfig.dataContext.xResolution != 0) // { // LastC = LastC / 200 / MyGlobal.globalConfig.dataContext.xResolution; // } // else // { // LastC = LastC / 200 / 0.007; // } // return "OK"; // } // catch (Exception ex) // { // return "Fit error" + ex.Message; // } //} //[Obsolete] ///// <summary> ///// 由轮廓拟合点 ///// </summary> ///// <param name="SideId">边序号 从1 开始</param> ///// <param name="LastR">输出行坐标</param> ///// <param name="LastC">输出列坐标</param> ///// <param name="hwnd">输入窗体(可选)</param> ///// <returns></returns> //public string FindMaxPtFallDown(int SideId, int ProfileId, out HTuple LastR, out HTuple LastC, out HTuple AnchorR, out HTuple AnchorC, HWindow_Final hwnd = null, bool ShowFeatures = false, bool UseFit = false) //{ // LastR = new HTuple(); LastC = new HTuple(); AnchorR = new HTuple(); AnchorC = new HTuple(); // try // { // HTuple row, col; // ShowProfile(ProfileId, out row, out col, hwnd); // int Id = SideId - 1; // if (RArray == null || RArray[ProfileId].Length == 0) // { // return "RArray is NULL"; // } // //除去 -30 *200 的点 // HTuple eq30_1 = row.TupleEqualElem(-6000 - 0 + 150); // HTuple eqId_1 = eq30_1.TupleFind(1); // HTuple temp_1 = row.TupleRemove(eqId_1); // HTuple temp_2 = col.TupleRemove(eqId_1); // if (fpTool.roiList[Id].Count == 0) // { // return "fpTool.roiList is Null"; // } // //取最左 作为初步锚定点 // HTuple maxZCol = true ? temp_2.TupleMin() : temp_2.TupleMax(); // //HTuple maxZCol = fpTool.fParam[Id].BeLeft ? temp_2.TupleMin() : temp_2.TupleMax(); // HTuple mZRowId = col.TupleFindFirst(maxZCol); // HTuple mZRow = row[mZRowId]; // int roiID = -1; // for (int i = 0; i < fpTool.fParam[Id].roiP.Count; i++) // { // for (int j = 0; j < fpTool.fParam[Id].roiP[i].NumOfSection; j++) // { // roiID++; // if (roiID == ProfileId) // { // break; // } // } // if (roiID == ProfileId) // { // roiID = i; // break; // } // } // // 锚定 Roi // HTuple RoiCoord = fpTool.roiList[Id][roiID].getModelData(); // double R1 = RoiCoord[0] + mZRow.D - fpTool.fParam[Id].roiP[roiID].AnchorRow; // double C1 = RoiCoord[1] + maxZCol.D - fpTool.fParam[Id].roiP[roiID].AnchorCol; // double R2 = RoiCoord[2] + mZRow.D - fpTool.fParam[Id].roiP[roiID].AnchorRow; // double C2 = RoiCoord[3] + maxZCol.D - fpTool.fParam[Id].roiP[roiID].AnchorCol; // if (C1 < 0) // { // C1 = 0; // } // //生成矩形框 // HObject left = new HObject(); // HObject right = new HObject(); // HOperatorSet.GenRegionLine(out left, 0, C1, 1000, C1); // HOperatorSet.GenRegionLine(out right, 0, C2, 1000, C2); // if (hwnd != null && ShowFeatures) // { // hwnd.viewWindow.displayHobject(left, "green"); // hwnd.viewWindow.displayHobject(right, "green"); // } // //求矩形区域内轮廓 极值 // HTuple ColLess = temp_2.TupleLessElem(C2); // HTuple ColGreater = temp_2.TupleGreaterElem(C1); // HTuple sub = ColLess.TupleSub(ColGreater); // HTuple IntersetID = sub.TupleFind(0); // //HTuple IntersetID = eq0.TupleFind(1); // if (IntersetID == -1) // { // return "区域内 无有效点"; // } // HTuple RowNew = temp_1[IntersetID]; // HTuple ColNew = temp_2[IntersetID]; // HTuple maxZ = new HTuple(); HTuple mZCol = new HTuple(); // //最高点下降 // if (fpTool.fParam[Id].roiP[roiID].SelectedType == 1) // { // //取最上 // maxZ = RowNew.TupleMin(); // HTuple mZColId = RowNew.TupleFindFirst(maxZ); // mZCol = ColNew[mZColId]; // } // else // { // //取极值 // int deg = fpTool.fParam[Id].roiP[roiID].AngleOfProfile; // GetInflection(RowNew, ColNew, deg, out maxZ, out mZCol, hwnd, true, true, true, ShowFeatures); // if (maxZ.Length == 0) // { // return "Ignore"; // } // HTuple Max1 = maxZ.TupleMax(); // HTuple maxId1 = maxZ.TupleFindFirst(Max1); // mZCol = mZCol[maxId1]; // maxZ = Max1; // if (hwnd != null && ShowFeatures) // { // HObject cross2 = new HObject(); // HOperatorSet.GenCrossContourXld(out cross2, maxZ, mZCol, 10, 0); // hwnd.viewWindow.displayHobject(cross2, "blue"); // } // if (maxZ.Length == 0) // { // return "Ignore"; // //return "FindMaxPt fail"; // } // } // double xresolution = MyGlobal.globalConfig.dataContext.xResolution; // HTuple rowStart = maxZ.D + fpTool.fParam[Id].roiP[roiID].TopDownDist * 200; // HTuple rowEnd = rowStart; // HTuple colStart = mZCol; // double dist = fpTool.fParam[Id].roiP[roiID].xDist == 0 ? 300 : fpTool.fParam[Id].roiP[roiID].xDist * 200; // HTuple colEnd = new HTuple(); // if (!fpTool.fParam[Id].roiP[roiID].useCenter) // { // colEnd = fpTool.fParam[Id].roiP[roiID].useLeft ? mZCol - dist : mZCol + dist; // } // else // { // //取轮廓中心 // colStart = mZCol - dist; // colEnd = mZCol + dist; // } // //求交点 // HObject Line = new HObject(); HObject Profile = new HObject(); HObject Intersect = new HObject(); // HOperatorSet.GenContourPolygonXld(out Line, rowStart.TupleConcat(rowEnd), colStart.TupleConcat(colEnd)); // HOperatorSet.GenContourPolygonXld(out Profile, row, col); // HTuple IntersecR, intersecC, isOver; // HOperatorSet.IntersectionContoursXld(Profile, Line, "mutual", out IntersecR, out intersecC, out isOver); // if (hwnd != null && ShowFeatures) // { // hwnd.viewWindow.displayHobject(Line, "green"); // } // if (IntersecR.Length == 0) // { // return "Ignore"; // } // if (IntersecR.Length > 1) // { // //取最上 // //取距离 极值或最高点 最近的点/最远点 // HTuple distMin = new HTuple(); // HTuple minC = new HTuple(); HTuple minCid = new HTuple(); // if (!fpTool.fParam[Id].roiP[roiID].useCenter) // { // for (int i = 0; i < intersecC.Length; i++) // { // double innerDis = Math.Abs(intersecC[i].D - mZCol.D); // distMin = distMin.TupleConcat(innerDis); // } // HTuple minDist = fpTool.fParam[Id].roiP[roiID].useNear ? distMin.TupleMin() : distMin.TupleMax(); // HTuple minId = distMin.TupleFindFirst(minDist); // minC = intersecC[minId]; // minCid = intersecC.TupleFindFirst(minC); // LastR = LastR.TupleConcat(IntersecR[minCid]); // LastC = LastC.TupleConcat(minC); // } // else // { // ////取轮廓中心 // //取离最大值或极值最近的两个点 // HTuple distless = new HTuple(); HTuple distgreater = new HTuple(); // for (int i = 0; i < intersecC.Length; i++) // { // double innerDis = intersecC[i].D - mZCol.D; // if (innerDis < 0) // { // distless = distless.TupleConcat(innerDis); // } // else // { // distgreater = distgreater.TupleConcat(innerDis); // } // } // HTuple min1 = distless.TupleMax(); // HTuple min2 = distgreater.TupleMin(); // HTuple minC1 = mZCol.D + min1; HTuple minC2 = mZCol.D + min2; // //取 区间 minCId1 -- minCId2 // HTuple MinMaxCol = col.TupleGreaterEqualElem(minC1); // HTuple MinMaxColID = MinMaxCol.TupleFind(1); // HTuple tempcol = col[MinMaxColID]; // HTuple temprow = row[MinMaxColID]; // HTuple MinMaxCol2 = tempcol.TupleLessEqualElem(minC2); // HTuple MinMaxColID2 = MinMaxCol2.TupleFind(1); // HTuple SegCol = tempcol[MinMaxColID2]; // HTuple SegRow = temprow[MinMaxColID2]; // HTuple centerR = SegRow.TupleMean(); // HTuple centerC = SegCol.TupleMean(); // LastR = LastR.TupleConcat(centerR); // LastC = LastC.TupleConcat(centerC); // } // } // else // { // //取最上 // LastR = LastR.TupleConcat(IntersecR); // LastC = LastC.TupleConcat(intersecC); // //取最左 // } // HObject cross = new HObject(); // HOperatorSet.GenCrossContourXld(out cross, IntersecR, intersecC, 6, 0); // if (hwnd != null && ProfileId == 1) // { // hwnd.viewWindow.displayHobject(cross, "white"); // } // if (LastR.Length == 0) // { // return "Ignore"; // } // HTuple Max = LastR.TupleMax(); // HTuple maxId = LastR.TupleFindFirst(Max); // LastC = LastC[maxId]; // LastR = Max; // AnchorR = LastR; // AnchorC = LastC; // ////启用中间点 // //if (fpTool.fParam[Id].roiP[roiID].useMidPt) // //{ // // HTuple EdgeCol = fpTool.fParam[Id].roiP[roiID].useLeft ? temp_2.TupleMin() : temp_2.TupleMax(); // // HTuple EdgColId = temp_2.TupleFindFirst(EdgeCol); // // HTuple EdgegRow = temp_1[EdgColId]; // // //取中间点 // // HTuple midR = (LastR + EdgegRow) / 2; // // HTuple midC = (LastC + EdgeCol) / 2; // // LastR = midR; // // LastC = midC; // //} // if (hwnd != null && ShowFeatures) // { // HObject cross1 = new HObject(); // HOperatorSet.GenCrossContourXld(out cross1, LastR, LastC, 10, 0); // hwnd.viewWindow.displayHobject(cross1, "green"); // } // if (LastR.Length == 0) // { // return "Ignore"; // //return "FindMaxPt fail"; // } // //HOperatorSet.TupleGenSequence(0, LastR.Length - 1, 1, out LastR); // HTuple PtID = new HTuple(); // HOperatorSet.TupleGreaterEqualElem(col, LastC, out PtID); // PtID = PtID.TupleFindFirst(1); // LastR = Row[ProfileId][PtID]; // LastC = CArray[ProfileId][PtID]; // //LastR = ProfileId; // //if (MyGlobal.globalConfig.dataContext.xResolution != 0) // //{ // // LastC = LastC / 200 / MyGlobal.globalConfig.dataContext.xResolution; // //} // //else // //{ // // LastC = LastC / 200 / 0.007; // //} // if (hwnd != null) // { // HObject cross1 = new HObject(); // HOperatorSet.GenCrossContourXld(out cross1, LastR, LastC, 10, 0); // HOperatorSet.SetColor(hwindow_final2.HWindowHalconID, "red"); // HOperatorSet.DispObj(cross1, hwindow_final2.HWindowHalconID); // } // return "OK"; // } // catch (Exception ex) // { // return "FindMaxPt error" + ex.Message; // } //} //[Obsolete] ///// <summary> ///// 由轮廓拟合点 ///// </summary> ///// <param name="SideId">边序号 从1 开始</param> ///// <param name="LastR">输出行坐标</param> ///// <param name="LastC">输出列坐标</param> ///// <param name="hwnd">输入窗体(可选)</param> ///// <returns></returns> //public string FindMaxPt(int SideId, int ProfileId, out HTuple LastR, out HTuple LastC, out HTuple AnchorR, out HTuple AnchorC, HWindow_Final hwnd = null, bool ShowFeatures = false, bool UseFit = false) //{ // LastR = new HTuple(); LastC = new HTuple(); AnchorR = new HTuple(); AnchorC = new HTuple(); // try // { // HTuple row, col; // ShowProfile(ProfileId, out row, out col, hwnd); // int Id = SideId - 1; // if (RArray == null || RArray[ProfileId].Length == 0) // { // return "RArray is NULL"; // } // //HTuple row1 = -row; // //HTuple col1 = col; // //row = row1 - 0 + 150; // //col = col1; // //除去 -30 *200 的点 // HTuple eq30_1 = row.TupleEqualElem(-6000 - 0 + 150); // HTuple eqId_1 = eq30_1.TupleFind(1); // HTuple temp_1 = row.TupleRemove(eqId_1); // HTuple temp_2 = col.TupleRemove(eqId_1); // if (fpTool.roiList[Id].Count == 0) // { // return "fpTool.roiList is Null"; // } // ////取最左 作为初步锚定点 // //HTuple maxZCol = temp_2.TupleMin(); // //HTuple mZRowId = col.TupleFindFirst(maxZCol); // //HTuple mZRow = row[mZRowId]; // HTuple mZRow = 0; HTuple maxZCol = 0; // int roiID = -1; // for (int i = 0; i < fpTool.fParam[Id].roiP.Count; i++) // { // for (int j = 0; j < fpTool.fParam[Id].roiP[i].NumOfSection; j++) // { // roiID++; // if (roiID == ProfileId) // { // break; // } // } // if (roiID == ProfileId) // { // roiID = i; // break; // } // } // // 锚定 Roi // HTuple RoiCoord = fpTool.roiList[Id][roiID].getModelData(); // double R1 = RoiCoord[0] + mZRow.D - fpTool.fParam[Id].roiP[roiID].AnchorRow; // double C1 = RoiCoord[1] + maxZCol.D - fpTool.fParam[Id].roiP[roiID].AnchorCol; // double R2 = RoiCoord[2] + mZRow.D - fpTool.fParam[Id].roiP[roiID].AnchorRow; // double C2 = RoiCoord[3] + maxZCol.D - fpTool.fParam[Id].roiP[roiID].AnchorCol; // if (C1 < 0) // { // C1 = 0; // } // //生成矩形框 // HObject left = new HObject(); // HObject right = new HObject(); // HOperatorSet.GenRegionLine(out left, 0, C1, 1000, C1); // HOperatorSet.GenRegionLine(out right, 0, C2, 1000, C2); // if (hwnd != null && ShowFeatures) // { // hwnd.viewWindow.displayHobject(left, "green"); // hwnd.viewWindow.displayHobject(right, "green"); // } // //求矩形区域内轮廓 极值 // HTuple ColLess = temp_2.TupleLessElem(C2); // HTuple ColGreater = temp_2.TupleGreaterElem(C1); // HTuple sub = ColLess.TupleSub(ColGreater); // HTuple IntersetID = sub.TupleFind(0); // //HTuple IntersetID = eq0.TupleFind(1); // if (IntersetID == -1) // { // return "区域内 无有效点"; // } // HTuple RowNew = temp_1[IntersetID]; // HTuple ColNew = temp_2[IntersetID]; // int deg = fpTool.fParam[Id].roiP[roiID].AngleOfProfile; // GetInflection(RowNew, ColNew, deg, out LastR, out LastC, hwnd, true, true, true, ShowFeatures); // if (LastR.Length == 0) // { // return "Ignore"; // } // HTuple Max = LastR.TupleMax(); // HTuple maxId = LastR.TupleFindFirst(Max); // LastC = LastC[maxId]; // LastR = Max; // AnchorR = LastR; // AnchorC = LastC; // ////启用中间点 // //if (fpTool.fParam[Id].roiP[roiID].useMidPt) // //{ // // HTuple EdgeCol = fpTool.fParam[Id].roiP[roiID].useLeft ? temp_2.TupleMin() : temp_2.TupleMax(); // // HTuple EdgColId = temp_2.TupleFindFirst(EdgeCol); // // HTuple EdgegRow = temp_1[EdgColId]; // // //取中间点 // // HTuple midR = (LastR + EdgegRow) / 2; // // HTuple midC = (LastC + EdgeCol) / 2; // // LastR = midR; // // LastC = midC; // //} // if (hwnd != null && ShowFeatures) // { // HObject cross = new HObject(); // HOperatorSet.GenCrossContourXld(out cross, LastR, LastC, 10, 0); // hwnd.viewWindow.displayHobject(cross, "green"); // } // if (LastR.Length == 0) // { // return "Ignore"; // } // HTuple PtID = new HTuple(); // HOperatorSet.TupleGreaterEqualElem(col, LastC, out PtID); // PtID = PtID.TupleFindFirst(1); // LastR = Row[ProfileId][PtID]; // LastC = CArray[ProfileId][PtID]; // //LastR = ProfileId; // //if (MyGlobal.globalConfig.dataContext.xResolution != 0) // //{ // // LastC = LastC / 200 / MyGlobal.globalConfig.dataContext.xResolution; // //} // //else // //{ // // LastC = LastC / 200 / 0.007; // //} // if (fpTool.fParam[0].BeLeft) // { // // 作为锚定点 // //第一条 // int sX1 = fpTool.fParam[Id].roiP[roiID].StartOffSet1.X; // int sY1 = fpTool.fParam[Id].roiP[roiID].StartOffSet1.Y; // int eX1 = fpTool.fParam[Id].roiP[roiID].EndOffSet1.X; // int eY1 = fpTool.fParam[Id].roiP[roiID].EndOffSet1.Y; // //第二条 // int sX2 = fpTool.fParam[Id].roiP[roiID].StartOffSet2.X; // int sY2 = fpTool.fParam[Id].roiP[roiID].StartOffSet2.Y; // int eX2 = fpTool.fParam[Id].roiP[roiID].EndOffSet2.X; // int eY2 = fpTool.fParam[Id].roiP[roiID].EndOffSet2.Y; // //起点 // HTuple gX1 = sX1 < eX1 ? col.TupleGreaterEqualElem(AnchorC.D + sX1) : col.TupleGreaterEqualElem(AnchorC.D + eX1); // HTuple gY1 = sY1 < eY1 ? row.TupleGreaterEqualElem(AnchorR.D + sY1) : row.TupleGreaterEqualElem(AnchorR.D + eY1); // HTuple eqx1 = gX1.TupleFind(1); // HTuple eqy1 = gY1.TupleFind(1); // HTuple SID1 = eqx1.TupleIntersection(eqy1); // //终点 // gX1 = sX1 < eX1 ? col.TupleLessEqualElem(AnchorC.D + eX1) : col.TupleLessEqualElem(AnchorC.D + sX1); // gY1 = sY1 < eY1 ? row.TupleLessEqualElem(AnchorR.D + eY1) : row.TupleLessEqualElem(AnchorR.D + sY1); // eqx1 = gX1.TupleFind(1); // eqy1 = gY1.TupleFind(1); // HTuple EID1 = eqx1.TupleIntersection(eqy1); // HTuple FID1 = SID1.TupleIntersection(EID1);//第一条 选取点索引 // if (FID1.Length == 0) // { // return "OK"; // } // //起点 // HTuple gX2 = sX2 < eX2 ? col.TupleGreaterEqualElem(AnchorC.D + sX2) : col.TupleGreaterEqualElem(AnchorC.D + eX2); // HTuple gY2 = sY2 < eY2 ? row.TupleGreaterEqualElem(AnchorR.D + sY2) : row.TupleGreaterEqualElem(AnchorR.D + eY2); // HTuple eqx2 = gX2.TupleFind(1); // HTuple eqy2 = gY2.TupleFind(1); // HTuple SID2 = eqx2.TupleIntersection(eqy2); // //终点 // gX2 = sX2 < eX2 ? col.TupleLessEqualElem(AnchorC.D + eX2) : col.TupleLessEqualElem(AnchorC.D + sX2); // gY2 = sY2 < eY2 ? row.TupleLessEqualElem(AnchorR.D + eY2) : row.TupleLessEqualElem(AnchorR.D + sY2); // eqx2 = gX2.TupleFind(1); // eqy2 = gY2.TupleFind(1); // HTuple EID2 = eqx2.TupleIntersection(eqy2); // HTuple FID2 = SID2.TupleIntersection(EID2);//第二条 选取点索引 // if (FID2.Length == 0) // { // return "OK"; // } // HTuple intersectR, intersectC, isOverlapping; // if (true) // { // HTuple Linr1 = row[FID1]; // HTuple Linc1 = col[FID1]; // HTuple Linr2 = row[FID2]; // HTuple Linc2 = col[FID2]; // HObject line1 = new HObject(); // HOperatorSet.GenContourPolygonXld(out line1, Linr1, Linc1); // HTuple Rowbg1, Colbg1, RowEd1, ColEd1, Nr1, Nc1, Dist1; // HOperatorSet.FitLineContourXld(line1, "tukey", -1, 0, 5, 2, out Rowbg1, out Colbg1, out RowEd1, out ColEd1, out Nr1, out Nc1, out Dist1); // HOperatorSet.GenRegionLine(out line1, Rowbg1, Colbg1, RowEd1, ColEd1); // HObject line2 = new HObject(); // HOperatorSet.GenContourPolygonXld(out line2, Linr2, Linc2); // HTuple Rowbg2, Colbg2, RowEd2, ColEd2, Nr2, Nc2, Dist2; // HOperatorSet.FitLineContourXld(line2, "tukey", -1, 0, 5, 2, out Rowbg2, out Colbg2, out RowEd2, out ColEd2, out Nr2, out Nc2, out Dist2); // HOperatorSet.GenRegionLine(out line2, Rowbg2, Colbg2, RowEd2, ColEd2); // HOperatorSet.IntersectionLines(Rowbg1, Colbg1, RowEd1, ColEd1, Rowbg2, Colbg2, RowEd2, ColEd2, out intersectR, out intersectC, out isOverlapping); // HTuple PtID2 = new HTuple(); // HOperatorSet.TupleGreaterEqualElem(col, intersectC, out PtID2); // PtID2 = PtID2.TupleFindFirst(1); // LastR = Row[ProfileId][PtID2]; // LastC = CArray[ProfileId][PtID2]; // if (hwnd != null) // { // HObject cross2 = new HObject(); // HOperatorSet.GenCrossContourXld(out cross2, intersectR, intersectC, 10, 45); // HOperatorSet.SetColor(hwindow_final1.HWindowHalconID, "blue"); // HOperatorSet.DispObj(cross2, hwindow_final1.HWindowHalconID); // HOperatorSet.DispObj(line1, hwindow_final1.HWindowHalconID); // HOperatorSet.DispObj(line2, hwindow_final1.HWindowHalconID); // } // } // } // if (hwnd != null) // { // HObject cross1 = new HObject(); // HOperatorSet.GenCrossContourXld(out cross1, LastR, LastC, 10, 0); // HOperatorSet.SetColor(hwindow_final2.HWindowHalconID, "green"); // HOperatorSet.DispObj(cross1, hwindow_final2.HWindowHalconID); // } // return "OK"; // } // catch (Exception ex) // { // return "FindMaxPt error" + ex.Message; // } //} //[Obsolete] //public string FindEdge(int SideId, int ProfileId, out HTuple EdgeR, out HTuple EdgeC, HWindow_Final hwnd = null, bool ShowFeatures = false) //{ // EdgeR = new HTuple(); EdgeC = new HTuple(); // try // { // HTuple row, col; // ShowProfile(ProfileId, out row, out col, hwnd); // int Id = SideId - 1; // if (RArray == null || RArray[ProfileId].Length == 0) // { // return "RArray is NULL"; // } // if (fpTool.roiList[Id].Count == 0) // { // return "FindEdge error fpTool.roiList is Null"; // } // int roiID = -1; // for (int i = 0; i < fpTool.fParam[Id].roiP.Count; i++) // { // for (int j = 0; j < fpTool.fParam[Id].roiP[i].NumOfSection; j++) // { // roiID++; // if (roiID == ProfileId) // { // break; // } // } // if (roiID == ProfileId) // { // roiID = i; // break; // } // } // EdgeC = fpTool.fParam[Id].roiP[roiID].useLeft ? col.TupleMin() : col.TupleMax(); // HTuple mZRowId = col.TupleFindFirst(EdgeC); // EdgeR = row[mZRowId]; // if (hwnd != null && ShowFeatures) // { // HObject cross = new HObject(); // HOperatorSet.GenCrossContourXld(out cross, EdgeR, EdgeC, 10, 0); // hwnd.viewWindow.displayHobject(cross, "green"); // } // HTuple PtID = new HTuple(); // HOperatorSet.TupleGreaterEqualElem(col, EdgeC, out PtID); // PtID = PtID.TupleFindFirst(1); // EdgeR = Row[ProfileId][PtID]; // EdgeC = CArray[ProfileId][PtID]; // if (hwnd != null) // { // HObject cross1 = new HObject(); // HOperatorSet.GenCrossContourXld(out cross1, EdgeR, EdgeC, 10, 0); // HOperatorSet.SetColor(hwnd.HWindowHalconID, "green"); // HOperatorSet.DispObj(cross1, hwnd.HWindowHalconID); // } // return "OK"; // } // catch (Exception ex) // { // return "FindEdge error" + ex.Message; // } //} //[Obsolete] ///// <summary> ///// 获取极大值或极小值 ///// </summary> ///// <param name="rows">输入行坐标</param> ///// <param name="cols">输入列坐标</param> ///// <param name="sigma">输入平滑系数</param> ///// <param name="IsUpDown">以上下方向筛选还是左右方向筛选</param> ///// <param name="IsMaxOrMin">选择极大值还是极小值</param> ///// <param name="hv_rowout">输出极值行坐标</param> ///// <param name="hv_colout">输出极值列坐标</param> ///// <param name="UseLeft"> 是否选择最左侧点</param> ///// <returns></returns> //public string PeakTroughOfWave(HTuple rows, HTuple cols, HTuple sigma, bool IsUpDown, bool IsMaxOrMin, out HTuple hv_rowout, out HTuple hv_colout, bool UseLeft = false) //{ // try // { // hv_rowout = new HTuple(); hv_colout = new HTuple(); // HTuple hv_Function = null, hv_SmoothedFunction = null, hv_Derivative = null, hv_ZeroCrossings = null, hv_Y = null, hv_Min = null, hv_Max = null; // HTuple hv_Indices1 = null, hv_Indices2 = null; // if (rows.Type == HTupleType.EMPTY || rows.Length < 5) // { // hv_rowout = new HTuple(); // hv_colout = new HTuple(); // return "NG"; // } // HOperatorSet.CreateFunct1dArray(rows, out hv_Function); // if (sigma > ((rows.Length - 2) / 7.8)) // { // sigma = 0.5; // } // HOperatorSet.SmoothFunct1dGauss(hv_Function, sigma, out hv_SmoothedFunction); // HOperatorSet.DerivateFunct1d(hv_SmoothedFunction, "first", out hv_Derivative); // HOperatorSet.ZeroCrossingsFunct1d(hv_Derivative, out hv_ZeroCrossings); // HTuple hv_indCol = ((hv_ZeroCrossings.TupleString(".0f"))).TupleNumber(); // if (hv_indCol.Length == 0) // { // //if (UseLeft) // //{ // // hv_colout = cols.TupleMin(); // // HTuple minId = cols.TupleFind(hv_colout); // // hv_rowout = rows[minId]; // //} // //else // //{ // hv_colout = new HTuple(); // hv_rowout = new HTuple(); // //} // return "OK"; // } // HOperatorSet.GetYValueFunct1d(hv_SmoothedFunction, hv_ZeroCrossings, "constant", // out hv_Y); // HTuple max = new HTuple(); HTuple min = new HTuple(); // HTuple hv_indColMax = new HTuple(); HTuple hv_indColMin = new HTuple(); // //轮廓最左点 // HTuple colLeft = cols.TupleMin(); // if (true) // { // for (int i = 0; i < hv_Y.Length; i++) // { // if (hv_indCol[i].I + 3 + 5 >= hv_SmoothedFunction.Length) // { // break; // } // if (hv_indCol[i].I < 2) // { // continue; // } // if (hv_SmoothedFunction[hv_indCol[i].I + 3] < hv_SmoothedFunction[hv_indCol[i].I + 3 - 5] && hv_SmoothedFunction[hv_indCol[i].I + 3] < hv_SmoothedFunction[hv_indCol[i].I + 3 + 5]) // { // max = max.TupleConcat(hv_Y[i]); // hv_indColMax = hv_indColMax.TupleConcat(hv_indCol[i]); // } // if (hv_SmoothedFunction[hv_indCol[i].I + 3] > hv_SmoothedFunction[hv_indCol[i].I + 3 - 5] && hv_SmoothedFunction[hv_indCol[i].I + 3] > hv_SmoothedFunction[hv_indCol[i].I + 3 + 5]) // { // if (cols[hv_indCol[i].I] > colLeft) //不取最左侧点 // { // min = min.TupleConcat(hv_Y[i]); // hv_indColMin = hv_indColMin.TupleConcat(hv_indCol[i]); // } // else // { // if (UseLeft) // { // min = min.TupleConcat(hv_Y[i]); // hv_indColMin = hv_indColMin.TupleConcat(hv_indCol[i]); // } // } // } // } // if (IsMaxOrMin)//极大值 // { // if (max.Length == 0) // { // return "PeakTroughOfWave:" + "No MaxValue"; // } // hv_Y = max; // hv_indCol = hv_indColMax; // } // else // { // if (min.Length == 0) // { // return "PeakTroughOfWave:" + "No MinValue"; // } // hv_Y = min; // hv_indCol = hv_indColMin; // } // } // if (IsUpDown)//上下方向 Row 方向最大和最小值 // { // HOperatorSet.TupleMin(hv_Y, out hv_Min); // HOperatorSet.TupleMax(hv_Y, out hv_Max); // HOperatorSet.TupleFindFirst(hv_Y, hv_Min, out hv_Indices1); // HOperatorSet.TupleFindFirst(hv_Y, hv_Max, out hv_Indices2); // hv_rowout = new HTuple(); // hv_rowout = hv_rowout.TupleConcat(hv_Y.TupleSelect( // hv_Indices1)); // hv_rowout = hv_rowout.TupleConcat(hv_Y.TupleSelect(hv_Indices2)); // hv_colout = new HTuple(); // hv_colout = hv_colout.TupleConcat(cols.TupleSelect( // hv_indCol.TupleSelect(hv_Indices1))); // hv_colout = hv_colout.TupleConcat(cols.TupleSelect( // hv_indCol.TupleSelect(hv_Indices2))); // } // else//左右方向 Col 方向 最大和最小值 // { // HTuple Col = cols[hv_indCol]; // HOperatorSet.TupleMin(Col, out hv_Min);//最左侧 // HOperatorSet.TupleMax(Col, out hv_Max);//最右侧 // HOperatorSet.TupleFindFirst(Col, hv_Min, out hv_Indices1); // HOperatorSet.TupleFindFirst(Col, hv_Max, out hv_Indices2); // hv_rowout = new HTuple(); // hv_rowout = hv_rowout.TupleConcat(hv_Y.TupleSelect( // hv_Indices1)); // hv_rowout = hv_rowout.TupleConcat(hv_Y.TupleSelect(hv_Indices2)); // hv_colout = new HTuple(); // hv_colout = hv_colout.TupleConcat(hv_Min); // hv_colout = hv_colout.TupleConcat(hv_Max); // } // return "OK"; // } // catch (Exception ex) // { // hv_colout = new HTuple(); hv_rowout = new HTuple(); // return "PeakTroughOfWave:" + ex.Message; // } //} //[Obsolete] ///// <summary> ///// 获取拐点 ///// </summary> ///// <param name="clipRow">轮廓行坐标</param> ///// <param name="clipCol">轮廓列坐标</param> ///// <param name="Deg">轮廓旋转角度</param> ///// <param name="pRow">拐点行坐标</param> ///// <param name="pCol">拐点列坐标</param> ///// <param name="Hwindow">显示窗口</param> ///// <param name="isUpDown">以上下方向筛选还是以左右方向筛选</param> ///// <param name="isMax">是否启用极大值(true 极大值,false 极小值)</param> ///// <returns></returns> //private string GetInflection(HTuple clipRow, HTuple clipCol, HTuple Deg, out HTuple pRow, out HTuple pCol, HWindow_Final Hwindow = null, bool isUpDown = true, bool isMax = true, bool useLeft = true, bool ifShowFeatures = false) //{ // pRow = new HTuple(); pCol = new HTuple(); // try // { // if (clipRow.Length == 0) // { // return "No Clip"; // } // if (!ifShowFeatures) // { // Hwindow = null; // } // HObject IntersectionO = new HObject(); HObject crossO = new HObject(); // HObject ContourO = new HObject(); // HTuple RowO, ColO, rowPeak, colPeak; // HTuple area, row, col, homMat2D; // HTuple Phi = Deg.TupleRad(); // HOperatorSet.GenRegionPoints(out IntersectionO, clipRow, clipCol); // HOperatorSet.GenContourPolygonXld(out ContourO, clipRow, clipCol); // HOperatorSet.AreaCenter(IntersectionO, out area, out row, out col); // HOperatorSet.VectorAngleToRigid(row, col, 0, row, col, Phi, out homMat2D); // HOperatorSet.AffineTransContourXld(ContourO, out ContourO, homMat2D); // HOperatorSet.GetContourXld(ContourO, out RowO, out ColO); // if (Hwindow != null) // { // HOperatorSet.SetDraw(Hwindow.HWindowHalconID, "margin"); // Hwindow.viewWindow.displayHobject(ContourO, "white", true); // HOperatorSet.SetDraw(Hwindow.HWindowHalconID, "margin"); // } // string ware = PeakTroughOfWave(RowO, ColO, 0.5, isUpDown, isMax, out rowPeak, out colPeak, useLeft); // string msg = ""; // //if (ware=="NG") // //{ // // msg = "轮廓点异常"; // // return msg; // //} // if (rowPeak.Length == 0) // { // pRow = new HTuple(); pCol = new HTuple(); // return "OK"; // msg = "OK"; // if (true) // { // colPeak = ColO.TupleMin(); // HTuple ind = ColO.TupleFindFirst(colPeak); // rowPeak = RowO[ind]; // rowPeak = rowPeak.TupleConcat(rowPeak); // colPeak = colPeak.TupleConcat(colPeak); // } // //else // //{ // // colPeak = ColO.TupleMax(); // // HTuple ind = ColO.TupleFindFirst(colPeak); // // rowPeak = RowO[ind]; // // rowPeak = rowPeak.TupleConcat(rowPeak); // // colPeak = colPeak.TupleConcat(colPeak); // //} // } // else // { // msg = "OK"; // } // HTuple Max = rowPeak.TupleMin(); // HTuple maxId = rowPeak.TupleFindFirst(Max); // colPeak = colPeak[maxId]; // rowPeak = Max; // HOperatorSet.VectorAngleToRigid(row, col, Phi, row, col, 0, out homMat2D); // HOperatorSet.AffineTransPoint2d(homMat2D, rowPeak, colPeak, out pRow, out pCol); // if (Hwindow != null) // { // HOperatorSet.GenCrossContourXld(out crossO, pRow, pCol, 12, 0); // HOperatorSet.SetDraw(Hwindow.HWindowHalconID, "margin"); // Hwindow.viewWindow.displayHobject(crossO, "red", true); // Hwindow.viewWindow.displayHobject(IntersectionO, "yellow", true); // HOperatorSet.SetDraw(Hwindow.HWindowHalconID, "margin"); // } // return msg; // } // catch (Exception ex) // { // return "GetInflection error " + ex.Message; // } //} //[Obsolete] //private void DispSection___1(ROIRectangle2 roi, int SideID, int RoiId, out HTuple[] LineCoord, HWindow_Final hwnd = null) //{ // LineCoord = new HTuple[1]; // try // { // HTuple RoiCoord = roi.getModelData(); // double cosa = Math.Cos(RoiCoord[2].D); // double sina = Math.Sin(RoiCoord[2].D); // double r1 = RoiCoord[0].D + RoiCoord[4].D * cosa; // double c1 = RoiCoord[1].D - RoiCoord[4].D * sina; // double r2 = RoiCoord[0].D - RoiCoord[4].D * cosa; // double c2 = RoiCoord[1].D + RoiCoord[4].D * sina; // // // int Num = fpTool.fParam[SideID].roiP[RoiId].NumOfSection; // LineCoord = new HTuple[Num]; // double Average = RoiCoord[4].D * 2 / (Num + 1); // for (int i = 0; i < Num; i++) // { // LineCoord[i] = new HTuple(); // double AverageLen = Average * (i + 1); // double Row2 = r2 + AverageLen * cosa + RoiCoord[3].D * sina; // double Col2 = c2 - AverageLen * sina + RoiCoord[3].D * cosa; // double Row1 = r2 + AverageLen * cosa - RoiCoord[3].D * sina; // double Col1 = c2 - AverageLen * sina - RoiCoord[3].D * cosa; // LineCoord[i] = LineCoord[i].TupleConcat(Row1).TupleConcat(Col1).TupleConcat(Row2).TupleConcat(Col2).TupleConcat(RoiCoord[2].D); // if (hwnd != null) // { // HObject Line = new HObject(); // HOperatorSet.GenRegionLine(out Line, LineCoord[i][0], LineCoord[i][1], LineCoord[i][2], LineCoord[i][3]); // HOperatorSet.SetColor(hwindow_final2.HWindowHalconID, "red"); // HOperatorSet.DispObj(Line, hwindow_final2.HWindowHalconID); // } // } // } // catch (Exception) // { // throw; // } //} //[Obsolete] //string GenSection(HObject Image, HTuple lineCoord, out HTuple row, out HTuple col, out HTuple IgnorePt) //{ // row = new HTuple(); col = new HTuple(); IgnorePt = 0; // try // { // HTuple width, height, lessId1, lessId2; // HOperatorSet.GetImageSize(Image, out width, out height); // HObject Rline; HObject Rline1 = new HObject(); // HOperatorSet.GenRegionLine(out Rline, lineCoord[0], lineCoord[1], lineCoord[2], lineCoord[3]); // HOperatorSet.GenContourRegionXld(Rline, out Rline1, "center"); // HOperatorSet.GetContourXld(Rline1, out row, out col); // if (row.Length == 0) // { // IgnorePt = 1; // return "GenSection截面在图像之外"; // } // HTuple deg = -(new HTuple(lineCoord[4].D)).TupleDeg(); // double tan = Math.Abs(Math.Tan(-lineCoord[4].D)); // int len1 = Math.Abs((int)(lineCoord[1].D - lineCoord[3].D)); // int len2 = Math.Abs((int)(lineCoord[0].D - lineCoord[2].D)); // int len = len1 > len2 ? len1 : len2; // HTuple x0 = lineCoord[1].D; // HTuple y0 = lineCoord[0].D; // HTuple newr = y0; HTuple newc = x0; // for (int i = 1; i < len; i++) // { // HTuple row1 = new HTuple(); HTuple col1 = new HTuple(); // if (len1 > len2) // { // row1 = lineCoord[0].D > lineCoord[2].D ? y0 - i * tan : y0 + i * tan; // col1 = lineCoord[1].D > lineCoord[3].D ? x0 - i : x0 + i; // } // else // { // row1 = lineCoord[0].D < lineCoord[2].D ? y0 + i : y0 - i; // col1 = lineCoord[1].D < lineCoord[3].D ? x0 + i / tan : x0 - i / tan; // } // newr = newr.TupleConcat(row1); // newc = newc.TupleConcat(col1); // } // row = newr; // col = newc; // HOperatorSet.TupleLessElem(row, height, out lessId1); // HOperatorSet.TupleFind(lessId1, 1, out lessId1); // if (lessId1.D == -1) // { // IgnorePt = 1; // row = 0; // col = 0; // return "GenSection截面在图像之外"; // } // row = row[lessId1]; // col = col[lessId1]; // HOperatorSet.TupleLessElem(col, width, out lessId2); // HOperatorSet.TupleFind(lessId2, 1, out lessId2); // if (lessId2.D == -1) // { // IgnorePt = 1; // row = 0; // col = 0; // return "GenSection截面在图像之外"; // } // row = row[lessId2]; // col = col[lessId2]; // //且 行列大于零 // HTuple lessId3, lessId4; // HOperatorSet.TupleGreaterElem(col, 0, out lessId3); // HOperatorSet.TupleFind(lessId3, 1, out lessId3); // row = row[lessId3]; // col = col[lessId3]; // HOperatorSet.TupleGreaterElem(row, 0, out lessId4); // HOperatorSet.TupleFind(lessId4, 1, out lessId4); // row = row[lessId4]; // col = col[lessId4]; // //HOperatorSet.GetGrayval(Image, row, col, out Zpoint); // //HTuple EqId = new HTuple(); // //HOperatorSet.TupleNotEqualElem(Zpoint, -30, out EqId); // //HOperatorSet.TupleFind(EqId, 1, out EqId); // //if (EqId.D != -1) // //{ // // Zpoint = Zpoint[EqId]; // // Cpoint = col[EqId]; // // Rpoint = row[EqId]; // // IgnorePt = 0; // //} // //else // //{ // // IgnorePt = 1; // //} // Rline.Dispose(); // Rline1.Dispose(); // //ConstImage.Dispose(); // //Contour.Dispose(); // return "OK"; // } // catch (Exception ex) // { // return "GenSection error" + ex.Message; // } //} //[Obsolete] //private string GenProfileCoord(int SideId, HObject HeightImage, out double[][] Rarray, out double[][] Row, out double[][] Carray, out double[][] Phi, out int ignorePt, HTuple Fix = null) //{ // Rarray = null; Carray = null; Row = null; Phi = null; ignorePt = 0; // try // { // int SId = SideId - 1; // int k = 0; // // // for (int i = 0; i < fpTool.roiList2[SId].Count; i++) // { // for (int j = 0; j < fpTool.fParam[SId].roiP[i].NumOfSection; j++) // { // k++; // } // } // int n = 0; // Rarray = new double[k][]; Carray = new double[k][]; Row = new double[k][]; Phi = new double[k][]; // double[] Rarray1; // double[] Carray1; // HTuple HPhi = new HTuple(); // int[] profileNum = new int[k]; // for (int i = 0; i < fpTool.roiList2[SId].Count; i++) // { // //Debug.WriteLine(n); // HTuple orignal = fpTool.roiList2[SId][i].getModelData(); // ROIRectangle2 temp = new ROIRectangle2(orignal[0], orignal[1], orignal[2], orignal[3], orignal[4]); // HTuple[] lineCoord = new HTuple[1]; // //将矩形进行定位 // if (Fix != null) // { // HTuple recCoord = temp.getModelData(); // HTuple CenterR = new HTuple(); HTuple CenterC = new HTuple(); // List<ROI> temproi = new List<ROI>(); // HTuple tempR = new HTuple(); HTuple tempC = new HTuple(); // HOperatorSet.AffineTransPoint2d(Fix, recCoord[0], recCoord[1], out CenterR, out CenterC); // temp.Row = CenterR; temp.Column = CenterC; // } // fpTool.DispSection(temp, SId, i, out lineCoord); // for (int j = 0; j < lineCoord.Length; j++) // { // /* HTuple Sigle = new HTuple();*/ // HTuple col = new HTuple(); HTuple row = new HTuple(); HTuple ignore = new HTuple(); // string ok = GenSection(HeightImage, lineCoord[j], out row, out col, out ignore); // ignorePt += ignore; // profileNum[n] = row.Length; // Rarray[n] = row; // Carray[n] = col; // //HRarray = HRarray.TupleConcat(row); // //HCarray = HCarray.TupleConcat(col); // //HRow = HRow.TupleConcat(row); // Phi[n] = lineCoord[j]; // n++; // //if (n == 358) // //{ // // Debug.WriteLine("error"); // //} // } // } // int total = 0; // for (int i = 0; i < n; i++) // { // for (int j = 0; j < profileNum[i]; j++) // { // //if (Rarray[i][j] != 0 && Carray[i][j] != 0) // //{ // total++; // //} // } // } // Rarray1 = new double[total]; // Carray1 = new double[total]; // int tt = 0; // for (int i = 0; i < n; i++) // { // for (int j = 0; j < profileNum[i]; j++) // { // Rarray1[tt] = Rarray[i][j]; // Carray1[tt] = Carray[i][j]; // tt++; // } // } // HTuple Zpoint = new HTuple(); HTuple HRow = new HTuple(); HTuple HRarray = new HTuple(); HTuple HCarray = new HTuple(); // try // { // HOperatorSet.GetGrayval(HeightImage, Rarray1, Carray1, out Zpoint); // } // catch (Exception) // { // return "GenProfileCoord error: 区域位于图像之外"; // } // HRarray = Rarray1; HCarray = Carray1; // int m = 0; // for (int i = 0; i < profileNum.Length; i++) // { // if (profileNum[i] == 0) // { // continue; // } // HTuple z = Zpoint.TupleSelectRange(m, m + profileNum[i] - 1); // HTuple r = HRarray.TupleSelectRange(m, m + profileNum[i] - 1); // HTuple c = HCarray.TupleSelectRange(m, m + profileNum[i] - 1); // HTuple EqId = new HTuple(); // HOperatorSet.TupleGreaterElem(z, -10, out EqId); // HOperatorSet.TupleFind(EqId, 1, out EqId); // if (EqId.D != -1) // { // z = z[EqId]; // r = r[EqId]; // c = c[EqId]; // } // else // { // ignorePt += 1; // } // Rarray[i] = z * 200; // Carray[i] = c; // Row[i] = r; // //Phi[m] = HPhi[j]; // m += profileNum[i]; // } // return "OK"; // } // catch (Exception ex) // { // return "GenProfileCoord error:" + ex.Message; // } //} //[Obsolete] //public string FindIntersectPoint(int Side, HObject HeightImage, out IntersetionCoord intersectCoord, HWindow_Final hwnd = null, bool debug = false) //{ // List<HTuple> Hlines = new List<HTuple>(); intersectCoord = new IntersetionCoord(); // try // { // string ok = FindPoint(Side, HeightImage, out Hlines, hwnd, debug); // if (ok != "OK") // { // return ok; // } // if (Hlines.Count != 4) // { // return "定位找线区域数量错误"; // } // for (int i = 0; i < Hlines.Count; i++) // { // if (Hlines[i].Length == 0) // { // return $"定位找线区域{i + 1}运行失败"; // } // } // //1,4 取中线 2,3取拟合线 // HTuple rb1 = (Hlines[0][0].D + Hlines[3][0].D) / 2; // HTuple cb1 = (Hlines[0][1].D + Hlines[3][1].D) / 2; // HTuple re1 = (Hlines[0][2].D + Hlines[3][2].D) / 2; // HTuple ce1 = (Hlines[0][3].D + Hlines[3][3].D) / 2; // //取1 4 中点 // HTuple midR = (rb1.D + re1.D) / 2; // HTuple midC = (cb1.D + ce1.D) / 2; // HObject crossMid = new HObject(); // HOperatorSet.GenCrossContourXld(out crossMid, midR, midC, 30, 0.5); // rb1 = midR.D; // re1 = midR.D; // cb1 = 0; // ce1 = 5000; // HObject contHorizon = new HObject(); // HOperatorSet.GenContourPolygonXld(out contHorizon, rb1.TupleConcat(re1), cb1.TupleConcat(ce1)); // HTuple rb2 = (Hlines[1][0].D + Hlines[2][0].D) / 2; // HTuple cb2 = (Hlines[1][1].D + Hlines[2][1].D) / 2; // HTuple re2 = (Hlines[1][2].D + Hlines[2][2].D) / 2; // HTuple ce2 = (Hlines[1][3].D + Hlines[2][3].D) / 2; // HTuple rowVer = new HTuple(); HTuple colVer = new HTuple(); // rowVer = rowVer.TupleConcat(Hlines[1][0].D).TupleConcat(Hlines[1][2].D).TupleConcat(Hlines[2][0].D).TupleConcat(Hlines[2][2].D); // colVer = colVer.TupleConcat(Hlines[1][1].D).TupleConcat(Hlines[1][3].D).TupleConcat(Hlines[2][1].D).TupleConcat(Hlines[2][3].D); // HObject contVer = new HObject(); // HOperatorSet.GenContourPolygonXld(out contVer, rowVer, colVer); // //拟合线 // //HObject line = new HObject(); // HTuple Nr, Nc, Dist; // HOperatorSet.FitLineContourXld(contVer, "tukey", -1, 0, 5, 2, out rb2, out cb2, out re2, out ce2, out Nr, out Nc, out Dist); // HOperatorSet.GenContourPolygonXld(out contVer, rb2.TupleConcat(re2), cb2.TupleConcat(ce2)); // //HOperatorSet.GenContourPolygonXld(out contVer, rb2.TupleConcat(re2), cb2.TupleConcat(ce2)); // HTuple Row, Col, Angle; // HOperatorSet.AngleLx(rb2, cb2, re2, ce2, out Angle); // HTuple isOver; // //HOperatorSet.IntersectionContoursXld(contHorizon, contVer, "mutual", out Row, out Col, out isOver); // HOperatorSet.IntersectionLines(rb1, cb1, re1, ce1, rb2, cb2, re2, ce2, out Row, out Col, out isOver); // if (hwnd != null) // { // //hwnd.viewWindow.displayHobject(contHorizon, "red"); // hwnd.viewWindow.displayHobject(crossMid, "red"); // HObject Cross = new HObject(); // HOperatorSet.GenCrossContourXld(out Cross, Row, Col, 30, 0.5); // hwnd.viewWindow.displayHobject(contVer, "blue"); // hwnd.viewWindow.displayHobject(Cross, "red"); // double xResolution = MyGlobal.globalConfig.dataContext.xResolution; // double yResolution = MyGlobal.globalConfig.dataContext.yResolution; // HTuple row1 = Row.D * xResolution; // HTuple col1 = Col.D * yResolution; // string Rowstr = (Math.Round(row1.D, 3)).ToString(); // string Colstr = (Math.Round(col1.D, 3)).ToString(); // string Anglestr = (Math.Round(Angle.D, 3)).ToString(); // hwnd.viewWindow.dispMessage(Rowstr, "red", Row, Col + 100); // hwnd.viewWindow.dispMessage(Colstr, "red", Row.D + 50, Col + 100); // hwnd.viewWindow.dispMessage(Anglestr, "red", Row.D + 100, Col + 100); // } // intersectCoord.Row = Row.D; // intersectCoord.Col = Col.D; // intersectCoord.Angle = Angle.D; // if (ok != "OK") // { // MessageBox.Show(ok); // } // return "OK"; // } // catch (Exception ex) // { // return "FindIntersectPoint error" + ex.Message; // } //} //[Obsolete] //private void RotateImage(int SideId, HObject IntensityImage, HObject HeightImage, out HObject RIntesity, out HObject RHeight, out HTuple homMatRotate, out HTuple homMatRotateInvert, HWindow_Final hwind = null) //{ // RIntesity = new HObject(); RHeight = new HObject(); // //将图像转正‘ // int Sid = SideId - 1; // HObject ReduceImage = new HObject(); HObject Rec = new HObject(); // //HTuple Coor = fpTool.roiList3[Sid][0].getModelData(); // HTuple Coor = new HTuple(); // HOperatorSet.GenRectangle1(out Rec, Coor[0], Coor[1], Coor[2], Coor[3]); // HOperatorSet.ReduceDomain(IntensityImage, Rec, out ReduceImage); // HOperatorSet.Threshold(ReduceImage, out Rec, 5, 255); // HOperatorSet.ErosionRectangle1(Rec, out Rec, 5, 5); // HOperatorSet.DilationRectangle1(Rec, out Rec, 5, 5); // HOperatorSet.Connection(Rec, out Rec); // HTuple area = new HTuple(); // HOperatorSet.RegionFeatures(Rec, "area", out area); // HTuple maxId = new HTuple(); // HOperatorSet.TupleMax(area, out maxId); // HOperatorSet.TupleFind(area, maxId, out maxId); // if (hwind != null) // { // //hwind.viewWindow.displayHobject(Rec); // } // HOperatorSet.SelectObj(Rec, out Rec, maxId + 1); // HTuple phi = new HTuple(); HTuple rad90 = new HTuple(); // HOperatorSet.RegionFeatures(Rec, "phi", out phi); // HOperatorSet.TupleRad(90, out rad90); // HTuple sub = new HTuple(); // if (phi < 0) // { // phi = phi.TupleAbs(); // sub = phi - rad90; // } // else // { // sub = rad90 - phi; // } // homMatRotate = new HTuple(); homMatRotateInvert = new HTuple(); // HOperatorSet.HomMat2dIdentity(out homMatRotate); // HOperatorSet.HomMat2dRotate(homMatRotate, sub, 0, 0, out homMatRotate); // HOperatorSet.HomMat2dIdentity(out homMatRotateInvert); // HOperatorSet.HomMat2dRotate(homMatRotateInvert, -sub, 0, 0, out homMatRotateInvert); // HOperatorSet.AffineTransImage(IntensityImage, out RIntesity, homMatRotate, "nearest_neighbor", "false"); // HOperatorSet.AffineTransImage(HeightImage, out RHeight, homMatRotate, "nearest_neighbor", "false"); // if (hwind != null) // { // //hwind.ClearWindow(); // //hwind.HobjectToHimage(RIntesity); // } //} //[Obsolete] //public string FindPoint(int SideId, HObject IntesityImage, HObject HeightImage, out double[][] RowCoord, out double[][] ColCoord, out double[][] ZCoord, out string[][] StrLineOrCircle, out HTuple[] originalPoint, HTuple HomMat3D = null, HWindow_Final hwind = null, bool debug = false, HTuple homMatFix = null) //{ // //HObject RIntesity = new HObject(), RHeight = new HObject(); // StringBuilder Str = new StringBuilder(); // originalPoint = new HTuple[2]; // RowCoord = null; ColCoord = null; ZCoord = null; StrLineOrCircle = null; // try // { // int Sid = SideId - 1; // string ok1 = GenProfileCoord(Sid + 1, HeightImage, out RArray, out Row, out CArray, out Phi, out Ignore, homMatFix); // if (ok1 != "OK") // { // return ok1; // } // int Len = fpTool.roiList2[Sid].Count;// 区域数量 // if (Len == 0) // { // //RIntesity.Dispose(); // //RHeight.Dispose(); // return "参数设置错误"; // } // RowCoord = new double[Len][]; ColCoord = new double[Len][]; ZCoord = new double[Len][]; StrLineOrCircle = new string[Len][]; // double[][] RowCoordt = new double[Len][]; double[][] ColCoordt = new double[Len][]; /*double[][] ZCoordt = new double[Len][];*/ // int Num = 0; int Add = 0; HTuple NewZ = new HTuple(); // HTuple origRow = new HTuple(); // HTuple origCol = new HTuple(); // for (int i = 0; i < Len; i++) // { // if (i == 11) // { // Debug.WriteLine(i); // } // HTuple row = new HTuple(), col = new HTuple(); // HTuple edgeRow = new HTuple(); HTuple edgeCol = new HTuple();//边缘点 // for (int j = Num; j < Add + fpTool.fParam[Sid].roiP[i].NumOfSection; j++) // { // if (Num == 99) // { // Debug.WriteLine(Num); // } // //Debug.WriteLine(Num); // HTuple row1, col1; HTuple anchor, anchorc; HTuple edgeR1, edgeC1; // if (fpTool.fParam[Sid].roiP[i].SelectedType == 0) // { // if (fpTool.fParam[Sid].roiP[i].TopDownDist != 0 && fpTool.fParam[Sid].roiP[i].xDist != 0) // { // string ok = fpTool.FindMaxPtFallDown(Sid + 1, j, out row1, out col1, out anchor, out anchorc); // } // else // { // string ok = fpTool.FindMaxPt(Sid + 1, j, out row1, out col1, out anchor, out anchorc); // } // } // else // { // //取最高点下降 // string ok = fpTool.FindMaxPtFallDown(Sid + 1, j, out row1, out col1, out anchor, out anchorc); // } // if (fpTool.fParam[Sid].roiP[i].useMidPt) // { // //取边缘点 // string ok = FindEdge(Sid + 1, j, out edgeR1, out edgeC1); // edgeRow = edgeRow.TupleConcat(edgeR1); // edgeCol = edgeCol.TupleConcat(edgeC1); // } // row = row.TupleConcat(row1); // col = col.TupleConcat(col1); // Num++; // } // string msg = ""; // if (hwind != null) // { // msg = fpTool.fParam[Sid].DicPointName[i]; // } // if (row.Length < 2) // { // return "区域" + msg + "拟合点数过少"; // } // Add = Num; // if (row.Length == 0) //区域之外 // { // continue; // } // HObject siglePart = new HObject(); // int Clipping = 0; // int iNum = row.Length; // double clipping = (double)fpTool.fParam[Sid].roiP[i].ClippingPer / 100; // Clipping = (int)(iNum * clipping); // if (Clipping == iNum / 2) // { // Clipping = iNum / 2 - 1; // } // HTuple lineAngle; // //取Roi角度 // lineAngle = 1.571 - fpTool.fParam[Sid].roiP[i].phi; // double angle1 = 1.571 + fpTool.fParam[Sid].roiP[i].phi; // double Smoothcont = fpTool.fParam[Sid].roiP[i].SmoothCont; // string IgnoreStr = IgnorPoint(row, col, angle1, Smoothcont, out row, out col); // if (IgnoreStr != "OK") // { // return "忽略点处理失败" + IgnoreStr; // } // if (hwind != null && debug) // { // HObject Cross = new HObject(); // HOperatorSet.GenCrossContourXld(out Cross, row, col, 5, 0.5); // Action sw = () => // { // hwind.viewWindow.displayHobject(Cross, "green", false); // }; // hwind.Invoke(sw); // if (fpTool.fParam[Sid].roiP[i].useMidPt) // { // HObject Cross1 = new HObject(); // HOperatorSet.GenCrossContourXld(out Cross1, edgeRow, edgeCol, 5, 0.5); // Action sw2 = () => // { // hwind.viewWindow.displayHobject(Cross1, "green", false); // }; // hwind.Invoke(sw2); // } // } // //直线段拟合 // //if (fpTool.fParam[Sid].roiP[i].LineOrCircle != "圆弧段") // //{ // HObject line = new HObject(); // HOperatorSet.GenContourPolygonXld(out line, row, col); // HTuple Rowbg, Colbg, RowEd, ColEd, Nr, Nc, Dist; // HOperatorSet.FitLineContourXld(line, "tukey", -1, Clipping, 5, 2, out Rowbg, out Colbg, out RowEd, out ColEd, out Nr, out Nc, out Dist); // HOperatorSet.GenContourPolygonXld(out line, Rowbg.TupleConcat(RowEd), Colbg.TupleConcat(ColEd)); // HObject lineEdge = new HObject(); // if (fpTool.fParam[Sid].roiP[i].useMidPt) // { // HOperatorSet.GenContourPolygonXld(out lineEdge, edgeRow, edgeCol); // HTuple Rowbg1, Colbg1, RowEd1, ColEd1, Nr1, Nc1, Dist1; // HOperatorSet.FitLineContourXld(lineEdge, "tukey", -1, Clipping, 5, 2, out Rowbg1, out Colbg1, out RowEd1, out ColEd1, out Nr1, out Nc1, out Dist1); // HOperatorSet.GenContourPolygonXld(out lineEdge, Rowbg1.TupleConcat(RowEd1), Colbg1.TupleConcat(ColEd1)); // HTuple midRbg = (Rowbg + Rowbg1) / 2; // HTuple midRed = (RowEd + RowEd1) / 2; // HTuple midCbg = (Colbg + Colbg1) / 2; // HTuple midCed = (ColEd + ColEd1) / 2; // Rowbg = midRbg; // RowEd = midRed; // Colbg = midCbg; // ColEd = midCed; // } // //取拟合线与ROI中心交点 // //HObject RoiCenter = new HObject(); // HTuple recCoord = fpTool.roiList2[Sid][i].getModelData(); // HTuple CenterR = new HTuple(); HTuple CenterC = new HTuple(); // if (homMatFix != null) // { // HOperatorSet.AffineTransPoint2d(homMatFix, recCoord[0], recCoord[1], out CenterR, out CenterC); // } // else // { // CenterR = recCoord[0]; // CenterC = recCoord[1]; // } // double EndR = CenterR + 100 * Math.Sin(fpTool.fParam[Sid].roiP[i].phi); // double EndC = CenterC + 100 * Math.Cos(fpTool.fParam[Sid].roiP[i].phi); // //HOperatorSet.GenRegionLine(out RoiCenter, fpTool.fParam[Sid].roiP[i].CenterRow, fpTool.fParam[Sid].roiP[i].CenterCol, EndR, EndC); // //HOperatorSet.GenRegionLine(out line, Rowbg, Colbg, RowEd, ColEd); // //if (hwind != null && debug) // //{ // // hwind.viewWindow.displayHobject(RoiCenter); // // hwind.viewWindow.displayHobject(line); // //} // HTuple isOverlapping = new HTuple(); // HOperatorSet.IntersectionLines(CenterR, CenterC, EndR, EndC, Rowbg, Colbg, RowEd, ColEd, out row, out col, out isOverlapping); // double Xresolution = MyGlobal.globalConfig.dataContext.xResolution; // double Yresolution = MyGlobal.globalConfig.dataContext.yResolution; // if (Xresolution == 0) // { // return "XResolution=0"; // } // double DisX = fpTool.fParam[Sid].roiP[i].offset * Math.Sin(lineAngle.D) / Xresolution; // double DisY = fpTool.fParam[Sid].roiP[i].offset * Math.Cos(lineAngle.D) / Yresolution; // double D = Math.Sqrt(DisX * DisX + DisY * DisY); // if (fpTool.fParam[Sid].roiP[i].offset > 0) // { // D = -D; // } // double distR = D * Math.Cos(lineAngle.D); // double distC = D * Math.Sin(lineAngle.D); // //row = (Rowbg.D + RowEd.D) / 2 - distR; // //col = (Colbg.D + ColEd.D) / 2 - distC; // row = row.D - distR; // col = col.D - distC; // double xOffset = fpTool.fParam[Sid].roiP[i].Xoffset / Xresolution; // double yOffset = fpTool.fParam[Sid].roiP[i].Yoffset / Yresolution; // row = row - yOffset; // col = col - xOffset; // if (hwind != null) // { // HObject cross1 = new HObject(); // HOperatorSet.GenCrossContourXld(out cross1, row, col, 30, 0.5); // Action sw = () => // { // hwind.viewWindow.displayHobject(cross1, "cadet blue", false); // }; // hwind.Invoke(sw); // } // //HTuple linephi = new HTuple(); // //HOperatorSet.LineOrientation(Rowbg, Colbg, RowEd, ColEd, out linephi); // //HTuple deg = -(new HTuple(linephi.D)).TupleDeg(); // //double tan = Math.Tan(-linephi.D); // //int len1 = Math.Abs((int)(Rowbg.D - RowEd.D)); // //int len2 = Math.Abs((int)(Colbg.D - ColEd.D)); // //int len = len1 > len2 ? len1 : len2; // //HTuple x0 = Colbg.D; // //HTuple y0 = Rowbg.D; // //double[] newr = new double[len]; double[] newc = new double[len]; // //for (int m = 0; m < len; m++) // //{ // // HTuple row1 = new HTuple(); HTuple col1 = new HTuple(); // // if (len1 > len2) // // { // // row1 = Rowbg.D > RowEd.D ? y0 - m : y0 + m; // // col1 = Rowbg.D > RowEd.D ? x0 - m / tan : x0 + m / tan; // // } // // else // // { // // row1 = Colbg.D > ColEd.D ? y0 - m * tan : y0 + m * tan; // // col1 = Colbg.D > ColEd.D ? x0 - m : x0 + m; // // } // // newr[m] = row1; // // newc[m] = col1; // //} // //row = newr;col = newc; // //HOperatorSet.GenContourPolygonXld(out line, row, col); // if (hwind != null && debug) // { // Action sw = () => // { // hwind.viewWindow.displayHobject(line, "red"); // hwind.viewWindow.displayHobject(lineEdge, "red"); // }; // hwind.Invoke(sw); // } // siglePart = line; // //} // //else // //{ // // HObject ArcObj = new HObject(); // // HOperatorSet.GenContourPolygonXld(out ArcObj, row, col); // // HTuple Rb, Cb, Re, Ce, Nr1, Nc1, Ptorder; // // HOperatorSet.FitLineContourXld(ArcObj, "tukey", -1, Clipping, 5, 2, out Rb, out Cb, out Re, out Ce, out Nr1, out Nc1, out Ptorder); // // HOperatorSet.GenContourPolygonXld(out ArcObj, Rb.TupleConcat(Re), Cb.TupleConcat(Ce)); // // HTuple lineAngle; // // HOperatorSet.AngleLx(Rb, Cb, Re, Ce, out lineAngle); // // double Xresolution = MyGlobal.globalConfig.dataContext.xResolution; // // double Yresolution = MyGlobal.globalConfig.dataContext.yResolution; // // if (Xresolution == 0) // // { // // return "XResolution = 0"; // // } // // double DisX = fpTool.fParam[Sid].roiP[i].offset * Math.Sin(lineAngle.D) / Xresolution; // // double DisY = fpTool.fParam[Sid].roiP[i].offset * Math.Cos(lineAngle.D) / Yresolution; // // double D = Math.Sqrt(DisX * DisX + DisY * DisY); // // if (fpTool.fParam[Sid].roiP[i].offset < 0) // // { // // D = -D; // // } // // double distR = D * Math.Cos(lineAngle.D); // // double distC = D * Math.Sin(lineAngle.D); // // row = (Rb.D + Re.D) / 2 - distR; // // col = (Cb.D + Ce.D) / 2 - distC; // // double xOffset = fpTool.fParam[Sid].roiP[i].Xoffset / Xresolution; // // double yOffset = fpTool.fParam[Sid].roiP[i].Yoffset / Yresolution; // // row = row - yOffset; // // col = col - xOffset; // // if (hwind != null) // // { // // HObject CrossArc = new HObject(); // // HOperatorSet.GenCrossContourXld(out CrossArc, row, col, 30, 0.5); // // hwind.viewWindow.displayHobject(CrossArc, "blue"); // // } // // if (hwind != null && debug) // // { // // hwind.viewWindow.displayHobject(ArcObj, "red"); // // hwind.viewWindow.dispMessage(msg, "blue", row.D, col.D); // // } // // siglePart = ArcObj; // //} // //加上 x y z 偏移 // //row = row + fpTool.fParam[Sid].roiP[i].Yoffset; // //col = col + fpTool.fParam[Sid].roiP[i].Xoffset; // //旋转至原图 // //HOperatorSet.AffineTransPoint2d(homMatRotateInvert, row, col, out row, out col); // HTuple AvraRow = new HTuple(), AvraCol = new HTuple(), AvraZ = new HTuple(); // int PointCount = fpTool.fParam[Sid].roiP[i].NumOfSection; // //取Z值 // HTuple zcoord = new HTuple(); // try // { // HOperatorSet.GetGrayval(HeightImage, row, col, out zcoord); // } // catch (Exception) // { // return "偏移点" + msg + "设置在图像之外"; // } // #region MyRegion // ////除去 -100 的点 // //HTuple eq100 = new HTuple(); // //HOperatorSet.TupleLessElem(zcoord, -5, out eq100); // //HTuple eq100Id = new HTuple(); // //HOperatorSet.TupleFind(eq100, 1, out eq100Id); // //HTuple not5 = eq100.TupleFind(0); // //HTuple Total = zcoord[not5]; // //HTuple Mean = Total.TupleMean(); // //if (eq100Id != -1) // //{ // // for (int m = 0; m < eq100Id.Length; m++) // // { // // if (eq100Id[m] == 0) // // { // // HTuple meanZ = new HTuple(); // // meanZ = meanZ.TupleConcat(zcoord[eq100Id[m].D], zcoord[eq100Id[m].D + 1], zcoord[eq100Id[m].D + 2], zcoord[eq100Id[m].D + 3], zcoord[eq100Id[m].D + 4], zcoord[eq100Id[m].D + 5]); // // HTuple eq30 = new HTuple(); // // HOperatorSet.TupleGreaterElem(meanZ, -5, out eq30); // // HTuple eq30Id = new HTuple(); // // HOperatorSet.TupleFind(eq30, 1, out eq30Id); // // if (eq30Id != -1) // // { // // meanZ = meanZ[eq30Id]; // // meanZ = meanZ.TupleMean(); // // zcoord[eq100Id[m].D] = meanZ; // // } // // else // // { // // meanZ = Mean; // // zcoord[eq100Id[m].D] = meanZ; // // } // // } // // if (eq100Id[m] - 1 >= 0) // // { // // if (zcoord[eq100Id[m].D - 1].D < -5) // // { // // zcoord[eq100Id[m].D] = Mean; // // } // // else // // { // // zcoord[eq100Id[m].D] = zcoord[eq100Id[m].D - 1]; // // } // // } // // else // // { // // zcoord[eq100Id[m].D] = Mean; // // } // // } // //} // ////将行列Z 均分 // //double Div = row.Length / (double) ((PointCount - 1)); // //if (Div <1) // //{ // // Div = 1; // //} // //for (int k = 0; k < PointCount; k++) // //{ // // if (k == 0) // // { // // AvraRow = AvraRow.TupleConcat(row[0]); // // AvraCol = AvraCol.TupleConcat(col[0]); // // AvraZ = AvraZ.TupleConcat(zcoord[0]); // // continue; // // } // // if (k == 529) // // { // // //Debug.WriteLine("k" + k); // // } // // //Debug.WriteLine("k" + k); // // int id = (int)(Div * k); // // if (id >= row.Length) // // { // // break; // // } // // AvraRow = AvraRow.TupleConcat(row[id]); // // AvraCol = AvraCol.TupleConcat(col[id]); // // AvraZ = AvraZ.TupleConcat(zcoord[id]); // //} // //row = AvraRow; // //col = AvraCol; // //zcoord = AvraZ; // //HTuple xc = new HTuple(); // //HOperatorSet.TupleGenSequence(0, zcoord.Length - 1, 1, out xc); // //HObject Cont = new HObject(); // //HOperatorSet.GenContourPolygonXld(out Cont, zcoord, xc); // //if (fpTool.fParam[Sid].roiP[i].LineOrCircle == "直线段") // //{ // // HTuple Rowbg1, Colbg1, RowEd1, ColEd1, Nr1, Nc1, Dist1; // // HOperatorSet.FitLineContourXld(Cont, "tukey", -1, 0, 5, 2, out Rowbg1, out Colbg1, out RowEd1, out ColEd1, out Nr1, out Nc1, out Dist1); // // HTuple linephi1 = new HTuple(); // // HOperatorSet.LineOrientation(Rowbg1, Colbg1, RowEd1, ColEd1, out linephi1); // // //HTuple deg = -(new HTuple(linephi1.D)).TupleDeg(); // // double tan1 = Math.Tan(-linephi1.D); // // int len11 = Math.Abs((int)(Rowbg1.D - RowEd1.D)); // // int len21 = Math.Abs((int)(Colbg1.D - ColEd1.D)); // // int len0 = zcoord.Length; // // HTuple x01 = Colbg1.D; // // HTuple y01 = Rowbg1.D; // // double[] newr1 = new double[len0]; double[] newc1 = new double[len0]; // // for (int m = 0; m < len0; m++) // // { // // HTuple row1 = new HTuple(); HTuple col1 = new HTuple(); // // if (len11 > len21) // // { // // row1 = Rowbg1.D > RowEd1.D ? y01 - m : y01 + m; // // col1 = Rowbg1.D > RowEd1.D ? x01 - m / tan1 : x01 + m / tan1; // // } // // else // // { // // row1 = Colbg1.D > ColEd1.D ? y01 - m * tan1 : y01 + m * tan1; // // col1 = Colbg1.D > ColEd1.D ? x01 - m : x01 + m; // // } // // newr1[m] = row1; // // newc1[m] = col1; // // } // // zcoord = newr1; xc = newc1; // //} // //else // //{ // // HOperatorSet.GenContourPolygonXld(out Cont, xc, zcoord); // // HOperatorSet.SmoothContoursXld(Cont, out Cont, 15); // // HOperatorSet.GetContourXld(Cont, out xc, out zcoord); // //} // //HTuple origRow = row; // //HTuple origCol = col; // #region 单边去重 // //if (i > 0) // //{ // // HObject regXld = new HObject(); // // HOperatorSet.GenRegionContourXld(siglePart, out regXld, "filled"); // // HTuple phi; // // HOperatorSet.RegionFeatures(regXld, "phi", out phi); // // phi = phi.TupleDeg(); // // phi = phi.TupleAbs(); // // //HTuple last1 = RowCoordt[i - 1][0];//x1 // // //HTuple lastc1 = ColCoordt[i - 1][0];//x1 // // //HTuple sub1 = Math.Abs(row[0].D - last1.D); // // //HTuple sub2 = Math.Abs(col[0].D - lastc1.D); // // //HTuple pt1 = sub1.D > sub2.D ? RowCoordt[i - 1][RowCoordt[i - 1].Length - 1] : ColCoordt[i - 1][ColCoordt[i - 1].Length - 1]; // // HTuple pt1 = phi.D > 75 ? RowCoordt[i - 1][RowCoordt[i - 1].Length - 1] : ColCoordt[i - 1][ColCoordt[i - 1].Length - 1]; // // HTuple colbase = Sid == 0 || Sid == 2 ? col.TupleLessEqualElem(pt1) : col.TupleGreaterEqualElem(pt1); // // HTuple Grater1 = phi.D > 75 ? row.TupleGreaterEqualElem(pt1) : colbase; // // switch (Sid) // // { // // case 0: //x2>x1 // // HTuple Grater1id = Grater1.TupleFind(1); // // row = row.TupleRemove(Grater1id); // // col = col.TupleRemove(Grater1id); // // zcoord = zcoord.TupleRemove(Grater1id); // // break; // // case 1: //y2>y1 // // HTuple Grater2id = Grater1.TupleFind(1); // // row = row.TupleRemove(Grater2id); // // col = col.TupleRemove(Grater2id); // // //origRow = origRow.TupleRemove(Grater2id); // // //origCol = origCol.TupleRemove(Grater2id); // // zcoord = zcoord.TupleRemove(Grater2id); // // break; // // case 2: //x2<x1 // // HTuple Grater3id = Grater1.TupleFind(1); // // row = row.TupleRemove(Grater3id); // // col = col.TupleRemove(Grater3id); // // //origRow = origRow.TupleRemove(Grater3id); // // //origCol = origCol.TupleRemove(Grater3id); // // zcoord = zcoord.TupleRemove(Grater3id); // // break; // // case 3: //y2<y1 // // HTuple Grater4id = Grater1.TupleFind(1); // // row = row.TupleRemove(Grater4id); // // col = col.TupleRemove(Grater4id); // // //origRow = origRow.TupleRemove(Grater4id); // // //origCol = origCol.TupleRemove(Grater4id); // // zcoord = zcoord.TupleRemove(Grater4id); // // break; // // } // //} // //if (row.Length == 0) // //{ // // return "单边设置 区域重复点数过大"; // //} // #endregion 单边去重 // #endregion // // // if (hwind != null && debug == false) // { // HObject NewSide = new HObject(); // HOperatorSet.GenContourPolygonXld(out NewSide, row, col); // Action sw = () => // { // hwind.viewWindow.displayHobject(NewSide, "red"); // }; // hwind.Invoke(sw); // } // origRow = origRow.TupleConcat(row); // origCol = origCol.TupleConcat(col); // RowCoordt[i] = row; // ColCoordt[i] = col; // //进行矩阵变换 // if (HomMat3D != null) // { // //HOperatorSet.AffineTransPoint3d(HomMat3D, row, col,zcoord, out row, out col,out zcoord); // HOperatorSet.AffineTransPoint2d(HomMat3D, row, col, out row, out col); // zcoord = zcoord + fpTool.fParam[Sid].roiP[i].Zoffset + fpTool.fParam[Sid].SigleZoffset + MyGlobal.globalConfig.TotalZoffset; // row = row + MyGlobal.globalConfig.gbParam[Sid].Xoffset; // col = col + MyGlobal.globalConfig.gbParam[Sid].Yoffset; // } // for (int n = 0; n < row.Length; n++) // { // Str.Append(row[n].D.ToString() + "," + col[n].D.ToString() + "," + zcoord[n].D.ToString() + "\r\n"); // } // RowCoord[i] = row; // ColCoord[i] = col; // ZCoord[i] = zcoord; // StrLineOrCircle[i] = new string[zcoord.Length]; // //ColCoordt[i] = col; // //ZCoordt[i] = zcoord; // //StrLineOrCircle[i][0] = fpTool.fParam[Sid].roiP[i].LineOrCircle == "直线段" ? "1;" : "2;"; // switch (fpTool.fParam[Sid].roiP[i].LineOrCircle) // { // case "连接段": // StrLineOrCircle[i][0] = "0;"; // break; // case "直线段": // StrLineOrCircle[i][0] = "1;"; // break; // case "圆弧段": // StrLineOrCircle[i][0] = "2;"; // break; // } // //for (int n = 1; n < zcoord.Length; n++) // //{ // // if (n== zcoord.Length -1 && i == Len -1 && Sid !=3) //最后一段 第四边不给 // // { // // StrLineOrCircle[i][n] = StrLineOrCircle[i][0]; // // } // // else // // { // // StrLineOrCircle[i][n] = "0;"; // // } // //} // //NewZ = NewZ.TupleConcat(ZCoord[i][0]); // } // //HTuple zId = NewZ.TupleGreaterElem(-10); // //zId = zId.TupleFind(1); // //NewZ = NewZ[zId]; // //for (int i = 0; i < ZCoord.GetLength(0); i++) // //{ // // if (ZCoord[i]== null) // // { // // return "Find Point 第" + (i + 1).ToString() + "点未取到"; // // } // // if (ZCoord[i][0]==-30) // // { // // ZCoord[i][0] = NewZ.TupleMean(); // // } // //} // originalPoint[0] = origRow; // originalPoint[1] = origCol; // for (int i = 0; i < ZCoord.GetLength(0); i++) // { // //在当前点附近取圆 // HObject Circle = new HObject(); // double radius = fpTool.fParam[Sid].roiP[i].ZftRad; // if (ZCoord[i][0] < -10 && radius == 0) // { // radius = 0.05; // } // double Xresolution = MyGlobal.globalConfig.dataContext.xResolution; // radius = radius / Xresolution; // if (radius != 0) // { // HOperatorSet.GenCircle(out Circle, origRow[i], origCol[i], radius); // //if (debug && hwind !=null) // //{ // // hwind.viewWindow.displayHobject(Circle, "red"); // //} // HTuple rows, cols; HTuple Zpt = new HTuple(); // HOperatorSet.GetRegionPoints(Circle, out rows, out cols); // try // { // HOperatorSet.GetGrayval(HeightImage, rows, cols, out Zpt); // HTuple greater = new HTuple(); // HOperatorSet.TupleGreaterElem(Zpt, -10, out greater); // HTuple greaterId = greater.TupleFind(1); // if (greaterId.D == -1) // { // return "高度滤波区域" + fpTool.fParam[Sid].DicPointName[i] + "无有效z值"; // } // HTuple Zgreater = Zpt[greaterId]; // HTuple maxPer = fpTool.fParam[Sid].roiP[i].ZftMax / 100; // HTuple minPer = fpTool.fParam[Sid].roiP[i].ZftMin / 100; // int imax = (int)maxPer.D * Zgreater.Length; // int imin = (int)minPer.D * Zgreater.Length; // //if (imax != imin) // //{ // HTuple Down = Zgreater.TupleSelectRange(imin, Zgreater.Length - imax - 1); // ZCoord[i][0] = Down.TupleMean(); // //} // //else // //{ // // ZCoord[i][0] = Zgreater.TupleMean(); // //} // } // catch (Exception) // { // return "偏移点" + fpTool.fParam[Sid].DicPointName[i] + "设置在图像之外"; // } // } // else // { // } // string msg = fpTool.fParam[Sid].DicPointName[i] + "(" + Math.Round(ZCoord[i][0], 3).ToString() + ")"; // if (hwind != null) // { // Action sw = () => // { // hwind.viewWindow.dispMessage(msg, "blue", origRow[i], origCol[i]); // }; // hwind.Invoke(sw); // } // ////判断 Z 值高度 // if (MyGlobal.xyzBaseCoord.ZCoord != null && MyGlobal.xyzBaseCoord.ZCoord.Count != 0) // { // if (ZCoord[i][0] - MyGlobal.xyzBaseCoord.ZCoord[Sid][i][0] > MyGlobal.globalConfig.HeightMax || ZCoord[i][0] - MyGlobal.xyzBaseCoord.ZCoord[Sid][i][0] < MyGlobal.globalConfig.HeightMin) // { // if (hwind != null) // { // Action sw = () => // { // hwind.viewWindow.dispMessage(msg + "-Height NG", "red", origRow[i], origCol[i]); // }; // hwind.Invoke(sw); // } // return $"{msg}高度超出范围" + Math.Round(ZCoord[i][0], 3); // } // } // } // if (HomMat3D == null) // { // StaticOperate.writeTxt("D:\\Laser3DOrign.txt", Str.ToString()); // } // //RIntesity.Dispose(); // //RHeight.Dispose(); // return "OK"; // } // catch (Exception ex) // { // //RIntesity.Dispose(); // //RHeight.Dispose(); // return "FindPoint error:" + ex.Message; // } //} //[Obsolete] //public string FindPoint(int SideId, HObject HeightImage, out List<HTuple> HLines, HWindow_Final hwind = null, bool debug = false) //{ // //HObject RIntesity = new HObject(), RHeight = new HObject(); // StringBuilder Str = new StringBuilder(); // HLines = new List<HTuple>(); // double[][] RowCoord = null; double[][] ColCoord = null; double[][] ZCoord = null; string[][] StrLineOrCircle = null; // try // { // int Sid = SideId - 1; // string ok1 = GenProfileCoord(Sid + 1, HeightImage, out RArray, out Row, out CArray, out Phi, out Ignore, null); // if (ok1 != "OK") // { // return ok1; // } // int Len = fpTool.roiList2[Sid].Count;// 区域数量 // if (Len == 0) // { // //RIntesity.Dispose(); // //RHeight.Dispose(); // return "参数设置错误"; // } // RowCoord = new double[Len][]; ColCoord = new double[Len][]; ZCoord = new double[Len][]; StrLineOrCircle = new string[Len][]; // double[][] RowCoordt = new double[Len][]; double[][] ColCoordt = new double[Len][]; /*double[][] ZCoordt = new double[Len][];*/ // int Num = 0; int Add = 0; HTuple NewZ = new HTuple(); // for (int i = 0; i < Len; i++) // { // HTuple row = new HTuple(), col = new HTuple(); // for (int j = Num; j < Add + fpTool.fParam[Sid].roiP[i].NumOfSection; j++) // { // if (Num == 99) // { // Debug.WriteLine(Num); // } // //Debug.WriteLine(Num); // HTuple row1, col1; HTuple anchor, anchorc; // if (fpTool.fParam[Sid].roiP[i].SelectedType == 0) // { // if (fpTool.fParam[Sid].roiP[i].TopDownDist != 0 && fpTool.fParam[Sid].roiP[i].xDist != 0) // { // string ok = fpTool.FindMaxPtFallDown(Sid + 1, j, out row1, out col1, out anchor, out anchorc); // } // else // { // string ok = fpTool.FindMaxPt(Sid + 1, j, out row1, out col1, out anchor, out anchorc); // } // } // else // { // //取最高点下降 // string ok = fpTool.FindMaxPtFallDown(Sid + 1, j, out row1, out col1, out anchor, out anchorc); // } // row = row.TupleConcat(row1); // col = col.TupleConcat(col1); // Num++; // } // Add = Num; // if (row.Length < 2) // { // //return "区域" + (i + 1).ToString() + "拟合点数过少"; // HLines.Add(new HTuple()); // continue; // } // if (row.Length == 0) //区域之外 // { // continue; // } // HObject siglePart = new HObject(); // int Clipping = 0; // int iNum = row.Length; // double clipping = fpTool.fParam[Sid].roiP[i].ClippingPer / 100; // Clipping = (int)(iNum * clipping); // if (Clipping == iNum / 2) // { // Clipping = iNum / 2 - 1; // } // ////直线段拟合 // //if (fpTool.fParam[Sid].roiP[i].LineOrCircle != "圆弧段") // //{ // //除去偏离较大点 // HTuple lineAngle; // lineAngle = 1.571 - fpTool.fParam[Sid].roiP[i].phi; // double angle1 = 1.571 + fpTool.fParam[Sid].roiP[i].phi; // double Smoothcont = fpTool.fParam[Sid].roiP[i].SmoothCont; // string IgnoreStr = IgnorPoint(row, col, angle1, Smoothcont, out row, out col); // if (IgnoreStr != "OK") // { // return "忽略点处理失败" + IgnoreStr; // } // if (hwind != null && debug) // { // HObject Cross = new HObject(); // HOperatorSet.GenCrossContourXld(out Cross, row, col, 5, 0.5); // Action sw = () => // { // hwind.viewWindow.displayHobject(Cross, "green", false); // }; // hwind.Invoke(sw); // } // HObject line = new HObject(); // HOperatorSet.GenContourPolygonXld(out line, row, col); // HTuple Rowbg, Colbg, RowEd, ColEd, Nr, Nc, Dist; // HOperatorSet.FitLineContourXld(line, "tukey", -1, Clipping, 5, 2, out Rowbg, out Colbg, out RowEd, out ColEd, out Nr, out Nc, out Dist); // HOperatorSet.GenContourPolygonXld(out line, Rowbg.TupleConcat(RowEd), Colbg.TupleConcat(ColEd)); // //取拟合线与ROI中心交点 // //HObject RoiCenter = new HObject(); // HTuple recCoord = fpTool.roiList2[Sid][i].getModelData(); // HTuple CenterR = new HTuple(); HTuple CenterC = new HTuple(); // CenterR = recCoord[0]; // CenterC = recCoord[1]; // double EndR = CenterR + 100 * Math.Sin(fpTool.fParam[Sid].roiP[i].phi); // double EndC = CenterC + 100 * Math.Cos(fpTool.fParam[Sid].roiP[i].phi); // //HOperatorSet.GenRegionLine(out RoiCenter, fpTool.fParam[Sid].roiP[i].CenterRow, fpTool.fParam[Sid].roiP[i].CenterCol, EndR, EndC); // //HOperatorSet.GenRegionLine(out line, Rowbg, Colbg, RowEd, ColEd); // //if (hwind!=null && debug) // //{ // // hwind.viewWindow.displayHobject(RoiCenter); // // hwind.viewWindow.displayHobject(line); // //} // HTuple isOverlapping = new HTuple(); // HOperatorSet.IntersectionLines(CenterR, CenterC, EndR, EndC, Rowbg, Colbg, RowEd, ColEd, out row, out col, out isOverlapping); // double Xresolution = MyGlobal.globalConfig.dataContext.xResolution; // double Yresolution = MyGlobal.globalConfig.dataContext.yResolution; // if (Xresolution == 0) // { // return "XResolution=0"; // } // double DisX = fpTool.fParam[Sid].roiP[i].offset * Math.Sin(lineAngle.D) / Xresolution; // double DisY = fpTool.fParam[Sid].roiP[i].offset * Math.Cos(lineAngle.D) / Yresolution; // double D = Math.Sqrt(DisX * DisX + DisY * DisY); // if (fpTool.fParam[Sid].roiP[i].offset > 0) // { // D = -D; // } // double distR = D * Math.Cos(lineAngle.D); // double distC = D * Math.Sin(lineAngle.D); // double xOffset = fpTool.fParam[Sid].roiP[i].Xoffset / Xresolution; // double yOffset = fpTool.fParam[Sid].roiP[i].Yoffset / Yresolution; // Rowbg = Rowbg.D - distR + yOffset; // RowEd = RowEd.D - distR + yOffset; // Colbg = Colbg.D - distC + xOffset; // ColEd = ColEd.D - distC + xOffset; // HTuple lineCoord = Rowbg.TupleConcat(Colbg).TupleConcat(RowEd).TupleConcat(ColEd); // HLines.Add(lineCoord); // //row = (Rowbg.D + RowEd.D) / 2; // //col = (Colbg.D + ColEd.D) / 2; // row = row - distR + yOffset; // col = col - distC + xOffset; // if (hwind != null) // { // HObject cross1 = new HObject(); // HOperatorSet.GenCrossContourXld(out cross1, row, col, 30, 0.5); // Action sw = () => // { // hwind.viewWindow.displayHobject(cross1, "yellow"); // }; // hwind.Invoke(sw); // } // //HTuple linephi = new HTuple(); // //HOperatorSet.LineOrientation(Rowbg, Colbg, RowEd, ColEd, out linephi); // //HTuple deg = -(new HTuple(linephi.D)).TupleDeg(); // //double tan = Math.Tan(-linephi.D); // //int len1 = Math.Abs((int)(Rowbg.D - RowEd.D)); // //int len2 = Math.Abs((int)(Colbg.D - ColEd.D)); // //int len = len1 > len2 ? len1 : len2; // //HTuple x0 = Colbg.D; // //HTuple y0 = Rowbg.D; // //double[] newr = new double[len]; double[] newc = new double[len]; // //for (int m = 0; m < len; m++) // //{ // // HTuple row1 = new HTuple(); HTuple col1 = new HTuple(); // // if (len1 > len2) // // { // // row1 = Rowbg.D > RowEd.D ? y0 - m : y0 + m; // // col1 = Rowbg.D > RowEd.D ? x0 - m / tan : x0 + m / tan; // // } // // else // // { // // row1 = Colbg.D > ColEd.D ? y0 - m * tan : y0 + m * tan; // // col1 = Colbg.D > ColEd.D ? x0 - m : x0 + m; // // } // // newr[m] = row1; // // newc[m] = col1; // //} // //row = newr;col = newc; // //HOperatorSet.GenContourPolygonXld(out line, row, col); // if (hwind != null && debug) // { // Action sw = () => // { // hwind.viewWindow.displayHobject(line, "red"); // }; // hwind.Invoke(sw); // } // siglePart = line; // //} // //else // //{ // // HObject ArcObj = new HObject(); // // HOperatorSet.GenContourPolygonXld(out ArcObj, row, col); // // HTuple Rowbg, Colbg, RowEd, ColEd, Nr1, Nc1, Ptorder; // // HOperatorSet.FitLineContourXld(ArcObj, "tukey", -1, Clipping, 5, 2, out Rowbg, out Colbg, out RowEd, out ColEd, out Nr1, out Nc1, out Ptorder); // // HOperatorSet.GenContourPolygonXld(out ArcObj, Rowbg.TupleConcat(RowEd), Colbg.TupleConcat(ColEd)); // // HTuple lineAngle; // // HOperatorSet.AngleLx(Rowbg, Colbg, RowEd, ColEd, out lineAngle); // // double Xresolution = MyGlobal.globalConfig.dataContext.xResolution; // // double Yresolution = MyGlobal.globalConfig.dataContext.yResolution; // // if (Xresolution == 0) // // { // // return "XResolution=0"; // // } // // double DisX = fpTool.fParam[Sid].roiP[i].offset * Math.Sin(lineAngle.D) / Xresolution; // // double DisY = fpTool.fParam[Sid].roiP[i].offset * Math.Cos(lineAngle.D) / Yresolution; // // double D = Math.Sqrt(DisX * DisX + DisY * DisY); // // if (fpTool.fParam[Sid].roiP[i].offset < 0) // // { // // D = -D; // // } // // double distR = D * Math.Cos(lineAngle.D); // // double distC = D * Math.Sin(lineAngle.D); // // double xOffset = fpTool.fParam[Sid].roiP[i].Xoffset / Xresolution; // // double yOffset = fpTool.fParam[Sid].roiP[i].Yoffset / Yresolution; // // Rowbg = Rowbg.D - distR + yOffset; // // RowEd = RowEd.D - distR + yOffset; // // Colbg = Colbg.D - distC + xOffset; // // ColEd = ColEd.D - distC + xOffset; // // row = (Rowbg.D + RowEd.D) / 2 ; // // col = (Colbg.D + ColEd.D) / 2 ; // // HTuple lineCoord = Rowbg.TupleConcat(Colbg).TupleConcat(RowEd).TupleConcat(ColEd); // // HLines.Add(lineCoord); // // if (hwind != null) // // { // // HObject CrossArc = new HObject(); // // HOperatorSet.GenCrossContourXld(out CrossArc, row, col, 30, 0.5); // // hwind.viewWindow.displayHobject(CrossArc, "blue"); // // } // // if (hwind != null && debug) // // { // // hwind.viewWindow.displayHobject(ArcObj, "red"); // // } // // siglePart = ArcObj; // //} // if (hwind != null) // { // //string[] color = { "red", "blue", "green", "lime green", "black" }; // if (row.Length != 0) // { // //Random rad = new Random(); // //int radi = rad.Next(4); // string msg = ""; // //foreach (var item in DicPointName[Sid]) // //{ // // if (item.Value == i) // // { // // msg = item.Key; // // } // //} // msg = fpTool.fParam[Sid].DicPointName[i]; // Action sw = () => // { // hwind.viewWindow.dispMessage("Fix" + msg, "red", row.D, col.D); // }; // hwind.Invoke(sw); // } // } // if (hwind != null) // { // HObject cross1 = new HObject(); // HOperatorSet.GenCrossContourXld(out cross1, row, col, 30, 0.5); // Action sw = () => // { // hwind.viewWindow.displayHobject(cross1, "red"); // }; // hwind.Invoke(sw); // } // //加上 x y z 偏移 // //row = row + fpTool.fParam[Sid].roiP[i].Yoffset; // //col = col + fpTool.fParam[Sid].roiP[i].Xoffset; // //旋转至原图 // //HOperatorSet.AffineTransPoint2d(homMatRotateInvert, row, col, out row, out col); // HTuple AvraRow = new HTuple(), AvraCol = new HTuple(), AvraZ = new HTuple(); // int PointCount = fpTool.fParam[Sid].roiP[i].NumOfSection; // ////取Z值 // //HTuple zcoord = new HTuple(); // //try // //{ // // HOperatorSet.GetGrayval(HeightImage, row, col, out zcoord); // //} // //catch (Exception) // //{ // // return "偏移点设置在图像之外"; // //} // // // if (hwind != null && debug == false) // { // HObject NewSide = new HObject(); // HOperatorSet.GenContourPolygonXld(out NewSide, row, col); // Action sw = () => // { // hwind.viewWindow.displayHobject(NewSide, "red"); // }; // hwind.Invoke(sw); // } // RowCoord[i] = row; // ColCoord[i] = col; // //ZCoord[i] = zcoord; // //StrLineOrCircle[i] = new string[zcoord.Length]; // //ColCoordt[i] = col; // //ZCoordt[i] = zcoord; // //StrLineOrCircle[i][0] = fpTool.fParam[Sid].roiP[i].LineOrCircle == "直线段" ? "1;" : "2;"; // //for (int n = 1; n < zcoord.Length; n++) // //{ // // if (n == zcoord.Length - 1 && i == Len - 1 && Sid != 3) //最后一段 第四边不给 // // { // // StrLineOrCircle[i][n] = StrLineOrCircle[i][0]; // // } // // else // // { // // StrLineOrCircle[i][n] = "0;"; // // } // //} // //NewZ = NewZ.TupleConcat(ZCoord[i][0]); // } // //HTuple zId = NewZ.TupleGreaterElem(-10); // //zId = zId.TupleFind(1); // //NewZ = NewZ[zId]; // //for (int i = 0; i < ZCoord.GetLength(0); i++) // //{ // // if (ZCoord[i] == null) // // { // // return "Find Point 第" + (i + 1).ToString() + "点未取到"; // // } // // if (ZCoord[i][0] == -30) // // { // // ZCoord[i][0] = NewZ.TupleMean(); // // } // //} // //RIntesity.Dispose(); // //RHeight.Dispose(); // return "OK"; // } // catch (Exception ex) // { // //RIntesity.Dispose(); // //RHeight.Dispose(); // return "FindPoint error:" + ex.Message; // } //} //[Obsolete] //string IgnorPoint(HTuple row, HTuple col, double Phi, double SmoothCont, out HTuple Row, out HTuple Col) //{ // Row = new HTuple(); Col = new HTuple(); // try // { // HTuple RowMean, ColMean, RowMedian, ColMedian; // HOperatorSet.TupleMean(row, out RowMean); // HOperatorSet.TupleMean(col, out ColMean); // HOperatorSet.TupleMedian(row, out RowMedian); // HOperatorSet.TupleMedian(col, out ColMedian); // double SubR = Math.Abs(RowMean.D - RowMedian.D); // double SubC = Math.Abs(ColMean.D - ColMedian.D); // double Sin = Math.Sin(Phi); // double Cos = Math.Cos(Phi); // double Standard = SubR * Cos + SubC * Sin; // int Num = (int)(row.Length * SmoothCont); // if (SmoothCont == 0 || SmoothCont == 1) // { // Row = row; // Col = col; // return "OK"; // } // HTuple SUB = new HTuple(); // for (int i = 0; i < row.Length; i++) // { // double rowsub = Math.Abs(row[i].D - RowMedian.D); // double colsub = Math.Abs(col[i].D - ColMedian.D); // //double sub1 = rowsub * Cos + colsub * Sin; // //SUB = SUB.TupleConcat(sub1); // double Add = rowsub * Cos * rowsub * Cos + colsub * Sin * colsub * Sin; // double Sqrt = Math.Sqrt(Add); // SUB = SUB.TupleConcat(Sqrt); // } // HTuple NewId = new HTuple(); // HTuple Less = new HTuple(); // HTuple Indices = new HTuple(); // HOperatorSet.TupleSortIndex(SUB, out Indices); // HTuple selected = new HTuple(); // HOperatorSet.TupleSelectRange(Indices, row.Length - Num, row.Length - 1, out selected); // HOperatorSet.TupleRemove(row, selected, out Row); // HOperatorSet.TupleRemove(col, selected, out Col); // return "OK"; // } // catch (Exception ex) // { // return "IgnorPoint error" + ex.Message; // } //} //#endregion public string FindPoint_BF(int SideId, HObject IntesityImage, HObject HeightImage, out double[][] RowCoord, out double[][] ColCoord, out double[][] ZCoord, out string[][] StrLineOrCircle, HTuple HomMat3D = null, HWindow_Final hwind = null, bool debug = false, HTuple homMatFix = null) { //HObject RIntesity = new HObject(), RHeight = new HObject(); StringBuilder Str = new StringBuilder(); RowCoord = null; ColCoord = null; ZCoord = null; StrLineOrCircle = null; try { int Sid = SideId - 1; string ok1 = fpTool.GenProfileCoord(Sid + 1, HeightImage, out FindPointTool.RArray, out FindPointTool.Row, out FindPointTool.CArray, out FindPointTool.Phi, out Ignore, homMatFix); if (ok1 != "OK") { return ok1; } int Len = fpTool.roiList2[Sid].Count;// 区域数量 if (Len == 0) { //RIntesity.Dispose(); //RHeight.Dispose(); return "参数设置错误"; } RowCoord = new double[Len][]; ColCoord = new double[Len][]; ZCoord = new double[Len][]; StrLineOrCircle = new string[Len][]; double[][] RowCoordt = new double[Len][]; double[][] ColCoordt = new double[Len][]; /*double[][] ZCoordt = new double[Len][];*/ int Num = 0; int Add = 0; for (int i = 0; i < Len; i++) { HTuple row = new HTuple(), col = new HTuple(); for (int j = Num; j < Add + fpTool.fParam[Sid].roiP[i].NumOfSection; j++) { if (Num == 99) { Debug.WriteLine(Num); } Debug.WriteLine(Num); HTuple row1, col1; HTuple anchor, anchorc; string ok = fpTool.FindMaxPt(Sid + 1, j, out row1, out col1, out anchor, out anchorc); //if (ok!="OK") //{ // return ok; //} row = row.TupleConcat(row1); col = col.TupleConcat(col1); Num++; } Add = Num; if (row.Length == 0) //区域之外 { continue; } HObject siglePart = new HObject(); //直线段拟合 if (fpTool.fParam[Sid].roiP[i].LineOrCircle == "直线段") { HObject line = new HObject(); HOperatorSet.GenContourPolygonXld(out line, row, col); HTuple Rowbg, Colbg, RowEd, ColEd, Nr, Nc, Dist; HOperatorSet.FitLineContourXld(line, "tukey", -1, 0, 5, 2, out Rowbg, out Colbg, out RowEd, out ColEd, out Nr, out Nc, out Dist); Rowbg = Rowbg + fpTool.fParam[Sid].roiP[i].offset; Colbg = Colbg + fpTool.fParam[Sid].roiP[i].Xoffset; RowEd = RowEd + fpTool.fParam[Sid].roiP[i].Yoffset2; ColEd = ColEd + fpTool.fParam[Sid].roiP[i].Xoffset2; row = (Rowbg.D + RowEd.D) / 2 + fpTool.fParam[Sid].roiP[i].offset; col = (Colbg.D + ColEd.D) / 2 + fpTool.fParam[Sid].roiP[i].Xoffset; HTuple linephi = new HTuple(); HOperatorSet.LineOrientation(Rowbg, Colbg, RowEd, ColEd, out linephi); HTuple deg = -(new HTuple(linephi.D)).TupleDeg(); double tan = Math.Tan(-linephi.D); int len1 = Math.Abs((int)(Rowbg.D - RowEd.D)); int len2 = Math.Abs((int)(Colbg.D - ColEd.D)); int len = len1 > len2 ? len1 : len2; HTuple x0 = Colbg.D; HTuple y0 = Rowbg.D; double[] newr = new double[len]; double[] newc = new double[len]; for (int m = 0; m < len; m++) { HTuple row1 = new HTuple(); HTuple col1 = new HTuple(); if (len1 > len2) { row1 = Rowbg.D > RowEd.D ? y0 - m : y0 + m; col1 = Rowbg.D > RowEd.D ? x0 - m / tan : x0 + m / tan; } else { row1 = Colbg.D > ColEd.D ? y0 - m * tan : y0 + m * tan; col1 = Colbg.D > ColEd.D ? x0 - m : x0 + m; } newr[m] = row1; newc[m] = col1; } row = newr; col = newc; HOperatorSet.GenContourPolygonXld(out line, row, col); ////两条线做判断 //if (Rowbg > RowEd)//从上往下 反向 //{ // row = row.TupleSelectRange(row.Length / 2, row.Length - 1); // col = col.TupleSelectRange(col.Length / 2, col.Length - 1); //} //else //{ // row = row.TupleSelectRange(0, row.Length / 2); // col = col.TupleSelectRange(0, col.Length / 2); //} if (hwind != null && debug) { hwind.viewWindow.displayHobject(line, "red"); } siglePart = line; } else { HObject ArcObj = new HObject(); HTuple tempR = new HTuple(row), tempC = new HTuple(col); for (int n = 0; n < row.Length; n++) { if (n > 1) { double sub = (row[n].D - row[n - 1].D); if (sub > 20) { tempR[n] = tempR[n - 1].D + 1; tempC[n] = tempC[n - 1].D + 1; } if (sub < -20) { tempR[n] = tempR[n - 1].D - 1; tempC[n] = tempC[n - 1].D + 1; } } } row = tempR; col = tempC; HOperatorSet.GenContourPolygonXld(out ArcObj, row, col); HOperatorSet.SmoothContoursXld(ArcObj, out ArcObj, 15); if (fpTool.fParam[Sid].roiP[i].Xoffset2 != 0) { HTuple homMat; HTuple deg1 = fpTool.fParam[Sid].roiP[i].Xoffset2; HTuple Phi1 = deg1.TupleRad(); HOperatorSet.VectorAngleToRigid(row[0], col[0], 0, row[0], col[0], Phi1, out homMat); HOperatorSet.AffineTransContourXld(ArcObj, out ArcObj, homMat); } HTuple Rb, Cb, Re, Ce, Nr1, Nc1, Ptorder; HOperatorSet.FitLineContourXld(ArcObj, "tukey", -1, 0, 5, 2, out Rb, out Cb, out Re, out Ce, out Nr1, out Nc1, out Ptorder); HOperatorSet.GetContourXld(ArcObj, out row, out col); row = row + fpTool.fParam[Sid].roiP[i].offset; col = col + fpTool.fParam[Sid].roiP[i].Xoffset; if (hwind != null && debug) { hwind.viewWindow.displayHobject(ArcObj, "blue"); } siglePart = ArcObj; } //加上 x y z 偏移 //row = row + fpTool.fParam[Sid].roiP[i].Yoffset; //col = col + fpTool.fParam[Sid].roiP[i].Xoffset; //旋转至原图 //HOperatorSet.AffineTransPoint2d(homMatRotateInvert, row, col, out row, out col); HTuple AvraRow = new HTuple(), AvraCol = new HTuple(), AvraZ = new HTuple(); int PointCount = fpTool.fParam[Sid].roiP[i].NumOfSection; //取Z值 HTuple zcoord = new HTuple(); HOperatorSet.GetGrayval(HeightImage, row, col, out zcoord); //除去 -100 的点 HTuple eq100 = new HTuple(); HOperatorSet.TupleLessElem(zcoord, -5, out eq100); HTuple eq100Id = new HTuple(); HOperatorSet.TupleFind(eq100, 1, out eq100Id); HTuple not5 = eq100.TupleFind(0); HTuple Total = zcoord[not5]; HTuple Mean = Total.TupleMean(); if (eq100Id != -1) { for (int m = 0; m < eq100Id.Length; m++) { if (eq100Id[m] == 0) { HTuple meanZ = new HTuple(); meanZ = meanZ.TupleConcat(zcoord[eq100Id[m].D], zcoord[eq100Id[m].D + 1], zcoord[eq100Id[m].D + 2], zcoord[eq100Id[m].D + 3], zcoord[eq100Id[m].D + 4], zcoord[eq100Id[m].D + 5]); HTuple eq30 = new HTuple(); HOperatorSet.TupleGreaterElem(meanZ, -5, out eq30); HTuple eq30Id = new HTuple(); HOperatorSet.TupleFind(eq30, 1, out eq30Id); if (eq30Id != -1) { meanZ = meanZ[eq30Id]; meanZ = meanZ.TupleMean(); zcoord[eq100Id[m].D] = meanZ; } else { meanZ = Mean; zcoord[eq100Id[m].D] = meanZ; } } if (eq100Id[m] - 1 >= 0) { if (zcoord[eq100Id[m].D - 1].D < -5) { zcoord[eq100Id[m].D] = Mean; } else { zcoord[eq100Id[m].D] = zcoord[eq100Id[m].D - 1]; } } else { zcoord[eq100Id[m].D] = Mean; } } } //将行列Z 均分 double Div = row.Length / (double)((PointCount - 1)); if (Div < 1) { Div = 1; } for (int k = 0; k < PointCount; k++) { if (k == 0) { AvraRow = AvraRow.TupleConcat(row[0]); AvraCol = AvraCol.TupleConcat(col[0]); AvraZ = AvraZ.TupleConcat(zcoord[0]); continue; } if (k == 529) { Debug.WriteLine("k" + k); } //Debug.WriteLine("k" + k); int id = (int)(Div * k); if (id >= row.Length) { break; } AvraRow = AvraRow.TupleConcat(row[id]); AvraCol = AvraCol.TupleConcat(col[id]); AvraZ = AvraZ.TupleConcat(zcoord[id]); } row = AvraRow; col = AvraCol; zcoord = AvraZ; HTuple xc = new HTuple(); HOperatorSet.TupleGenSequence(0, zcoord.Length - 1, 1, out xc); HObject Cont = new HObject(); HOperatorSet.GenContourPolygonXld(out Cont, zcoord, xc); if (fpTool.fParam[Sid].roiP[i].LineOrCircle == "直线段") { HTuple Rowbg1, Colbg1, RowEd1, ColEd1, Nr1, Nc1, Dist1; HOperatorSet.FitLineContourXld(Cont, "tukey", -1, 0, 5, 2, out Rowbg1, out Colbg1, out RowEd1, out ColEd1, out Nr1, out Nc1, out Dist1); HTuple linephi1 = new HTuple(); HOperatorSet.LineOrientation(Rowbg1, Colbg1, RowEd1, ColEd1, out linephi1); //HTuple deg = -(new HTuple(linephi1.D)).TupleDeg(); double tan1 = Math.Tan(-linephi1.D); int len11 = Math.Abs((int)(Rowbg1.D - RowEd1.D)); int len21 = Math.Abs((int)(Colbg1.D - ColEd1.D)); int len0 = zcoord.Length; HTuple x01 = Colbg1.D; HTuple y01 = Rowbg1.D; double[] newr1 = new double[len0]; double[] newc1 = new double[len0]; for (int m = 0; m < len0; m++) { HTuple row1 = new HTuple(); HTuple col1 = new HTuple(); if (len11 > len21) { row1 = Rowbg1.D > RowEd1.D ? y01 - m : y01 + m; col1 = Rowbg1.D > RowEd1.D ? x01 - m / tan1 : x01 + m / tan1; } else { row1 = Colbg1.D > ColEd1.D ? y01 - m * tan1 : y01 + m * tan1; col1 = Colbg1.D > ColEd1.D ? x01 - m : x01 + m; } newr1[m] = row1; newc1[m] = col1; } zcoord = newr1; xc = newc1; } else { HOperatorSet.GenContourPolygonXld(out Cont, xc, zcoord); HOperatorSet.SmoothContoursXld(Cont, out Cont, 15); HOperatorSet.GetContourXld(Cont, out xc, out zcoord); } HTuple origRow = row; HTuple origCol = col; if (true) #region 单边去重 if (i > 0) { HObject regXld = new HObject(); HOperatorSet.GenRegionContourXld(siglePart, out regXld, "filled"); HTuple phi; HOperatorSet.RegionFeatures(regXld, "phi", out phi); phi = phi.TupleDeg(); phi = phi.TupleAbs(); //HTuple last1 = RowCoordt[i - 1][0];//x1 //HTuple lastc1 = ColCoordt[i - 1][0];//x1 //HTuple sub1 = Math.Abs(row[0].D - last1.D); //HTuple sub2 = Math.Abs(col[0].D - lastc1.D); //HTuple pt1 = sub1.D > sub2.D ? RowCoordt[i - 1][RowCoordt[i - 1].Length - 1] : ColCoordt[i - 1][ColCoordt[i - 1].Length - 1]; HTuple pt1 = phi.D > 75 ? RowCoordt[i - 1][RowCoordt[i - 1].Length - 1] : ColCoordt[i - 1][ColCoordt[i - 1].Length - 1]; HTuple colbase = Sid == 0 || Sid == 2 ? col.TupleLessEqualElem(pt1) : col.TupleGreaterEqualElem(pt1); HTuple Grater1 = phi.D > 75 ? row.TupleGreaterEqualElem(pt1) : colbase; switch (Sid) { case 0: //x2>x1 HTuple Grater1id = Grater1.TupleFind(1); row = row.TupleRemove(Grater1id); col = col.TupleRemove(Grater1id); zcoord = zcoord.TupleRemove(Grater1id); break; case 1: //y2>y1 HTuple Grater2id = Grater1.TupleFind(1); row = row.TupleRemove(Grater2id); col = col.TupleRemove(Grater2id); //origRow = origRow.TupleRemove(Grater2id); //origCol = origCol.TupleRemove(Grater2id); zcoord = zcoord.TupleRemove(Grater2id); break; case 2: //x2<x1 HTuple Grater3id = Grater1.TupleFind(1); row = row.TupleRemove(Grater3id); col = col.TupleRemove(Grater3id); //origRow = origRow.TupleRemove(Grater3id); //origCol = origCol.TupleRemove(Grater3id); zcoord = zcoord.TupleRemove(Grater3id); break; case 3: //y2<y1 HTuple Grater4id = Grater1.TupleFind(1); row = row.TupleRemove(Grater4id); col = col.TupleRemove(Grater4id); //origRow = origRow.TupleRemove(Grater4id); //origCol = origCol.TupleRemove(Grater4id); zcoord = zcoord.TupleRemove(Grater4id); break; } } #endregion 单边去重 if (row.Length == 0) { return "单边设置 区域重复点数过大"; } if (hwind != null && debug == false) { HObject NewSide = new HObject(); HOperatorSet.GenContourPolygonXld(out NewSide, row, col); hwind.viewWindow.displayHobject(NewSide, "red"); } RowCoordt[i] = row; ColCoordt[i] = col; //进行矩阵变换 if (HomMat3D != null) { //HOperatorSet.AffineTransPoint3d(HomMat3D, row, col,zcoord, out row, out col,out zcoord); HOperatorSet.AffineTransPoint2d(HomMat3D, row, col, out row, out col); //zcoord = zcoord + fpTool.fParam[Sid].roiP[i].Zoffset + fpTool.fParam[Sid].SigleZoffset + MyGlobal.globalConfig.TotalZoffset; } for (int n = 0; n < row.Length; n++) { Str.Append(row[n].D.ToString() + "," + col[n].D.ToString() + "," + zcoord[n].D.ToString() + "\r\n"); } RowCoord[i] = row; ColCoord[i] = col; ZCoord[i] = zcoord; StrLineOrCircle[i] = new string[zcoord.Length]; //ColCoordt[i] = col; //ZCoordt[i] = zcoord; StrLineOrCircle[i][0] = fpTool.fParam[Sid].roiP[i].LineOrCircle == "直线段" ? "1;" : "2;"; for (int n = 1; n < zcoord.Length; n++) { if (n == zcoord.Length - 1 && i == Len - 1 && Sid != 3) //最后一段 第四边不给 { StrLineOrCircle[i][n] = StrLineOrCircle[i][0]; } else { StrLineOrCircle[i][n] = "0;"; } } //if (hwind != null && debug == false) //{ // HObject NewSide = new HObject(); // HOperatorSet.GenContourPolygonXld(out NewSide, row, col); // hwind.viewWindow.displayHobject(NewSide, "red"); //} } if (HomMat3D == null) { StaticOperate.writeTxt("D:\\Laser3D.txt", Str.ToString()); } //RIntesity.Dispose(); //RHeight.Dispose(); return "OK"; } catch (Exception ex) { //RIntesity.Dispose(); //RHeight.Dispose(); return "FindPoint error:" + ex.Message; } } private void 更改ToolStripMenuItem_Click(object sender, EventArgs e) { try { int Id = Convert.ToInt32(SideName.Substring(4, 1)) - 1; if (dataGridView1.CurrentCell == null) { return; } if (fpTool.roiList2[Id].Count > 0 && roiController2.ROIList.Count == fpTool.roiList2[Id].Count) { int roiID = dataGridView1.CurrentCell.RowIndex; roiID = CurrentRowIndex; if (roiID < 0) { return; } RoiIsMoving = true; if (roiID >= 0) { //fpTool.fParam[Id].roiP[roiId].LineOrCircle = fpTool.fParam[Id].roiP[roiId].LineOrCircle == "直线段" ? "圆弧段" : "直线段"; //comboBox2.SelectedItem = fpTool.fParam[Id].roiP[roiId].LineOrCircle; switch (fpTool.fParam[Id].roiP[roiID].LineOrCircle) { case "直线段": if (MessageBox.Show("更改为圆弧段(是)更改为连接段(否)", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes) { fpTool.fParam[Id].roiP[roiID].LineOrCircle = "圆弧段"; } else { fpTool.fParam[Id].roiP[roiID].LineOrCircle = "连接段"; } break; case "圆弧段": if (MessageBox.Show("更改为直线段(是)更改为连接段(否)", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes) { fpTool.fParam[Id].roiP[roiID].LineOrCircle = "直线段"; } else { fpTool.fParam[Id].roiP[roiID].LineOrCircle = "连接段"; } break; case "连接段": if (MessageBox.Show("更改为直线段(是)更改为圆弧段(否)", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes) { fpTool.fParam[Id].roiP[roiID].LineOrCircle = "直线段"; } else { fpTool.fParam[Id].roiP[roiID].LineOrCircle = "圆弧段"; } break; } comboBox2.SelectedItem = fpTool.fParam[Id].roiP[roiID].LineOrCircle; dataGridView1.Rows[roiID].Cells[2].Value = fpTool.fParam[Id].roiP[roiID].LineOrCircle; } RoiIsMoving = false; } } catch (Exception) { throw; } } private void FitLineSet_FormClosing(object sender, FormClosingEventArgs e) { if (isSave) { } else { DialogResult result = MessageBox.Show("当前参数未保存,是否关闭?", "提示:", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result != DialogResult.Yes) { e.Cancel = true; return; } } RoiParam.isInvoke = false; RoiParam.ChangeSection -= RoiParam_ChangeSection; //MyGlobal.Right_findPointTool_Find.Init("FitLineSet", isRight); //MyGlobal.Left_findPointTool_Find.Init("FitLineSet", isRight); //MyGlobal.Right_findPointTool_Fix.Init("Fix", isRight); //MyGlobal.Left_findPointTool_Fix.Init("Fix", isRight); //MyGlobal.flset2.Init(); if (hwindow_final1.Image != null) { hwindow_final1.Image.Dispose(); hwindow_final1.ClearWindow(); } if (hwindow_final2.Image != null) { hwindow_final2.Image.Dispose(); hwindow_final2.ClearWindow(); } RGBImage.Dispose(); checkBox1.Checked = false; checkBox2.Checked = false; checkBox4.Checked = false; checkBoxRoi.Checked = false; //comboBox1.SelectedIndex = 0; //comboBox2.SelectedIndex = 0; isCloing = true; CurrentSide = "Side1"; } bool isInsert = false; private void 插入ToolStripMenuItem_Click(object sender, EventArgs e) { isGenSection = false; if (dataGridView1.CurrentCell == null) { return; } int Id = Convert.ToInt32(SideName.Substring(4, 1)) - 1; if (hwindow_final2.Image == null || !hwindow_final2.Image.IsInitialized()) { return; } int currentId = dataGridView1.CurrentCell.RowIndex; currentId = CurrentRowIndex; if (currentId < 0) { return; } RoiIsMoving = true; isInsert = true; HTuple coord1 = fpTool.roiList[Id][currentId].getModelData(); HTuple coord2 = fpTool.roiList2[Id][currentId].getModelData(); List<ROI> roiListTemp = new List<ROI>(); List<ROI> roiListTemp1 = new List<ROI>(); HWindow_Final tempWindow = new HWindow_Final(); tempWindow.viewWindow.genRect2(coord2[0].D + 45, coord2[1].D + 45, coord2[2].D, coord2[3].D, coord2[4].D, ref roiListTemp); ROI temp2 = roiListTemp[0]; tempWindow.viewWindow.genRect1(coord1[0].D, coord1[1].D, coord1[2].D, coord1[3].D, ref roiListTemp1); ROI rec = roiListTemp1[0]; fpTool.roiList2[Id].Insert(currentId, temp2); fpTool.roiList[Id].Insert(currentId, rec); hwindow_final1.viewWindow.notDisplayRoi(); hwindow_final2.viewWindow.notDisplayRoi(); if (fpTool.roiList2[Id].Count > 0) { if (SelectAll) { hwindow_final2.viewWindow.notDisplayRoi(); roiController2.viewController.ShowAllRoiModel = -1; hwindow_final2.viewWindow.displayROI(ref fpTool.roiList2[Id]); } else { hwindow_final2.viewWindow.displayROI(ref fpTool.roiList2[Id]); roiController2.viewController.ShowAllRoiModel = currentId + 1; roiController2.viewController.repaint(currentId + 1); } hwindow_final2.viewWindow.setActiveRoi(currentId + 1); } if (fpTool.roiList[Id].Count > 0) { temp.Clear(); ROI roi = fpTool.roiList[Id][currentId + 1]; temp.Add(roi); hwindow_final1.viewWindow.notDisplayRoi(); hwindow_final1.viewWindow.displayROI(ref temp); } RoiParam RP = new RoiParam(); RP = fpTool.fParam[Id].roiP[currentId].Clone(); //新位置的 HTuple NewCoord = temp2.getModelData(); RP.CenterRow = NewCoord[0]; RP.CenterCol = NewCoord[1]; fpTool.fParam[Id].roiP.Insert(currentId, RP); fpTool.fParam[Id].roiP[currentId].LineOrCircle = comboBox2.SelectedItem.ToString(); //insert dataGridView1.Rows.Insert(currentId); dataGridView1.Rows[currentId].Cells[0].Value = currentId; dataGridView1.Rows[currentId].Cells[1].Value = "Default"; dataGridView1.Rows[currentId].Cells[2].Value = fpTool.fParam[Id].roiP[currentId].LineOrCircle; fpTool.fParam[Id].DicPointName.Insert(currentId, "Default"); //排序 for (int i = 0; i < dataGridView1.Rows.Count; i++) { dataGridView1.Rows[i].Cells[0].Value = i; } //roiController2.setROIShape(new ROIRectangle2()); RoiIsMoving = false; } int PtOrder = -1; private void simpleButton5_Click_1(object sender, EventArgs e)//偏移起终点1,2 { if (hwindow_final1.Image == null || !hwindow_final1.Image.IsInitialized()) { return; } SimpleButton sbtn = (SimpleButton)sender; hwindow_final1.viewWindow.notDisplayRoi(); switch (sbtn.Text) { case "偏移起点1": PtOrder = 0; roiController.setROIShape(new ROIPoint()); break; case "偏移终点1": PtOrder = 1; roiController.setROIShape(new ROIPoint()); break; case "偏移起点2": PtOrder = 2; roiController.setROIShape(new ROIPoint()); break; case "偏移终点2": PtOrder = 3; roiController.setROIShape(new ROIPoint()); break; } } bool edit = false; private void checkBoxRoi_CheckedChanged(object sender, EventArgs e)//ROI编辑模式 { edit = checkBoxRoi.Checked; if (edit) { hwindow_final1.viewWindow.setEditModel(true); hwindow_final2.viewWindow.setEditModel(true); } else { hwindow_final1.viewWindow.setEditModel(false); hwindow_final2.viewWindow.setEditModel(false); } } bool ReName = false; bool isSelectOne = false; string PreSelect = ""; private void textBox_OffsetX_TextChanged(object sender, EventArgs e) { try { if (isLoading) { return; } int SideId = Convert.ToInt32(SideName.Substring(4, 1)) - 1; TextBox tb = (TextBox)sender; string index = tb.Text.ToString(); //bool ok = Regex.IsMatch(index, @"(?i)^(\-[0-9]{1,}[.][0-9]*)+$") || Regex.IsMatch(index, @"(?i)^(\-[0-9]{1,}[0-9]*)+$") || Regex.IsMatch(index, @"(?i)^([0-9]{1,}[0-9]*)+$") || Regex.IsMatch(index, @"(?i)^(\[0-9]{1,}[0-9]*)+$"); bool ok = Regex.IsMatch(index, @"^[-]?\d+[.]?\d*$");//是否为数字 //bool ok = Regex.IsMatch(index, @"^([-]?)\d*$");//是否为整数 if (!ok || RoiIsMoving) { return; } double num = double.Parse(index); int roiID = dataGridView1.CurrentCell.RowIndex; roiID = CurrentRowIndex; if (roiID == -1) { return; } int count = dataGridView1.SelectedCells.Count; List<int> rowInd = new List<int>(); for (int i = 0; i < count; i++) { int Ind = dataGridView1.SelectedCells[i].RowIndex; if (!rowInd.Contains(Ind)) { rowInd.Add(Ind); } } for (int i = 0; i < rowInd.Count; i++) { switch (tb.Name) { case "textBox_OffsetX": fpTool.fParam[SideId].roiP[rowInd[i]].Xoffset = num; break; case "textBox_OffsetY": fpTool.fParam[SideId].roiP[rowInd[i]].Yoffset = num; break; case "textBox_Offset": fpTool.fParam[SideId].roiP[rowInd[i]].offset = num; break; case "textBox_ZFtMax": fpTool.fParam[SideId].roiP[rowInd[i]].ZftMax = (int)num; break; case "textBox_ZFtMin": fpTool.fParam[SideId].roiP[rowInd[i]].ZftMin = (int)num; break; case "textBox_ZFtRad": fpTool.fParam[SideId].roiP[rowInd[i]].ZftRad = num; break; case "textBox_downDist": fpTool.fParam[SideId].roiP[rowInd[i]].TopDownDist = num; break; case "textBox_xDist": fpTool.fParam[SideId].roiP[rowInd[i]].xDist = num; break; case "textBox_Clipping": //if (num > 50) //{ // textBox_Clipping.Text = "50"; // num = 50; //} //if (num < 0) //{ // textBox_Clipping.Text = "0"; // num = 0; //} fpTool.fParam[SideId].roiP[rowInd[i]].ClippingPer = num; break; case "textBox_SmoothCont": //if (num > 1) //{ // textBox_SmoothCont.Text = "1"; // num = 50; //} //if (num < 0) //{ // textBox_SmoothCont.Text = "0"; // num = 0; //} fpTool.fParam[SideId].roiP[rowInd[i]].SmoothCont = num; break; case "textBox_OffsetZ": fpTool.fParam[SideId].roiP[rowInd[i]].Zoffset = num; break; case "textBox_IndStart1": //fpTool.fParam[SideId].roiP[roiID].StartOffSet1 = (int)num; break; case "textBox_IndEnd1": //fpTool.fParam[SideId].roiP[roiID].EndOffSet1 = (int)num; break; case "textBox_IndStart2": //fpTool.fParam[SideId].roiP[roiID].StartOffSet2 = (int)num; break; case "textBox_IndEnd2": //fpTool.fParam[SideId].roiP[roiID].EndOffSet2 = (int)num; break; } } } catch (Exception) { throw; } } private void checkBox4_CheckedChanged(object sender, EventArgs e)//不启用定位 { NotUseFix = checkBox4.Checked; RoiParam.isInvoke = false; LoadToUI(); ChangeSide(); RoiParam.isInvoke = true; } bool isSelecting = false; private void dataGridView1_CurrentCellChanged(object sender, EventArgs e) { if (dataGridView1.CurrentCell == null || RoiIsMoving || isSelecting || isLoading) { return; } int roiID = dataGridView1.CurrentCell.RowIndex; if (roiID < 0) { return; } isSelecting = true; if (SelectAll) { } else { dataGridView1.ClearSelection(); dataGridView1.Rows[roiID].Selected = true; } isSelecting = false; try { isGenSection = false; RoiIsMoving = true; isSelectOne = false; int SideId = Convert.ToInt32(SideName.Substring(4, 1)) - 1; int id = roiID; //hwindow_final2.viewWindow.notDisplayRoi(); if (fpTool.roiList2[SideId].Count > 0) { if (SelectAll) { hwindow_final2.viewWindow.notDisplayRoi(); roiController2.viewController.ShowAllRoiModel = -1; hwindow_final2.viewWindow.displayROI(ref fpTool.roiList2[SideId]); hwindow_final2.viewWindow.selectROI(id); } else { if (roiController2.ROIList.Count != fpTool.roiList2[SideId].Count) { roiController2.viewController.ShowAllRoiModel = -1; hwindow_final2.viewWindow.displayROI(ref fpTool.roiList2[SideId]); } //hwindow_final2.viewWindow.notDisplayRoi(); //hwindow_final2.viewWindow.displayROI(ref fpTool.roiList2[SideId]); roiController2.viewController.ShowAllRoiModel = id; roiController2.viewController.repaint(id); } //if (SelectAll) //{ //roiController2.viewController.repaint(id); //} //else //{ // tempList.Clear(); // for (int i = 0; i < fpTool.roiList2[SideId].Count; i++) // { // ROI temp = (ROI)fpTool.roiList2[SideId][i]; // tempList.Add(temp); // } // hwindow_final2.viewWindow.displayROI(ref tempList, id); //} } else { return; } HTuple[] lineCoord = new HTuple[1]; //if (SelectAll) //{ fpTool.DispSection((ROIRectangle2)fpTool.roiList2[SideId][id], SideId, id, out lineCoord, hwindow_final2); //} //else //{ // DispSection((ROIRectangle2)tempList[0], SideId, id, out lineCoord, hwindow_final2); //} int pID = 1; for (int i = 0; i < id; i++) { for (int j = 0; j < fpTool.fParam[SideId].roiP[i].NumOfSection; j++) { pID++; } } CurrentIndex = pID; CurrentRowIndex = roiID; textBox_Current.Text = CurrentIndex.ToString(); HTuple row, col; HTuple anchor, anchorc; //fpTool.FindMaxPt(SideId + 1, CurrentIndex - 1, out row, out col, out anchor, out anchorc, hwindow_final1, ShowSection); if (fpTool.fParam[SideId].roiP[CurrentRowIndex].SelectedType == 0) { if (fpTool.fParam[SideId].roiP[CurrentRowIndex].TopDownDist != 0 && fpTool.fParam[SideId].roiP[CurrentRowIndex].xDist != 0) { fpTool.FindMaxPtFallDown(SideId + 1, CurrentIndex - 1, out row, out col, out anchor, out anchorc, hwindow_final1, ShowSection, false, hwindow_final2); } else { fpTool.FindMaxPt(SideId + 1, CurrentIndex - 1, out row, out col, out anchor, out anchorc, hwindow_final2, ShowSection, false, hwindow_final1); } } else { fpTool.FindMaxPtFallDown(SideId + 1, CurrentIndex - 1, out row, out col, out anchor, out anchorc, hwindow_final1, ShowSection, false, hwindow_final2); } //string[] color = {"red","blue","green", "lime green", "black" }; //if (row.Length != 0) //{ // //Random rad = new Random(); // //int i = rad.Next(4); // PreSelect = dataGridView1.Rows[id].Cells[1].Value.ToString(); // hwindow_final2.viewWindow.dispMessage(PreSelect, "blue", row.D, col.D); //} //HTuple tempData = new HTuple(); //List<ROI> temproi = new List<ROI>(); //tempData = fpTool.roiList2[SideId][id].getModelData(); //hwindow_final2.viewWindow.genRect2(tempData[0].D, tempData[1].D, tempData[2].D, fpTool.fParam[SideId].roiP[id].Len1, fpTool.fParam[SideId].roiP[id].Len2, ref temproi); //fpTool.roiList2[SideId][id] = temproi[0]; //hwindow_final2.viewWindow.notDisplayRoi(); //hwindow_final2.viewWindow.displayROI(ref fpTool.roiList2[SideId]); temp.Clear(); ROI roi = fpTool.roiList[SideId][id]; temp.Add(roi); hwindow_final1.viewWindow.notDisplayRoi(); hwindow_final1.viewWindow.displayROI(ref temp); propertyGrid1.SelectedObject = fpTool.fParam[SideId].roiP[id]; //textBox_Num.Text = ((int)fpTool.fParam[SideId].roiP[id].NumOfSection).ToString(); //textBox_Len.Text = ((int)fpTool.fParam[SideId].roiP[id].Len1).ToString(); //textBox_Width.Text = ((int)fpTool.fParam[SideId].roiP[id].Len2).ToString(); //textBox_Row.Text = ((int)fpTool.fParam[SideId].roiP[id].CenterRow).ToString(); //textBox_Col.Text = ((int)fpTool.fParam[SideId].roiP[id].CenterCol).ToString(); //HTuple deg = new HTuple(); //HOperatorSet.TupleDeg(fpTool.fParam[SideId].roiP[id].phi, out deg); //textBox_phi.Text = ((int)deg.D).ToString(); //textBox_Deg.Text = fpTool.fParam[SideId].roiP[id].AngleOfProfile.ToString(); //textBox_OffsetY.Text = fpTool.fParam[SideId].roiP[id].Yoffset.ToString(); //textBox_OffsetX.Text = fpTool.fParam[SideId].roiP[id].Xoffset.ToString(); //textBox_Offset.Text = fpTool.fParam[SideId].roiP[id].offset.ToString(); //textBox_OffsetZ.Text = fpTool.fParam[SideId].roiP[id].Zoffset.ToString(); //textBox_ZFtMax.Text = fpTool.fParam[SideId].roiP[id].ZftMax.ToString(); //textBox_ZFtMin.Text = fpTool.fParam[SideId].roiP[id].ZftMin.ToString(); //textBox_ZFtRad.Text = fpTool.fParam[SideId].roiP[id].ZftRad.ToString(); //textBox_Clipping.Text = fpTool.fParam[SideId].roiP[id].ClippingPer.ToString(); //textBox_SmoothCont.Text = fpTool.fParam[SideId].roiP[roiID].SmoothCont.ToString(); ////textBox_IndEnd2.Text = fpTool.fParam[SideId].roiP[id].EndOffSet2.ToString(); //comboBox2.SelectedItem = fpTool.fParam[SideId].roiP[id].LineOrCircle; ////label_xoffset2.Text = fpTool.fParam[SideId].roiP[id].LineOrCircle == "圆弧段" ? "旋转角度" : "x终点偏移"; ////label20.Text = fpTool.fParam[SideId].roiP[id].LineOrCircle == "圆弧段" ? "度" : "pix"; //checkBox_useLeft.Checked = fpTool.fParam[SideId].roiP[id].useLeft; //checkBox_center.Checked = fpTool.fParam[SideId].roiP[id].useCenter; //checkBox_zZoom.Checked = fpTool.fParam[SideId].roiP[id].useZzoom; //checkBox_midPt.Checked = fpTool.fParam[SideId].roiP[id].useMidPt; //checkBox_Far.Checked = !fpTool.fParam[SideId].roiP[id].useNear; //textBox_downDist.Text = fpTool.fParam[SideId].roiP[id].TopDownDist.ToString(); //textBox_xDist.Text = fpTool.fParam[SideId].roiP[id].xDist.ToString(); //comboBox_GetPtType.SelectedIndex = fpTool.fParam[SideId].roiP[id].SelectedType; RoiIsMoving = false; } catch (Exception) { RoiIsMoving = false; //Debug.WriteLine(richTextBox1.SelectedText); throw; } } ROI CopyTemp; ROI CopyTemp2; int CopyId = -1; int CurrentRowIndex = -1; private void 复制ToolStripMenuItem_Click(object sender, EventArgs e) { try { isGenSection = false; if (dataGridView1.CurrentCell == null) { return; } int Id = Convert.ToInt32(SideName.Substring(4, 1)) - 1; if (hwindow_final2.Image == null || !hwindow_final2.Image.IsInitialized()) { return; } int currentId = CurrentRowIndex; if (currentId < 0) { return; } HTuple coord1 = fpTool.roiList[Id][currentId].getModelData(); HTuple coord2 = fpTool.roiList2[Id][currentId].getModelData(); List<ROI> roiListTemp = new List<ROI>(); List<ROI> roiListTemp1 = new List<ROI>(); HWindow_Final tempWindow = new HWindow_Final(); tempWindow.viewWindow.genRect2(coord2[0].D + 45, coord2[1].D + 45, coord2[2].D, coord2[3].D, coord2[4].D, ref roiListTemp); CopyTemp2 = roiListTemp[0]; tempWindow.viewWindow.genRect1(coord1[0].D, coord1[1].D, coord1[2].D, coord1[3].D, ref roiListTemp1); CopyTemp = roiListTemp1[0]; CopyId = currentId; } catch (Exception) { throw; } } private void 粘贴ToolStripMenuItem_Click(object sender, EventArgs e) { try { isGenSection = false; if (CopyId == -1) { return; } RoiIsMoving = true; int Id = Convert.ToInt32(SideName.Substring(4, 1)) - 1; int currentId = dataGridView1.CurrentCell.RowIndex; currentId = CurrentRowIndex; //添加到当前Id之后 fpTool.roiList2[Id].Insert(currentId + 1, CopyTemp2); fpTool.roiList[Id].Insert(currentId + 1, CopyTemp); hwindow_final1.viewWindow.notDisplayRoi(); hwindow_final2.viewWindow.notDisplayRoi(); if (fpTool.roiList2[Id].Count > 0) { if (SelectAll) { //hwindow_final2.viewWindow.notDisplayRoi(); roiController2.viewController.ShowAllRoiModel = -1; hwindow_final2.viewWindow.displayROI(ref fpTool.roiList2[Id]); } else { roiController2.viewController.ShowAllRoiModel = currentId + 1; hwindow_final2.viewWindow.displayROI(ref fpTool.roiList2[Id]); roiController2.viewController.repaint(currentId + 1); } hwindow_final2.viewWindow.setActiveRoi(currentId + 1); } if (fpTool.roiList[Id].Count > 0) { temp.Clear(); ROI roi = fpTool.roiList[Id][CopyId + 1]; temp.Add(roi); hwindow_final1.viewWindow.notDisplayRoi(); hwindow_final1.viewWindow.displayROI(ref temp); } RoiParam RP = new RoiParam(); RP = fpTool.fParam[Id].roiP[CopyId].Clone(); //新位置的 HTuple NewCoord = CopyTemp2.getModelData(); RP.CenterRow = NewCoord[0]; RP.CenterCol = NewCoord[1]; fpTool.fParam[Id].roiP.Insert(currentId + 1, RP); fpTool.fParam[Id].roiP[currentId + 1].LineOrCircle = RP.LineOrCircle; //insert dataGridView1.Rows.Insert(currentId + 1); dataGridView1.Rows[currentId + 1].Cells[0].Value = currentId + 1; dataGridView1.Rows[currentId + 1].Cells[1].Value = "Default"; dataGridView1.Rows[currentId + 1].Cells[2].Value = fpTool.fParam[Id].roiP[currentId + 1].LineOrCircle; fpTool.fParam[Id].DicPointName.Insert(currentId + 1, "Default"); //排序 for (int i = 0; i < dataGridView1.Rows.Count; i++) { dataGridView1.Rows[i].Cells[0].Value = (i + 1); } dataGridView1.ClearSelection(); dataGridView1.Rows[currentId + 1].Selected = true; CurrentRowIndex = currentId + 1; RoiIsMoving = false; } catch (Exception) { throw; } } private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e) { try { if (isLoading) { return; } bool newID = dataGridView1.IsCurrentCellInEditMode; if (!newID) { return; } int Id = Convert.ToInt32(SideName.Substring(4, 1)) - 1; int currentId = CurrentRowIndex; if (currentId != -1) { if (dataGridView1.Rows[currentId].Cells[1] == null) { return; } string Value = dataGridView1.Rows[currentId].Cells[1].Value.ToString(); if (fpTool.fParam[Id].DicPointName.Contains(Value)) { MessageBox.Show("ID已存在"); dataGridView1.Rows[currentId].Cells[1].Value = "Default"; return; } fpTool.fParam[Id].DicPointName[currentId] = dataGridView1.Rows[currentId].Cells[1].Value.ToString(); } } catch (Exception) { throw; } } private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)//左右工位 { if (isLoading) { return; } if (comboBox3.SelectedItem.ToString() == "Right") { isRight = true; comboBox3.BackColor = Color.LimeGreen; } else { isRight = false; comboBox3.BackColor = Color.Yellow; } RoiParam.isInvoke = false; LoadToUI(); ChangeSide(); RoiParam.isInvoke = true; MessageBox.Show("切换成功!"); } private void simpleButton1_Click_1(object sender, EventArgs e)//添加 { try { if (cb_x1.SelectedItem!=null) { } } catch (Exception ex) { MessageBox.Show(ex.Message); } } } public class ParamPath { public static string ParaName = ""; public static bool IsRight = false; public static string ToolType = ""; public static string ParamDir { get { switch (ToolType) { case "Calib": if (IsRight) { return AppDomain.CurrentDomain.BaseDirectory + "Calib\\Right\\" + ParaName + "\\"; } else { return AppDomain.CurrentDomain.BaseDirectory + "Calib\\Left\\" + ParaName + "\\"; } case "GlueGuide": if (IsRight) { return MyGlobal.ConfigPath_Right + ParaName + "\\"; } else { return MyGlobal.ConfigPath_Left + ParaName + "\\"; } } return Application.StartupPath + "\\Config" + "\\" + ParaName + "\\"; } } public static string Path_Param { get { return ParamDir + "Fix.xml"; } } public static string Path_Setting { get { return ParamDir + "setting.xml"; } } public static string Path_roi { get { return ParamDir + "RoiLineCircle.roi"; } } public static string Path_tup { get { return ParamDir + "Calibrate" + ".tup"; } } public static string Path_CalibPix { get { return ParamDir + "CalibratePix" + ".txt"; } } public static void WriteTxt(string fileName, string value) { try { //string fileName = AppDomain.CurrentDomain.BaseDirectory + "data.txt"; using (FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write)) { using (StreamWriter sw = new StreamWriter(fs)) { sw.BaseStream.Seek(0, SeekOrigin.End); sw.WriteLine("{0}\n", value); sw.Flush(); sw.Close(); } } } catch (Exception) { throw; } } } [Serializable] public struct IntersetionCoord { public double Row; public double Col; public double Angle; } //[Serializable] //public class FitProfileParam //{ // /// <summary> // /// 选择最高点左侧 // /// </summary> // public bool BeLeft = false; // /// <summary> // /// 有效轮廓起始点 // /// </summary> // public int StartPt = 0; // /// <summary> // /// 有效轮廓结束点 // /// </summary> // public int EndPt = 0; // /// <summary> // /// 最高点下降距离 // /// </summary> // public double UpDownDist = 0; // /// <summary> // /// 单边高度偏移 // /// </summary> // public double SigleZoffset = 0; // /// <summary> // /// 最小区间高度 // /// </summary> // public double MinZ = 0; // /// <summary> // /// 最大区间高度 // /// </summary> // public double MaxZ = 0.5; // public List<RoiParam> roiP = new List<RoiParam>(); // public List<string> DicPointName = new List<string>(); // /// <summary> // /// 使用定位 // /// </summary> // public bool UseFix = false; //} [Serializable] public class RoiParam { public static bool isInvoke = false; public static event Action<ValueChangedType,double> ChangeSection; #region 锚定轮廓roi [BrowsableAttribute(false)] public double AnchorRow { get; set; } = 0; [BrowsableAttribute(false)] public double AnchorCol { get; set; } = 0; #endregion /// <summary> /// 选择直线段 还是圆弧段 连接段 /// </summary> [BrowsableAttribute(false)] public string LineOrCircle { get; set; } = "直线段"; #region 截面设置 [Category("\t\t\t\t截面设置")] [DisplayName("矩形区域截面数量")] [Description("截面数量")] public int NumOfSection { get { return _NumOfSection; } set { if (value==0) { value = 10; } _NumOfSection = value; if (isInvoke) { ChangeSection?.Invoke(ValueChangedType.数量,_NumOfSection); } } } int _NumOfSection = 10; [Category("\t\t\t\t截面设置")] [DisplayName("矩形长轴")] [Description("截面矩形长轴的一半 单位pix")] public double Len1 { get { return _Len1; } set { if (value == 0) { value = 100; } _Len1 = value; if (isInvoke) { ChangeSection?.Invoke(ValueChangedType.长度,_Len1); } } } double _Len1 = 0; [Category("\t\t\t\t截面设置")] [DisplayName("矩形短轴")] [Description("截面矩形短轴的一半 单位pix")] public double Len2 { get { return _Len2; } set { if (value == 0) { value = 50; } _Len2 = value; if (isInvoke) { ChangeSection?.Invoke(ValueChangedType.宽度,_Len2); } } } double _Len2 = 0; [Category("\t\t\t\t截面设置")] [DisplayName("矩形中心行坐标")] [Description("矩形中心行坐标 单位pix")] public double CenterRow { get { return _CenterRow; } set { if (value == 0) { value = 50; } _CenterRow = value; if (isInvoke) { ChangeSection?.Invoke(ValueChangedType.行坐标,_CenterRow); } } } double _CenterRow = 0; [Category("\t\t\t\t截面设置")] [DisplayName("矩形中心列坐标")] [Description("矩形中心列坐标 单位pix")] public double CenterCol { get { return _CenterCol; } set { if (value == 0) { value = 50; } _CenterCol = value; if (isInvoke) { ChangeSection?.Invoke(ValueChangedType.列坐标,_CenterCol); } } } double _CenterCol = 0; [BrowsableAttribute(false)] [Category("\t\t\t\t截面设置")] [DisplayName("矩形角度 phi")] [Description("矩形角度 弧度")] public double phi { get { //HTuple rad = new HTuple(); //HOperatorSet.TupleRad(_phi, out rad); return _phi; } set { HTuple deg = new HTuple(); HOperatorSet.TupleDeg(value, out deg); phi_deg = deg; //if (isInvoke) //{ // ChangeSection?.Invoke(ValueChangedType.角度); //} } } [Category("\t\t\t\t截面设置")] [DisplayName("矩形角度")] [Description("矩形角度 单位度")] public double phi_deg { get { return _Deg; } set { //HTuple deg = new HTuple(); //HOperatorSet.TupleDeg(value, out deg); HTuple rad = new HTuple(); HOperatorSet.TupleRad(value, out rad); _phi = rad; _Deg = value; if (isInvoke) { ChangeSection?.Invoke(ValueChangedType.角度,_phi); } } } double _phi = 0; double _Deg = 0; #endregion #region 拟合直线相对锚定点偏移 取胶槽 [BrowsableAttribute(false)] public double Xoffset2 { get; set; } = 0; [BrowsableAttribute(false)] public double Yoffset2 { get; set; } = 0; public Point StartOffSet1 = new Point(0, 0);//拟合直线相对锚定点偏移 public Point EndOffSet1 = new Point(0, 0); public Point StartOffSet2 = new Point(0, 0); public Point EndOffSet2 = new Point(0, 0); #endregion #region 偏移设置 [Category("\t\t偏移设置")] [DisplayName("X方向偏移")] [Description("X方向偏移 单位mm")] public double Xoffset { get { return _Xoffset; } set { _Xoffset = value; if (isInvoke) { ChangeSection?.Invoke(ValueChangedType.X方向偏移, _Xoffset); } } } double _Xoffset = 0; [Category("\t\t偏移设置")] [DisplayName("Y方向偏移")] [Description("Y方向偏移 单位mm")] public double Yoffset { get { return _Yoffset; } set { _Yoffset = value; if (isInvoke) { ChangeSection?.Invoke(ValueChangedType.Y方向偏移, _Yoffset); } } } double _Yoffset = 0; [Category("\t\t偏移设置")] [DisplayName("Roi方向偏移")] [Description("Roi方向偏移 单位mm")] public double offset { get { return _offset; } set { _offset = value; if (isInvoke) { ChangeSection?.Invoke(ValueChangedType.Roi方向偏移, _offset); } } } double _offset = 0; [Category("\t\t偏移设置")] [DisplayName("Z方向偏移")] [Description("Z方向偏移 单位mm")] public double Zoffset { get { return _Zoffset; } set { _Zoffset = value; if (isInvoke) { ChangeSection?.Invoke(ValueChangedType.Z方向偏移, _Zoffset); } } } double _Zoffset = 0; #endregion #region 轮廓设置 [Category("\t\t轮廓设置")] [DisplayName("轮廓旋转角度")] [Description("轮廓旋转角度设置 单位度")] public int AngleOfProfile { get { return _AngleOfProfile; } set { if (value >360) { value = 360; } if (value<-360) { value = -360; } _AngleOfProfile = value; if (isInvoke) { ChangeSection?.Invoke(ValueChangedType.轮廓旋转角度, _AngleOfProfile); } } } int _AngleOfProfile = 0; [Category("\t\t轮廓设置")] [DisplayName("轮廓平滑")] [Description("轮廓平滑系数 3-20 ")] public double Sigma { get { return _Sigma; } set { _Sigma = value; if (isInvoke) { ChangeSection?.Invoke(ValueChangedType.轮廓平滑, _Sigma); } } } double _Sigma = 0.5; #endregion #region 找线方式 [TypeConverter(typeof(FileNameConverter))] [Category("\t\t\t\t找线方式")] [DisplayName("\t找线方式设置")] [Description("找线方式设置 极值 或 最高点下降")] public string TypeOfFindLine { get { return _TypeOfFindLine; } set { _TypeOfFindLine = value; if (isInvoke) { double a = _TypeOfFindLine == "极值" ? 0 : 1; ChangeSection?.Invoke(ValueChangedType.找线方式设置, a); } } } string _TypeOfFindLine = "极值"; /// <summary> /// 0极值 1最高点下降 /// </summary> [BrowsableAttribute(false)] public int SelectedType { get { if (TypeOfFindLine == "极值") { return 0; } else { return 1; } } set { } } [Category("\t\t\t\t找线方式")] [DisplayName("最高点下降距离")] [Description("最高点下降距离 单位mm")] public double TopDownDist { get { return _TopDownDist; } set { if (value > 360) { value = 360; } if (value < -360) { value = -360; } _TopDownDist = value; if (isInvoke) { ChangeSection?.Invoke(ValueChangedType.最高点下降距离, _TopDownDist); } } } double _TopDownDist = 0; [Category("\t\t\t\t找线方式")] [DisplayName("水平方向距离")] [Description("离最高点或极值点的距离 单位mm")] public double xDist { get { return _xDist; } set { if (value > 360) { value = 360; } if (value < -360) { value = -360; } _xDist = value; if (isInvoke) { ChangeSection?.Invoke(ValueChangedType.X方向距离, _xDist); } } } double _xDist = 0; #endregion #region 取点方式设置 [Category("\t\t\t取点方式设置")] [DisplayName("是否取中间点")] [Description("对于长边可选择是否 取最外侧边缘和台阶边缘中间点,取中间点为true 否则为false")] public bool useMidPt { get { return _useMidPt; } set { _useMidPt = value; if (isInvoke) { double a = _useMidPt ? 1 : 0; ChangeSection?.Invoke(ValueChangedType.是否取中间点, a); } } } bool _useMidPt = false; [Category("\t\t\t取点方式设置")] [DisplayName("取轮廓区域中心点")] [Description("是否选择区域中心点,取中心点为true 否则为false")] public bool useCenter { get { return _useCenter; } set { _useCenter = value; if (isInvoke) { double a = _useCenter ? 1 : 0; ChangeSection?.Invoke(ValueChangedType.取轮廓区域中心点, a); } } } bool _useCenter = false; #endregion #region 点筛选 [Category("\t\t点筛选")] [DisplayName("是否取左侧值")] [Description("在最高点或极值点的左侧 为 true 否则为 false")] public bool useLeft { get { return _useLeft; } set { _useLeft = value; if (isInvoke) { double a = _useLeft ? 1 : 0; ChangeSection?.Invoke(ValueChangedType.是否取左侧值, a); } } } bool _useLeft = true; [Category("\t\t点筛选")] [DisplayName("取最近点还是最远点")] [Description("是否选择离最高点或极值点的最远距离的点,取最近点为true 否则为false")] public bool useNear { get { return _useNear; } set { _useNear = value; if (isInvoke) { double a = _useNear ? 1 : 0; ChangeSection?.Invoke(ValueChangedType.取最近点还是最远点, a); } } } bool _useNear = false; #endregion #region Z方向缩放设置 [Category("\tZ方向缩放设置")] [DisplayName("是否启用Z向缩放")] [Description("是否选择区域中心点,启用缩放为true 否则为false")] public bool useZzoom { get { return _useZzoom; } set { _useZzoom = value; if (isInvoke) { double a = _useZzoom ? 1 : 0; ChangeSection?.Invoke(ValueChangedType.是否启用Z向缩放, a); } } } bool _useZzoom = false; [Category("\tZ方向缩放设置")] [DisplayName("轮廓Z向拉伸")] [Description("轮廓沿Z向拉伸比列 单位为倍数")] public double ClippingPer { get { return _ClippingPer; } set { _ClippingPer = value; if (isInvoke) { ChangeSection?.Invoke(ValueChangedType.轮廓Z向拉伸, _ClippingPer); } } } double _ClippingPer = 0; #endregion #region 高度滤波设置 [Category("高度滤波设置")] [DisplayName("高度方向滤波最大百分比")] [Description("高度方向滤波最大百分比 范围设置0-100")] public double ZftMax { get { return _ZftMax; } set { if (value > 100) { value = 100; } if (value < 0) { value = 0; } _ZftMax = value; if (isInvoke) { ChangeSection?.Invoke(ValueChangedType.高度方向滤波最大百分比, _ZftMax); } } } double _ZftMax = 0; [Category("高度滤波设置")] [DisplayName("高度方向滤波最小百分比")] [Description("高度方向滤波最小百分比 范围设置0-100")] public double ZftMin { get { return _ZftMin; } set { if (value > 100) { value = 100; } if (value < 0) { value = 0; } _ZftMin = value; if (isInvoke) { ChangeSection?.Invoke(ValueChangedType.高度方向滤波最小百分比, _ZftMin); } } } double _ZftMin = 0; [Category("高度滤波设置")] [DisplayName("高度方向滤波半径")] [Description("高度方向滤波半径 单位mm")] public double ZftRad { get { return _ZftRad; } set { _ZftRad = value; if (isInvoke) { ChangeSection?.Invoke(ValueChangedType.高度方向滤波半径, _ZftRad); } } } double _ZftRad = 0; #endregion #region 直线拟合设置 [Category("\t直线拟合设置")] [DisplayName("直线滤波系数")] [Description("直线找点滤波系数 范围设置0-0.5")] public double SmoothCont { get { return _SmoothCont; } set { if (value < 0) { value = 0; } if (value > 0.5) { value = 0.5; } _SmoothCont = value; if (isInvoke) { ChangeSection?.Invoke(ValueChangedType.直线滤波系数, _SmoothCont); } } } double _SmoothCont = 0; #endregion public RoiParam Clone() { RoiParam temp = new RoiParam(); temp = (RoiParam)this.MemberwiseClone(); return temp; } public class FileNameConverter : StringConverter { public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { return new StandardValuesCollection(new string[] {"极值","最高点下降"}); } } } public enum ValueChangedType { 数量 = 1, 长度 = 2, 宽度 = 3, 角度 = 4, 行坐标 = 5, 列坐标 = 6, X方向偏移 =7, Y方向偏移 =8, Roi方向偏移 =9, Z方向偏移 = 10, 轮廓旋转角度 = 11, 最高点下降距离 =12, X方向距离 =13, 是否取左侧值 =14, 是否取中间点 =15, 取最近点还是最远点 =16, 取轮廓区域中心点 =17, 是否启用Z向缩放 =18, 轮廓Z向拉伸 =19, 轮廓平滑 =20, 直线滤波系数 =21, 高度方向滤波最大百分比 =22, 高度方向滤波最小百分比 =23, 高度方向滤波半径 =24, 找线方式设置 = 25 } [Serializable] public class FitProfileParam { #region 截面参数设置 #endregion /// <summary> /// 选择最高点左侧 /// </summary> public bool BeLeft = false; /// <summary> /// 有效轮廓起始点 /// </summary> public int StartPt = 0; /// <summary> /// 有效轮廓结束点 /// </summary> public int EndPt = 0; /// <summary> /// 最高点下降距离 /// </summary> public double UpDownDist = 0; /// <summary> /// 单边高度偏移 /// </summary> public double SigleZoffset = 0; /// <summary> /// 最小区间高度 /// </summary> public double MinZ = 0; /// <summary> /// 最大区间高度 /// </summary> public double MaxZ = 0.5; public List<RoiParam> roiP = new List<RoiParam>(); public List<string> DicPointName = new List<string>(); /// <summary> /// 使用定位 /// </summary> public bool UseFix = false; } }
using System.Collections.Generic; using System.IO; using System.Linq; using FluentAssertions; using Moq; using Xunit; using Xunit.Extensions; namespace NuCheck.Tests { public class PackagesAggregatorTest { public class Groups_All_Projects_By_Package_Id_And_Version { private const string solutionFile = @"C:\solution.sln"; private readonly PackagesAggregator sut; private Mock<IPackagesFileLoader> packagesFileLoaderMock; private Mock<IProjectExtractor> projectExtractorMock; public Groups_All_Projects_By_Package_Id_And_Version() { var projects = new[] { new Project("PROJ1", "project1.csproj"), new Project("PROJ2", "project2.csproj") }; string project1FileName = Path.Combine(Path.GetDirectoryName(solutionFile), projects[0].FileName); string project2FileName = Path.Combine(Path.GetDirectoryName(solutionFile), projects[1].FileName); var packagesOfProject1 = new[] { new Package("Package.P1", "1.0.0"), new Package("Package.P2", "1.0.0") }; var packagesOfProject2 = new[] { new Package("Package.P1", "1.0.0"), new Package("Package.P2", "1.1.0") }; projectExtractorMock = new Mock<IProjectExtractor>(); projectExtractorMock.Setup(m => m.ExtractAll(solutionFile)) .Returns(projects); packagesFileLoaderMock = new Mock<IPackagesFileLoader>(); packagesFileLoaderMock.Setup(m => m.Load(project1FileName)) .Returns(packagesOfProject1); packagesFileLoaderMock.Setup(m => m.Load(project2FileName)) .Returns(packagesOfProject2); sut = new PackagesAggregator(projectExtractorMock.Object, packagesFileLoaderMock.Object); } [Fact] public void Groups_All_Packages() { // Arrange var expected = new Dictionary<Package, IEnumerable<Project>> { { new Package("Package.P1", "1.0.0"), new[] { new Project("PROJ1", "project1.csproj"), new Project("PROJ2", "project2.csproj") } }, { new Package("Package.P2", "1.0.0"), new[] { new Project("PROJ1", "project1.csproj") } }, { new Package("Package.P2", "1.1.0"), new[] { new Project("PROJ2", "project2.csproj") } } }; // Act/Assert sut.Aggregate(solutionFile).ShouldBeEquivalentTo(expected); } [Theory] [InlineData("Package", null)] [InlineData("Package.P3", null)] [InlineData("Package.P1", new[] { "Package.P1" })] [InlineData("package.p1", new[] { "Package.P1" })] [InlineData("Package.P1*", new[] { "Package.P1" })] [InlineData("Package*", new[] { "Package.P1", "Package.P2" })] [InlineData("Package.P?", new[] { "Package.P1", "Package.P2" })] [InlineData("P*.P2", new[] { "Package.P2" })] public void Groups_Only_Packages_Whose_Ids_Match_The_Provided_Expression(string expression, string[] packageIds) { // Arrange var data = new Dictionary<Package, IEnumerable<Project>> { { new Package("Package.P1", "1.0.0"), new[] { new Project("PROJ1", "project1.csproj"), new Project("PROJ2", "project2.csproj") } }, { new Package("Package.P2", "1.0.0"), new[] { new Project("PROJ1", "project1.csproj") } }, { new Package("Package.P2", "1.1.0"), new[] { new Project("PROJ2", "project2.csproj") } } }; var expected = data.Where(a => packageIds != null && packageIds.Contains(a.Key.Id)); // Act/Assert sut.Aggregate(solutionFile, expression).ShouldBeEquivalentTo(expected); } } } }
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // using DotNetNuke.Entities.Modules; namespace DotNetNuke.Entities.Tabs { public interface ITabChangeTracker { /// <summary> /// Tracks a change when a module is added to a page /// </summary> /// <param name="module">Module which tracks the change</param> /// <param name="moduleVersion">Version number corresponding to the change</param> /// <param name="userId">User Id who provokes the change</param> void TrackModuleAddition(ModuleInfo module, int moduleVersion, int userId); /// <summary> /// Tracks a change when a module is modified on a page /// </summary> /// <param name="module">Module which tracks the change</param> /// <param name="moduleVersion">Version number corresponding to the change</param> /// <param name="userId">User Id who provokes the change</param> void TrackModuleModification(ModuleInfo module, int moduleVersion, int userId); /// <summary> /// Tracks a change when a module is deleted from a page /// </summary> /// <param name="module">Module which tracks the change</param> /// <param name="moduleVersion">Version number corresponding to the change</param> /// <param name="userId">User Id who provokes the change</param> void TrackModuleDeletion(ModuleInfo module, int moduleVersion, int userId); /// <summary> /// Tracks a change when a module is copied from an exisitng page /// </summary> /// <param name="module">Module which tracks the change</param> /// <param name="moduleVersion">Version number corresponding to the change</param> /// <param name="originalTabId">Tab Id where the module originally is</param> /// <param name="userId">User Id who provokes the change</param> void TrackModuleCopy(ModuleInfo module, int moduleVersion, int originalTabId, int userId); /// <summary> /// Tracks a change when a copied module is deleted from an exisitng page /// </summary> /// <param name="module">Module which tracks the change</param> /// <param name="moduleVersion">Version number corresponding to the change</param> /// <param name="originalTabId">Tab Id where the module originally is</param> /// <param name="userId">User Id who provokes the change</param> void TrackModuleUncopy(ModuleInfo module, int moduleVersion, int originalTabId, int userId); } }
using System; using System.ComponentModel.DataAnnotations.Schema; using System.Collections.Generic; using System.Text; namespace Hotel.Data.Models { public class RezervisanaUsluga { public int Id { set; get; } // jedna uslugahotela public int UslugeHotelaId { get; set; } [ForeignKey(nameof(UslugeHotelaId))] public virtual UslugeHotela UslugeHotela { get; set; } // jedancheckin public int CheckINId { get; set; } [ForeignKey(nameof(CheckINId))] public virtual CheckIN CheckIN { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace AsyncDelegates.Examples { public static class WaitForAsyncExample { public static void ShowWaitAsync() { Func<int, int, int> myDelegate = (x, y) => { Thread.Sleep(3000); return x + y; }; IAsyncResult asyncResult = myDelegate.BeginInvoke(1, 2, null, null); Console.WriteLine("Main thread is paused"); asyncResult.AsyncWaitHandle.WaitOne(); // Pause main thread Console.WriteLine("Main thread continued to work"); int result = myDelegate.EndInvoke(asyncResult); Console.WriteLine("\nResult: " + result); } public static void ShowIsComplited() { Func<int, int, int> myDelegate = (x, y) => { Thread.Sleep(3000); return x + y; }; IAsyncResult asyncResult = myDelegate.BeginInvoke(1, 2, null, null); // Loop will work till async task is finished while (!asyncResult.IsCompleted) { Thread.Sleep(100); Console.Write("*"); } int result = myDelegate.EndInvoke(asyncResult); Console.WriteLine("\nResult: " + result); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Text; using JsonFx.Json; using Midworld; partial class GoogleDrive { static T TryGet<T>(Dictionary<string, object> dict, string key) { object v; if (dict.TryGetValue(key, out v) && v is T) return (T)v; else return default(T); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using Bitcoin.BitcoinUtilities; using Bitcoin.Blox.Network; using Org.BouncyCastle.Math; using System.Threading.Tasks; namespace Bitcoin.Blox.Protocol_Messages { public class BlockMessage : Message { /// <summary> /// How many bytes are required to represent a block header. /// </summary> public const int HeaderSize = 80; private const uint _allowedTimeDrift = 2 * 60 * 60; // Same value as official client. // Fields defined as part of the protocol format. private uint _version; private Byte[] _prevBlockHash; private Byte[] _merkleRoot; private uint _time; private uint _difficultyTarget; // "nBits" private uint _nonce; /// <summary> /// If null, it means this object holds only the headers. /// </summary> internal IList<TransactionMessage> Transactions { get; private set; } /// <summary> /// Stores the hash of the block. If null, getHash() will recalculate it. /// </summary> [NonSerialized] private Byte[] _hash; /// <summary> /// Special case constructor, used for the genesis node, cloneAsHeader and unit tests. /// </summary> internal BlockMessage(P2PNetworkParameters netParams): base(netParams) { // Set up a few basic things. We are not complete after this though. _version = 1; _difficultyTarget = 0x1d07fff8; _time = (uint)P2PConnectionManager.GetUTCNowWithOffset(); _prevBlockHash = new byte[32]; } /// <summary> /// Constructs a block object from the BitCoin wire format. /// </summary> /// <exception cref="ProtocolException"/> public BlockMessage(byte[] payloadBytes, P2PNetworkParameters netParams): base(payloadBytes, 0, true,netParams) { } protected override void Parse() { _version = ReadUint32(); _prevBlockHash = ReadHash(); _merkleRoot = ReadHash(); _time = ReadUint32(); _difficultyTarget = ReadUint32(); _nonce = ReadUint32(); _hash = Utilities.ReverseBytes(Utilities.DoubleDigest(Bytes, 0, Cursor)); if (Cursor == Bytes.Length) { // This message is just a header, it has no transactions. return; } var numTransactions = (int)ReadVarInt(); Transactions = new List<TransactionMessage>(numTransactions); for (var i = 0; i < numTransactions; i++) { var tx = new TransactionMessage(Bytes, Cursor, P2PNetParameters); Transactions.Add(tx); Cursor += tx.MessageSize; } } private void WriteHeader(Stream stream) { Utilities.Uint32ToByteStreamLe(_version, stream); Byte[] writePrevBlockBytes = Utilities.ReverseBytes(_prevBlockHash); Byte[] writeMerkelRootBytes = Utilities.ReverseBytes(_merkleRoot); stream.Write(writePrevBlockBytes, 0, writePrevBlockBytes.Length); stream.Write(writeMerkelRootBytes ,0, writeMerkelRootBytes.Length); Utilities.Uint32ToByteStreamLe(_time, stream); Utilities.Uint32ToByteStreamLe(_difficultyTarget, stream); Utilities.Uint32ToByteStreamLe(_nonce, stream); } /// <exception cref="IOException"/> public override void BitcoinSerializeToStream(Stream stream) { WriteHeader(stream); // We may only have enough data to write the header. if (Transactions == null) return; stream.Write(new VarInt((ulong)Transactions.Count).Encode(),0, new VarInt((ulong)Transactions.Count).Encode().Length); foreach (var tx in Transactions) { tx.BitcoinSerializeToStream(stream); } } /// <summary> /// Calculates the block hash by serializing the block and hashing the resulting bytes. /// </summary> private Byte[] pCalculateHash() { using (var bos = new MemoryStream()) { WriteHeader(bos); return Utilities.ReverseBytes(Utilities.DoubleDigest(bos.ToArray())); } } /// <summary> /// Returns the hash of the block (which for a valid, solved block should be below the target) in the form seen /// on the block explorer. If you call this on block 0 in the production chain, you will get /// "00000000839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048". /// </summary> public string HashAsString { get { return Hash.ToString(); } } /// <summary> /// Returns the hash of the block (which for a valid, solved block should be below the target). Big endian. /// </summary> public Byte[] Hash { get { return _hash ?? (_hash = pCalculateHash()); } } /// <summary> /// The number that is one greater than the largest representable SHA-256 hash. /// </summary> private static readonly BigInteger _largestHash = BigInteger.One.ShiftLeft(256); /// <summary> /// Returns the work represented by this block. /// </summary> /// <remarks> /// Work is defined as the number of tries needed to solve a block in the average case. Consider a difficulty /// target that covers 5% of all possible hash values. Then the work of the block will be 20. As the target gets /// lower, the amount of work goes up. /// </remarks> /// <exception cref="VerificationException"/> public BigInteger GetWork() { var target = GetDifficultyTargetAsInteger(); return _largestHash.Divide(target.Add(BigInteger.One)); } /// <summary> /// Returns a copy of the block, but without any transactions. /// </summary> public BlockMessage CloneAsHeader() { var block = new BlockMessage(P2PNetParameters); block._nonce = _nonce; block._prevBlockHash = _prevBlockHash; block._merkleRoot = _merkleRoot; block._version = _version; block._time = _time; block._difficultyTarget = _difficultyTarget; block.Transactions = null; block._hash = _hash; return block; } /// <summary> /// Returns a multi-line string containing a description of the contents of the block. Use for debugging purposes /// only. /// </summary> public override string ToString() { var s = new StringBuilder(); s.AppendFormat("v{0} block:", _version).AppendLine(); s.AppendFormat(" previous block: {0}", _prevBlockHash).AppendLine(); s.AppendFormat(" merkle root: {0}", MerkleRoot).AppendLine(); s.AppendFormat(" time: [{0}] {1}", _time, new DateTime(_time * 1000)).AppendLine(); s.AppendFormat(" difficulty target (nBits): {0}", _difficultyTarget).AppendLine(); s.AppendFormat(" nonce: {0}", _nonce).AppendLine(); if (Transactions != null && Transactions.Count > 0) { s.AppendFormat(" with {0} transaction(s):", Transactions.Count).AppendLine(); foreach (var tx in Transactions) { s.Append(tx.ToString()); } } return s.ToString(); } /// <summary> /// Finds a value of nonce that makes the blocks hash lower than the difficulty target. This is called mining, /// but solve() is far too slow to do real mining with. It exists only for unit testing purposes and is not a part /// of the public API. /// </summary> /// <remarks> /// This can loop forever if a solution cannot be found solely by incrementing nonce. It doesn't change extraNonce. /// </remarks> internal void Solve() { while (true) { // Is our proof of work valid yet? if (pCheckProofOfWork()) return; // No, so increment the nonce and try again. _nonce++; } } /// <summary> /// Returns the difficulty target as a 256 bit value that can be compared to a SHA-256 hash. Inside a block the /// target is represented using a compact form. If this form decodes to a value that is out of bounds, /// an exception is thrown. /// </summary> /// <exception cref="VerificationException"/> public BigInteger GetDifficultyTargetAsInteger() { var target = Utilities.DecodeCompactBits(_difficultyTarget); if (target.CompareTo(BigInteger.Zero) <= 0 || target.CompareTo(P2PNetworkParameters.ProofOfWorkLimit) > 0) throw new Exception("Difficulty target is bad: " + target); return target; } /// <summary> /// Returns true if the hash of the block is OK (lower than difficulty target). /// </summary> /// <exception cref="VerificationException"/> private bool pCheckProofOfWork() { // This part is key - it is what proves the block was as difficult to make as it claims // to be. Note however that in the context of this function, the block can claim to be // as difficult as it wants to be .... if somebody was able to take control of our network // connection and fork us onto a different chain, they could send us valid blocks with // ridiculously easy difficulty and this function would accept them. // // To prevent this attack from being possible, elsewhere we check that the difficultyTarget // field is of the right value. This requires us to have the preceding blocks. var target = GetDifficultyTargetAsInteger(); var h = Utilities.NewPositiveBigInteger(Hash); if (h.CompareTo(target) > 0) { // Proof of work check failed! #if(DEBUG) Console.WriteLine("Hash is higher than target: " + HashAsString + " vs " + target.ToString(16)); #endif return false; } return true; } private bool pCheckTimestamp() { var currentTime = P2PConnectionManager.GetUTCNowWithOffset(); if (_time > currentTime + _allowedTimeDrift) { #if(DEBUG) Console.WriteLine("Block too far in future"); #endif return false; } return true; } private bool pCheckMerkleRoot() { var calculatedRoot = pCalculateMerkleRoot(); if (!calculatedRoot.Equals(_merkleRoot)) { #if (DEBUG) Console.WriteLine("Merkle hashes do not match: " + calculatedRoot + " vs " + _merkleRoot); ; #endif return false; } return true; } private Byte[] pCalculateMerkleRoot() { var tree = BuildMerkleTree(); return tree[tree.Count - 1]; } private IList<byte[]> BuildMerkleTree() { // The Merkle root is based on a tree of hashes calculated from the transactions: // // root // /\ // / \ // A B // / \ / \ // t1 t2 t3 t4 // // The tree is represented as a list: t1,t2,t3,t4,A,B,root where each entry is a hash. // // The hashing algorithm is double SHA-256. The leaves are a hash of the serialized contents of the // transaction. The interior nodes are hashes of the concentration of the two child hashes. // // This structure allows the creation of proof that a transaction was included into a block without having to // provide the full block contents. Instead, you can provide only a Merkle branch. For example to prove t2 was // in a block you can just provide t2, the hash(t1) and B. Now the other party has everything they need to // derive the root, which can be checked against the block header. // // Note that if the number of transactions is not even the last tx is repeated to make it so. A tree with 5 transactions would look like this: // // root // / \ // 1 \ // / \ \ // 2 3 4 // / \ / \ / \ // t1 t2 t3 t4 t5 t5 var tree = new List<byte[]>(); // Start by adding all the hashes of the transactions as leaves of the tree. foreach (var t in Transactions) { tree.Add(t.Hash); } var levelOffset = 0; // Offset in the list where the currently processed level starts. // Step through each level, stopping when we reach the root (levelSize == 1). for (var levelSize = Transactions.Count; levelSize > 1; levelSize = (levelSize + 1) / 2) { // For each pair of nodes on that level: for (var left = 0; left < levelSize; left += 2) { // The right hand node can be the same as the left hand, in the case where we don't have enough // transactions. var right = Math.Min(left + 1, levelSize - 1); var leftBytes = Utilities.ReverseBytes(tree[levelOffset + left]); var rightBytes = Utilities.ReverseBytes(tree[levelOffset + right]); tree.Add(Utilities.ReverseBytes(Utilities.DoubleDigestTwoBuffers(leftBytes, 0, 32, rightBytes, 0, 32))); } // Move to the next level. levelOffset += levelSize; } return tree; } private bool pCheckTransactions() { // The first transaction in a block must always be a coinbase transaction. if (!Transactions[0].IsCoinBase) { #if(DEBUG) Console.WriteLine("First tx is not coinbase"); #endif return false; } // The rest must not be. for (var i = 1; i < Transactions.Count; i++) { if (Transactions[i].IsCoinBase) { #if (DEBUG) Console.WriteLine("TX " + i + " is coinbase when it should not be."); #endif return false; } } return true; } /// <summary> /// Checks the block data to ensure it follows the rules laid out in the network parameters. Specifically, throws /// an exception if the proof of work is invalid, if the timestamp is too far from what it should be. This is /// <b>not</b> everything that is required for a block to be valid, only what is checkable independent of the /// chain and without a transaction index. /// </summary> private bool pVerifyHeader() { // Prove that this block is OK. It might seem that we can just ignore most of these checks given that the // network is also verifying the blocks, but we cannot as it'd open us to a variety of obscure attacks. // // Firstly we need to ensure this block does in fact represent real work done. If the difficulty is high // enough, it's probably been done by the network. if (pCheckProofOfWork()) { return pCheckTimestamp(); } else { #if(DEBUG) return false; #endif } } /// <summary> /// Checks the block contents /// </summary> private bool pVerifyTransactions() { // Now we need to check that the body of the block actually matches the headers. The network won't generate // an invalid block, but if we didn't validate this then an untrusted man-in-the-middle could obtain the next // valid block from the network and simply replace the transactions in it with their own fictional // transactions that reference spent or non-existant inputs. if (Transactions.Count > 0) { if (pCheckTransactions()) { return pCheckMerkleRoot(); } else { return false; } } return true; } /// <summary> /// Verifies both the header and that the transactions hash to the merkle root. /// </summary> public bool Verify() { if (pVerifyHeader()) { return pVerifyTransactions(); } else { return false; } } public override bool Equals(object o) { if (!(o is BlockMessage)) return false; var other = (BlockMessage)o; return Hash.Equals(other.Hash); } public override int GetHashCode() { return _hash != null ? _hash.Aggregate(1, (current, element) => 31 * current + element) : 0; } /// <summary> /// Returns the merkle root in big endian form, calculating it from transactions if necessary. /// </summary> public Byte[] MerkleRoot { get { return _merkleRoot ?? (_merkleRoot = pCalculateMerkleRoot()); } } /// <summary> /// Adds a transaction to this block. /// </summary> internal void AddTransaction(TransactionMessage t) { if (Transactions == null) { Transactions = new List<TransactionMessage>(); } Transactions.Add(t); // Force a recalculation next time the values are needed. _merkleRoot = null; _hash = null; } /// <summary> /// Returns the version of the block data structure as defined by the BitCoin protocol. /// </summary> public long Version { get { return _version; } } /// <summary> /// Returns the hash of the previous block in the chain, as defined by the block header. /// </summary> public Byte[] PrevBlockHash { get { return _prevBlockHash; } } /// <summary> /// Returns the time at which the block was solved and broadcast, according to the clock of the solving node. /// This is measured in seconds since the UNIX epoch (midnight Jan 1st 1970). /// </summary> public uint TimeSeconds { get { return _time; } } /// <summary> /// Returns the difficulty of the proof of work that this block should meet encoded in compact form. The /// <see cref="BlockChain"/> verifies that this is not too easy by looking at the length of the chain when the block is /// added. To find the actual value the hash should be compared against, use getDifficultyTargetBI. /// </summary> public uint DifficultyTarget { get { return _difficultyTarget; } } /// <summary> /// Returns the nonce, an arbitrary value that exists only to make the hash of the block header fall below the /// difficulty target. /// </summary> public uint Nonce { get { return _nonce; } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace OpenSSL_WinGui { public partial class mainForm : Form { private static List<String> sslData = new List<string>(); SetDefaultsForm setForm = new SetDefaultsForm(); public mainForm() { InitializeComponent(); } private void mainForm_Load(object sender, EventArgs e) { if (!System.IO.Directory.Exists(@"C:\Program Files (x86)\GnuWin32")) { //Later, ask the User if they installed OpenSSL to a different location and if they want to point OSWGUI at it //Also, if they ever do point it, save in OSWGUI config the new location for open ssl MessageBox.Show("OpenSSL not detected!\nPlease Reinstall OpenSSL"); Application.Exit(); } } /*C:\Program Files (x86)\GnuWin32\bin\openssl.exe genrsa -out "C:\Users\tjmapes\Desktop\root.key" 2048 (This works, will generate root.key at the specified location *for the beginning we will focus on 2048 bits and sha256 * also, add option to encrypt the private key with a password (-dex3 {passwordhere} */ private void quitToolStripMenuItem_Click(object sender, EventArgs e) { Application.Exit(); } private void aboutToolStripMenuItem1_Click(object sender, EventArgs e) { new AboutBox1().Show(); } private void setDefaultValuesToolStripMenuItem_Click(object sender, EventArgs e) { //this is where we will open either another form, or an alert box where we fill in the defaults for the certificates to be generated setForm = new SetDefaultsForm(); setForm.Show(); setForm.FormClosed += SetForm_FormClosed; /* * SetDefaultsForm.getEnteredDataFromTextBoxes() ? * */ } private void SetForm_FormClosed(object sender, FormClosedEventArgs e) { Properties.Settings.Default.Upgrade(); Properties.Settings.Default.Save(); sslData = setForm.sslData; if (Properties.Settings.Default.PropertyValues.Count == 0) { Properties.Settings.Default.EmailAddress = sslData[0]; Properties.Settings.Default.OrganizationalUnit = sslData[1]; Properties.Settings.Default.CompanyName = sslData[2]; Properties.Settings.Default.City = sslData[3]; Properties.Settings.Default.StateCode = sslData[4]; Properties.Settings.Default.CoutryCode = sslData[5]; } Properties.Settings.Default.Save(); Properties.Settings.Default.Reload(); } private void button1_Click(object sender, EventArgs e) { MessageBox.Show(Properties.Settings.Default.EmailAddress); } } }
using JKMServices.BLL; using Moq; using UnitTests.Mock; using Xunit; namespace UnitTests { /// <summary> /// Class Name : MoveDetailsTest /// Author : Ranjana Singh /// Creation Date : 27 Dec 2017 /// Purpose : Test cases for BLL Move Details methods. /// Revision : /// </summary> public class MoveDetailsTest { readonly MoveData moveData = new MoveData(); readonly Mock<JKMServices.DAL.CRM.IMoveDetails> mockCRMMoveDetails; readonly MoveDetails moveDetails; readonly Mock<JKMServices.DAL.CRM.ICustomerDetails> mockCRMCustomerDetails; public MoveDetailsTest() { //Arrange Mock<JKMServices.BLL.Interface.IResourceManagerFactory> mockBllJKMResource = new Mock<JKMServices.BLL.Interface.IResourceManagerFactory>(); mockCRMCustomerDetails = new Mock<JKMServices.DAL.CRM.ICustomerDetails>(); mockCRMMoveDetails = new Mock<JKMServices.DAL.CRM.IMoveDetails>(); Mock<Utility.Logger.ILogger> mockLogger = new Mock<Utility.Logger.ILogger>(); moveDetails = new MoveDetails( mockCRMCustomerDetails.Object, mockCRMMoveDetails.Object, mockBllJKMResource.Object, null, mockLogger.Object); } [Theory] [InlineData("JG1020")] //Testing with existing customerID public void GetMoveIdTest(string customerID) { //Arrange mockCRMMoveDetails.Setup(x => x.GetMoveId(It.IsAny<string>())).Returns(moveData.GetMoveIdDataPositive()); mockCRMCustomerDetails.Setup(x => x.CheckCustomerRegistered(It.IsAny<string>())).Returns(true); //Act moveDetails.GetMoveID(customerID); //Assert mockCRMMoveDetails.VerifyAll(); } /// <summary> /// Method Name : PutMoveData_Positive /// Author : Pratik Soni /// Creation Date : 16 Jan 2018 /// Purpose : Test case for BLL -> MoveDetails /// Revision : /// </summary> [Theory] [InlineData("RM0035661")] public void PutMoveData_Positive(string moveId) { //Moq DAL success response mockCRMMoveDetails.Setup(x => x.PutMoveData(It.IsAny<string>(), It.IsAny<string>())).Returns(moveData.GetMockMoveData_NoContentTest); //Act moveDetails.PutMoveData(moveId, moveData.MockedRequestBody_positive()); //Assert mockCRMMoveDetails.VerifyAll(); } /// <summary> /// Method Name : PutMoveData_Negative /// Author : Pratik Soni /// Creation Date : 16 Jan 2018 /// Purpose : Test case for BLL -> MoveDetails /// Revision : /// </summary> [Theory] [InlineData("RM0035661")] public void PutMoveData_Negative(string moveId) { //Moq DAL success response "1" mockCRMMoveDetails.Setup(x => x.PutMoveData(It.IsAny<string>(), It.IsAny<string>())).Returns(moveData.GetMockMoveData_NoContentTest); //Act moveDetails.PutMoveData(moveId, ""); //Assert mockCRMMoveDetails.VerifyAll(); } } }
using System; using Xunit; using System.Collections.Generic; using FizzBuzzTree; using Trees.Classes; namespace FizzBuzzTreeTDD { public class UnitTest1 { [Fact] public void FizzBuzz() { Node root = new Node(15); Node nodeTwo = new Node(3); Node nodeThree = new Node(4); Node nodeFour = new Node(5); BinaryTree fizzBuzz = new BinaryTree(root); fizzBuzz.Root.LeftChild = nodeTwo; fizzBuzz.Root.RightChild = nodeThree; fizzBuzz.Root.LeftChild.LeftChild = nodeFour; List<string> Fizz = new List<string>() { "FizzBuzz" }; Assert.Equal(Fizz, Program.TraversePreOrder(fizzBuzz.Root)); } [Fact] public void Buzz() { Node root = new Node(10); Node nodeTwo = new Node(15); Node nodeThree = new Node(4); Node nodeFour = new Node(5); BinaryTree fizzBuzz = new BinaryTree(root); fizzBuzz.Root.LeftChild = nodeTwo; fizzBuzz.Root.RightChild = nodeThree; fizzBuzz.Root.LeftChild.LeftChild = nodeFour; List<string> Buzz = new List<string>() { "Buzz" }; Assert.Equal(Buzz, Program.TraversePreOrder(fizzBuzz.Root)); } [Fact] public void Fizz() { Node root = new Node(9); Node nodeTwo = new Node(15); Node nodeThree = new Node(4); Node nodeFour = new Node(5); BinaryTree fizzBuzz = new BinaryTree(root); fizzBuzz.Root.LeftChild = nodeTwo; fizzBuzz.Root.RightChild = nodeThree; fizzBuzz.Root.LeftChild.LeftChild = nodeFour; List<string> Fizz = new List<string>() { "Fizz" }; Assert.Equal(Fizz, Program.TraversePreOrder(fizzBuzz.Root)); } [Fact] public void NoFizzOrBuzz() { Node root = new Node(2); Node nodeTwo = new Node(15); Node nodeThree = new Node(4); Node nodeFour = new Node(5); BinaryTree fizzBuzz = new BinaryTree(root); fizzBuzz.Root.LeftChild = nodeTwo; fizzBuzz.Root.RightChild = nodeThree; fizzBuzz.Root.LeftChild.LeftChild = nodeFour; List<string> value = new List<string>() { "2" }; Assert.Equal(value, Program.TraversePreOrder(fizzBuzz.Root)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using CmsShoppingCart.Models; using CmsShoppingCart.Models.ViewModels.Pages; using CmsShoppingCart.Models.Data; namespace CmsShoppingCart.Areas.Admin.Controllers { public class PagesController : Controller { // GET: Admin/Pages public ActionResult Index() { // Declare a list of PageVM List<PageVM> pagelist; // Init the list using (Db db = new Db()) { pagelist = db.Pages.ToList().OrderBy(p => p.Sorting).Select(p => new PageVM(p)).ToList(); } // return view with list return View(pagelist); } // GET: Admin/Pages/AddPage [HttpGet] public ActionResult AddPage() { return View(); } // Post: Admin/Pages/AddPage [HttpPost] public ActionResult AddPage(PageVM model) { // Check model state if (!ModelState.IsValid) { return View(model); } using (Db db = new Db()) { // Declare slug string slug; //init pageDto PageDto pageDto = new PageDto(); //pageDto title pageDto.Title = model.Title; //check if and set slug if need be if (string.IsNullOrWhiteSpace(model.Slug)) { slug = model.Title.Replace(" ", "-").ToLower(); } else { slug = model.Slug.Replace(" ", "-").ToLower(); } // Make sure title and slug are unique if (db.Pages.Any(x => x.Title == model.Title) || db.Pages.Any(x => x.Slug == model.Slug)) { ModelState.AddModelError("", "That Title or Slug already exists."); return View(model); } // pageDto the rest pageDto.Slug = model.Slug; pageDto.Body = model.Body; pageDto.HasSidebar = model.HasSidebar; pageDto.Sorting = 100; //save pageDto db.Pages.Add(pageDto); db.SaveChanges(); } //set TempData message TempData["SM"] = "You have added a new page!"; // Redirect return RedirectToAction("Index"); } // Get: Admin/Pages/EditPage/id [HttpGet] public ActionResult EditPage(int id) { // Declare pagevm PageVM model; //Get the Page using (Db db = new Db()) { PageDto pagedto = db.Pages.Find(id); //Confirm page exist if (pagedto == null) { return Content("The page does not exist"); } //Init pageVm model = new PageVM(pagedto); } //return the view model return View(model); } // Post: Admin/Pages/EditPage/id [HttpPost] public ActionResult EditPage(PageVM model) { // Check model state if (!ModelState.IsValid) { return View(model); } using (Db db = new Db()) { //Declare slug string slug; //Get the page PageDto pageDto = db.Pages.Find(model.Id); //check if and set slug if need be pageDto.Title = model.Title; if (model.Slug != "home") { if (string.IsNullOrWhiteSpace(model.Slug)) { slug = model.Title.Replace(" ", "-").ToLower(); } else { slug = model.Slug.Replace(" ", "-").ToLower(); } } // Make sure title and slug are unique if (db.Pages.Where(x => x.Id != model.Id).Any(x => x.Title == model.Title) || db.Pages.Where(x => x.Id != model.Id).Any(x => x.Slug == model.Slug)) { ModelState.AddModelError("", "That Title or Slug already exists."); return View(model); } // pageDto the rest pageDto.Slug = model.Slug; pageDto.Body = model.Body; pageDto.HasSidebar = model.HasSidebar; pageDto.Sorting = 100; //save pageDto db.SaveChanges(); } //set TempData message TempData["SM"] = "You have Edited a new page!"; // Redirect return RedirectToAction("Index"); } // Get: Admin/Pages/PageDetails/id public ActionResult PageDetails(int id) { //Declare PageVM PageVM page; using (Db db = new Db()) { PageDto pageDto; pageDto = db.Pages.Find(id); //confirm page exist if (pageDto == null) { return Content("the page does not exist."); } // init pagevm page = new PageVM(pageDto); } // return view with model return View(page); } // Get: Admin/Pages/DeletePage/id public ActionResult DeletePage(int id) { using (Db db = new Db()) { PageDto page = db.Pages.Find(id); db.Pages.Remove(page); db.SaveChanges(); } return RedirectToAction("Index"); } // Post: Admin/Pages/RecorderPages [HttpPost] public void RecorderPages(int[] id) { using (Db db = new Db()) { int count = 1; PageDto dto; foreach (var pageId in id) { dto = db.Pages.Find(pageId); dto.Sorting = count; db.SaveChanges(); count++; } } } // Get: Admin/Pages/EditSidebar [HttpGet] public ActionResult EditSidebar() { // Declare the model SidebarVM model; using (Db db = new Db()) { // get Dto SidebarDto dto = db.Sidebar.Find(1); //init the model model = new SidebarVM(dto); } // retutn view model return View(model); } [HttpPost] public ActionResult EditSidebar(SidebarVM model) { using (Db db = new Db()) { SidebarDto dto= db.Sidebar.Find(1); dto.Body = model.Body; db.SaveChanges(); } TempData["SM"] = "You have Edited a Sidebar!"; return RedirectToAction("Index"); } } }
using System.ComponentModel.Composition; using System.Linq; using System.Windows; using Microsoft.Practices.Prism.Regions; using Microsoft.Practices.Prism.ViewModel; using Torshify.Radio.Framework; using Torshify.Radio.Framework.Commands; namespace Torshify.Radio.Core.Views.Stations { [Export(typeof(StationsViewModel))] public class StationsViewModel : NotificationObject, INavigationAware { #region Fields private IRegionNavigationService _navigationService; #endregion Fields #region Constructors public StationsViewModel() { NavigateToTileCommand = new AutomaticCommand<Tile>(ExecuteNavigateToTile, CanExecuteNavigateToTile); } #endregion Constructors #region Properties public AutomaticCommand<Tile> NavigateToTileCommand { get; private set; } [Import] public ITileService TileService { get; set; } #endregion Properties #region Methods bool INavigationAware.IsNavigationTarget(NavigationContext navigationContext) { return true; } void INavigationAware.OnNavigatedFrom(NavigationContext navigationContext) { } void INavigationAware.OnNavigatedTo(NavigationContext navigationContext) { if (_navigationService != null) { _navigationService.Region.NavigationService.Navigated -= NavigationServiceOnNavigated; _navigationService.Region.NavigationService.Navigating -= NavigationServiceOnNavigating; } _navigationService = navigationContext.NavigationService; _navigationService.Region.NavigationService.Navigated += NavigationServiceOnNavigated; _navigationService.Region.NavigationService.Navigating += NavigationServiceOnNavigating; } private bool CanExecuteNavigateToTile(Tile tile) { return tile != null; } private void ExecuteNavigateToTile(Tile tile) { var regionManager = _navigationService.Region.RegionManager; if (regionManager.Regions.ContainsRegionWithName(tile.TargetRegionName)) { regionManager.RequestNavigate(tile.TargetRegionName, tile.NavigationUri); } } private void NavigationServiceOnNavigated(object sender, RegionNavigationEventArgs e) { var active = e.NavigationContext.NavigationService.Region.ActiveViews.FirstOrDefault() as FrameworkElement; if (active != null) { IRadioStation radioStation = active as IRadioStation; if (radioStation == null) { radioStation = active.DataContext as IRadioStation; } if (radioStation != null) { radioStation.OnTuneIn(e.NavigationContext); } } } private void NavigationServiceOnNavigating(object sender, RegionNavigationEventArgs e) { var active = e.NavigationContext.NavigationService.Region.ActiveViews.FirstOrDefault() as FrameworkElement; if (active != null) { IRadioStation radioStation = active as IRadioStation; if (radioStation == null) { radioStation = active.DataContext as IRadioStation; } if (radioStation != null) { radioStation.OnTuneAway(e.NavigationContext); } } } #endregion Methods } }
using Microsoft.IdentityModel.Tokens; namespace Dashboard.API.Application.Infrastructure.Identity { public interface IValidateAuthToken { TokenValidationParameters TokenValidationParameters { get; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace _01.SqareRoot { class SquareRoot { static void Main(string[] args) { /*Write a program that reads an integer number and calculates and prints its square root. If the number is invalid or negative, print "Invalid number". In all cases finally print "Good bye". Use try-catch-finally */ Console.Write("Enter a positive number: "); try { int number = int.Parse(Console.ReadLine()); if (number < 0) { throw new ArgumentOutOfRangeException("The number must be positive!"); } else { double sqRoot = Math.Sqrt(number); Console.WriteLine("Square root of {0} is {1}.", number, sqRoot); } } catch (ArgumentOutOfRangeException) { Console.WriteLine("Invalid number!"); } catch (FormatException) { Console.WriteLine("Invalid number!"); } catch (OverflowException) { Console.WriteLine("Invalid number!"); } finally { Console.WriteLine("Good Bye!!!"); } } } }
using NUnit.Framework; using System; namespace XamChat.Tests { public static class Test { public static void Setup () { ServiceContainer.Register<ISetting>(()=>new FakeSetting()); ServiceContainer.Register<IWebServices>(()=>new FakeService(){SleepDurtion = 0}); } } }
/* * Copyright 2014 Technische Universitšt Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using JetBrains.ReSharper.Psi; using JetBrains.ReSharper.Psi.CSharp.Tree; using JetBrains.ReSharper.Psi.Tree; using JetBrains.Util; using KaVE.Commons.Model.Naming; using KaVE.Commons.Model.Naming.Types; using KaVE.Commons.Model.SSTs.Expressions; using KaVE.Commons.Model.SSTs.Impl; using KaVE.Commons.Model.SSTs.Impl.Expressions.Assignable; using KaVE.Commons.Model.SSTs.Impl.Expressions.Simple; using KaVE.Commons.Model.SSTs.Impl.References; using KaVE.Commons.Model.SSTs.Impl.Statements; using KaVE.Commons.Model.SSTs.References; using KaVE.Commons.Model.SSTs.Statements; using KaVE.Commons.Utils.Assertion; using KaVE.RS.Commons.Analysis.CompletionTarget; using KaVE.RS.Commons.Analysis.Util; using KaVE.RS.Commons.Utils.Naming; using IBreakStatement = JetBrains.ReSharper.Psi.CSharp.Tree.IBreakStatement; using IContinueStatement = JetBrains.ReSharper.Psi.CSharp.Tree.IContinueStatement; using IExpressionStatement = JetBrains.ReSharper.Psi.CSharp.Tree.IExpressionStatement; using IReturnStatement = JetBrains.ReSharper.Psi.CSharp.Tree.IReturnStatement; using IStatement = KaVE.Commons.Model.SSTs.IStatement; using IThrowStatement = JetBrains.ReSharper.Psi.CSharp.Tree.IThrowStatement; namespace KaVE.RS.Commons.Analysis.Transformer.StatementVisitorParts { public partial class StatementVisitor : TreeNodeVisitor<IList<IStatement>> { private readonly CompletionTargetMarker _marker; private readonly ExpressionVisitor _exprVisitor; private readonly UniqueVariableNameGenerator _nameGen; private static ExpressionStatement EmptyCompletionExpression { get { return new ExpressionStatement {Expression = new CompletionExpression()}; } } public StatementVisitor(UniqueVariableNameGenerator nameGen, CompletionTargetMarker marker) { _marker = marker; _nameGen = nameGen; _exprVisitor = new ExpressionVisitor(_nameGen, marker); } public override void VisitNode(ITreeNode node, IList<IStatement> context) { node.Children<ICSharpTreeNode>().ForEach( child => { try { child.Accept(this, context); } catch (NullReferenceException) { } catch (AssertException) { } }); } #region statements public override void VisitBreakStatement(IBreakStatement stmt, IList<IStatement> body) { AddIf(stmt, CompletionCase.EmptyCompletionBefore, body); body.Add(new BreakStatement()); AddIf(stmt, CompletionCase.EmptyCompletionAfter, body); } public override void VisitLocalVariableDeclaration(ILocalVariableDeclaration decl, IList<IStatement> body) { if (IsTargetMatch(decl, CompletionCase.EmptyCompletionBefore)) { body.Add(EmptyCompletionExpression); } var id = decl.DeclaredName; ITypeName type; try { type = decl.Type.GetName(); } catch (AssertException) { // TODO this is an intermediate "fix"... the analysis sometimes fails here ("cannot create name for anonymous type") type = Names.UnknownType; } body.Add(SSTUtil.Declare(id, type)); IAssignableExpression initializer = null; if (decl.Initial != null) { initializer = _exprVisitor.ToAssignableExpr(decl.Initial, body); } else if (_marker.HandlingNode == decl && _marker.Case == CompletionCase.InBody) { initializer = new CompletionExpression(); } if (initializer != null) { if (!IsSelfAssign(id, initializer)) { body.Add(SSTUtil.AssignmentToLocal(id, initializer)); } } if (decl == _marker.HandlingNode && _marker.Case == CompletionCase.EmptyCompletionAfter) { body.Add(EmptyCompletionExpression); } } public override void VisitDeclarationStatement(IDeclarationStatement decl, IList<IStatement> body) { if (IsTargetMatch(decl, CompletionCase.EmptyCompletionBefore)) { body.Add(EmptyCompletionExpression); } VisitNode(decl.Declaration, body); if (decl == _marker.HandlingNode && _marker.Case == CompletionCase.EmptyCompletionAfter) { body.Add(EmptyCompletionExpression); } } public override void VisitLocalConstantDeclaration(ILocalConstantDeclaration decl, IList<IStatement> body) { if (IsTargetMatch(decl, CompletionCase.EmptyCompletionBefore)) { body.Add(EmptyCompletionExpression); } var id = decl.DeclaredName; ITypeName type; try { type = decl.Type.GetName(); } catch (AssertException) { // TODO this is an intermediate "fix"... the analysis sometimes fails here ("cannot create name for anonymous type") type = Names.UnknownType; } body.Add(SSTUtil.Declare(id, type)); IAssignableExpression initializer = null; if (decl.ValueExpression != null) { initializer = _exprVisitor.ToAssignableExpr(decl.ValueExpression, body); } else if (_marker.HandlingNode == decl && _marker.Case == CompletionCase.Undefined) { initializer = new CompletionExpression(); } if (initializer != null) { if (!IsSelfAssign(id, initializer)) { body.Add(SSTUtil.AssignmentToLocal(id, initializer)); } } if (decl == _marker.HandlingNode && _marker.Case == CompletionCase.EmptyCompletionAfter) { body.Add(EmptyCompletionExpression); } } private bool IsTargetMatch(ICSharpTreeNode o, CompletionCase completionCase) { var isValid = _marker.HandlingNode != null; var isMatch = o == _marker.HandlingNode; var isRightCase = _marker.Case == completionCase; return isValid && isMatch && isRightCase; } public override void VisitAssignmentExpression(IAssignmentExpression expr, IList<IStatement> body) { if (IsTargetMatch(expr, CompletionCase.EmptyCompletionBefore)) { body.Add(EmptyCompletionExpression); } var isTarget = IsTargetMatch(expr, CompletionCase.InBody); var sstRef = _exprVisitor.ToAssignableRef(expr.Dest, body) ?? new UnknownReference(); var sstExpr = isTarget ? new CompletionExpression() : _exprVisitor.ToAssignableExpr(expr.Source, body); var operation = TryGetEventSubscriptionOperation(expr); if (operation.HasValue) { body.Add( new EventSubscriptionStatement { Reference = sstRef, Operation = operation.Value, Expression = sstExpr }); } else { if (!IsSelfAssign(sstRef, sstExpr)) { body.Add( new Assignment { Reference = sstRef, Expression = IsFancyAssign(expr) ? new ComposedExpression() : sstExpr }); } } if (IsTargetMatch(expr, CompletionCase.EmptyCompletionAfter)) { body.Add(EmptyCompletionExpression); } } private static bool IsSelfAssign(string id, IAssignableExpression sstExpr) { return IsSelfAssign(new VariableReference {Identifier = id}, sstExpr); } private static bool IsSelfAssign(IAssignableReference sstRef, IAssignableExpression sstExpr) { // TODO add test! var refExpr = sstExpr as KaVE.Commons.Model.SSTs.Expressions.Simple.IReferenceExpression; return refExpr != null && sstRef.Equals(refExpr.Reference); } private static bool IsFancyAssign(IAssignmentExpression expr) { return expr.AssignmentType != AssignmentType.EQ; } private EventSubscriptionOperation? TryGetEventSubscriptionOperation(IAssignmentExpression expr) { var isRegularEq = expr.AssignmentType == AssignmentType.EQ; if (isRegularEq) { return null; } var refExpr = expr.Dest as IReferenceExpression; if (refExpr == null) { return null; } var elem = refExpr.Reference.Resolve().DeclaredElement; if (elem == null) { return null; } var loc = elem as ITypeOwner; if (loc != null) { var type = loc.Type.GetName(); if (!type.IsDelegateType) { return null; } } var isAdd = expr.AssignmentType == AssignmentType.PLUSEQ; if (isAdd) { return EventSubscriptionOperation.Add; } var isRemove = expr.AssignmentType == AssignmentType.MINUSEQ; if (isRemove) { return EventSubscriptionOperation.Remove; } return null; } /*private static AssignmentOperation ToOperation(AssignmentType assignmentType) { switch (assignmentType) { case AssignmentType.EQ: return AssignmentOperation.Equals; case AssignmentType.PLUSEQ: return AssignmentOperation.Add; case AssignmentType.MINUSEQ: return AssignmentOperation.Remove; default: return AssignmentOperation.Unknown; } }*/ public override void VisitExpressionStatement(IExpressionStatement stmt, IList<IStatement> body) { if (stmt.Expression != null) { var assignment = stmt.Expression as IAssignmentExpression; var prefix = stmt.Expression as IPrefixOperatorExpression; var postfix = stmt.Expression as IPostfixOperatorExpression; if (assignment != null) { assignment.Accept(this, body); } else if (prefix != null) { prefix.Accept(this, body); } else if (postfix != null) { postfix.Accept(this, body); } else { body.Add( new ExpressionStatement { Expression = stmt.Expression.Accept(_exprVisitor, body) ?? new UnknownExpression() }); if (IsTargetMatch(stmt.Expression, CompletionCase.EmptyCompletionAfter)) { body.Add( new ExpressionStatement { Expression = new CompletionExpression() }); } } } } public override void VisitPrefixOperatorExpression(IPrefixOperatorExpression expr, IList<IStatement> body) { if (IsTargetMatch(expr, CompletionCase.EmptyCompletionBefore)) { body.Add(EmptyCompletionExpression); } var varRef = _exprVisitor.ToVariableRef(expr.Operand, body); if (varRef.IsMissing) { body.Add(new UnknownStatement()); } else { body.Add( new Assignment { Reference = varRef, Expression = new ComposedExpression { References = {varRef} } }); } if (IsTargetMatch(expr, CompletionCase.EmptyCompletionAfter)) { body.Add(EmptyCompletionExpression); } } public override void VisitPostfixOperatorExpression(IPostfixOperatorExpression expr, IList<IStatement> body) { if (IsTargetMatch(expr, CompletionCase.EmptyCompletionBefore)) { body.Add(EmptyCompletionExpression); } var varRef = _exprVisitor.ToVariableRef(expr.Operand, body); if (varRef.IsMissing) { body.Add(new UnknownStatement()); } else { body.Add( new Assignment { Reference = varRef, Expression = new ComposedExpression { References = {varRef} } }); } if (IsTargetMatch(expr, CompletionCase.EmptyCompletionAfter)) { body.Add(EmptyCompletionExpression); } } public override void VisitReturnStatement(IReturnStatement stmt, IList<IStatement> body) { if (IsTargetMatch(stmt, CompletionCase.EmptyCompletionBefore)) { body.Add(EmptyCompletionExpression); } if (stmt.Value == null) { body.Add( new ReturnStatement { IsVoid = true }); } else { body.Add( new ReturnStatement { Expression = _exprVisitor.ToSimpleExpression(stmt.Value, body) ?? new UnknownExpression() }); } if (IsTargetMatch(stmt, CompletionCase.EmptyCompletionAfter)) { body.Add(EmptyCompletionExpression); } } public override void VisitThrowStatement(IThrowStatement stmt, IList<IStatement> body) { if (IsTargetMatch(stmt, CompletionCase.EmptyCompletionBefore)) { body.Add(EmptyCompletionExpression); } IVariableReference varRef = new VariableReference(); if (stmt.Semicolon == null && IsTargetMatch(stmt, CompletionCase.EmptyCompletionAfter)) { varRef = new VariableReference {Identifier = _nameGen.GetNextVariableName()}; body.Add( new VariableDeclaration { Type = Names.Type("System.Exception, mscorlib, 4.0.0.0"), Reference = varRef }); body.Add(new Assignment {Reference = varRef, Expression = new CompletionExpression()}); } else if (stmt.Exception != null) { varRef = _exprVisitor.ToVariableRef(stmt.Exception, body); } body.Add(new ThrowStatement {Reference = varRef}); if (IsTargetMatch(stmt, CompletionCase.EmptyCompletionAfter)) { body.Add(EmptyCompletionExpression); } } public override void VisitEmptyStatement(IEmptyStatement stmt, IList<IStatement> body) { if (stmt == _marker.HandlingNode) { body.Add(EmptyCompletionExpression); } } public override void VisitContinueStatement(IContinueStatement stmt, IList<IStatement> body) { if (IsTargetMatch(stmt, CompletionCase.EmptyCompletionBefore)) { body.Add(EmptyCompletionExpression); } body.Add(new ContinueStatement()); if (IsTargetMatch(stmt, CompletionCase.EmptyCompletionAfter)) { body.Add(EmptyCompletionExpression); } } #endregion #region blocks #endregion } }
using LogicBuilder.Attributes; using System; using System.Collections.Generic; using System.Linq; namespace Enrollment.Forms.Parameters.DataForm { public class FormGroupBoxSettingsParameters : FormItemSettingsParameters { public FormGroupBoxSettingsParameters ( [NameValue(AttributeNames.DEFAULTVALUE, "Header")] [Comments("Title for the group box.")] string groupHeader, [Comments("Configuration for each field in the group box.")] List<FormItemSettingsParameters> fieldSettings, [Comments("Multibindings list for the group header field - typically used in edit mode.")] MultiBindingParameters headerBindings = null, [Comments("Hide this group box.")] bool isHidden = false ) { if (fieldSettings.Any(s => s is FormGroupBoxSettingsParameters)) throw new ArgumentException($"{nameof(fieldSettings)}: D8590E1F-D029-405F-8E6C-EA98803004B8"); GroupHeader = groupHeader; FieldSettings = fieldSettings; HeaderBindings = headerBindings; IsHidden = isHidden; } public string GroupHeader { get; set; } public List<FormItemSettingsParameters> FieldSettings { get; set; } public MultiBindingParameters HeaderBindings { get; set; } public bool IsHidden { get; set; } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class _U : MonoBehaviour { public static _U Inst = null; private static _U _inst; private Dictionary<int, Canvas> _canvas; private Dictionary<string, _UP> _panels; private Transform _canvasRoot; public void Init() { if (Inst == null) Inst = this; // build canvas group GameObject cto = GameObject.Find("_Canvas"); _canvasRoot = cto.transform; GetCanvas(0); } private Canvas GetCanvas(int index) { if (_canvas == null) _canvas = new Dictionary<int, Canvas>(); if (_canvas.ContainsKey(index)) return _canvas[index]; GameObject co = new GameObject(index.ToString()); co.transform.SetParent(_canvasRoot); var result = co.AddComponent<Canvas>(); _canvas.Add(index, result); var rt = result.transform as RectTransform; rt.anchorMin = Vector2.zero; rt.anchorMax = Vector2.one; rt.pivot = Vector2.one * 0.5f; rt.anchoredPosition = Vector2.zero; rt.offsetMax = Vector2.zero; rt.offsetMin = Vector2.zero; result.sortingOrder = index; co.AddComponent<GraphicRaycaster>(); return result; } private void _ClosePanel(_UP panel) { string name = panel.Name; if (_panels == null) _panels = new Dictionary<string, _UP>(); if (!_panels.ContainsKey(name)) return; var panelInDic = _panels[name]; _panels.Remove(name); panelInDic.WhenDestroy(); Destroy(panelInDic.gameObject); } public static void ClosePanel(_UP panel) { Inst._ClosePanel(panel); } public void _ShowPanel(string panelName, int canvasIdx, _UC context) { if (_panels == null) _panels = new Dictionary<string, _UP>(); if (_panels.ContainsKey(panelName)) return; string path = "UI/" + panelName; var obj = _R.Load(path) as GameObject; var panelObj = Instantiate<GameObject>(obj); var rt = panelObj.transform as RectTransform; var position = rt.anchoredPosition; var offsetMax = rt.offsetMax; var offsetMin = rt.offsetMin; panelObj.transform.SetParent(GetCanvas(canvasIdx).transform); rt.anchoredPosition = position; rt.offsetMax = offsetMax; rt.offsetMin = offsetMin; var panel = panelObj.GetComponent<_UP>(); _panels.Add(panelName, panel); panel.context = context; panel.WhenFirstShow(); // TODO 这里给个动画 panel.WhenShow(); } public static void ShowPanel(string panelName, int canvasIdx, _UC context) { Inst._ShowPanel(panelName, canvasIdx, context); } }
using PlatformRacing3.Server.Game.Client; using PlatformRacing3.Server.Game.Communication.Messages.Incoming.Json; namespace PlatformRacing3.Server.Game.Communication.Messages; internal interface IMessageIncomingJson { void Handle(ClientSession session, JsonPacket message); }
using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GlobalDevelopment.SocialNetworks.Facebook.Models { public class FacebookWorkExperience { /// <summary> /// ID. /// </summary> public string ID { get; set; } /// <summary> /// Description. /// </summary> public string Description { get; set; } /// <summary> /// Employer. /// </summary> public FacebookPage Employer { get; set; } /// <summary> /// End date. /// </summary> public string EndDate { get; set; } /// <summary> /// Tagged by. /// </summary> public FacebookUser From { get; set; } /// <summary> /// Location /// </summary> public FacebookPage Location { get; set; } /// <summary> /// Position. /// </summary> public FacebookPage Position { get; set; } /// <summary> /// Projects. /// </summary> public List<FacebookProjectExperience> Projects { get; set; } /// <summary> /// Start date. /// </summary> public string StartDate { get; set; } /// <summary> /// Tagged Users. /// </summary> public List<FacebookUser> With { get; set; } public FacebookWorkExperience(JToken token) { JObject obj = JObject.Parse(token.ToString()); ID = (obj["id"] ?? "NA").ToString(); Description = (obj["description"] ?? "NA").ToString(); if (obj["employer"] != null) Employer = new FacebookPage(obj["employer"]); EndDate = (obj["end_date"] ?? "NA").ToString(); if (obj["from"] != null) From = new FacebookUser(obj["from"]); if (obj["location"] != null) Location = new FacebookPage(obj["location"]); if (obj["position"] != null) Position = new FacebookPage(obj["position"]); if (obj["projects"] != null) { Projects = new List<FacebookProjectExperience>(); foreach(var tk in obj["projects"]) { FacebookProjectExperience fpe = new FacebookProjectExperience(tk); Projects.Add(fpe); } } if (obj["with"] != null) { With = new List<FacebookUser>(); foreach (var tk in obj["with"]) { FacebookUser fu = new FacebookUser(tk); With.Add(fu); } } } } }
using System.Collections.Immutable; using System.Composition; using System.Globalization; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace Meziantou.Analyzer.Rules; [ExportCodeFixProvider(LanguageNames.CSharp), Shared] public sealed class AvoidComparisonWithBoolConstantFixer : CodeFixProvider { public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(RuleIdentifiers.AvoidComparisonWithBoolConstant); public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); var nodeToFix = root?.FindNode(context.Span, getInnermostNodeForTie: true); if (nodeToFix == null) return; var diagnostic = context.Diagnostics[0]; var title = "Remove comparison with bool constant"; var codeAction = CodeAction.Create( title, ct => RemoveComparisonWithBoolConstant(context.Document, diagnostic, nodeToFix, ct), equivalenceKey: title); context.RegisterCodeFix(codeAction, context.Diagnostics); } private static async Task<Document> RemoveComparisonWithBoolConstant(Document document, Diagnostic diagnostic, SyntaxNode nodeToFix, CancellationToken cancellationToken) { if (nodeToFix is not BinaryExpressionSyntax binaryExpressionSyntax) return document; if (binaryExpressionSyntax.Left is null || binaryExpressionSyntax.Right is null) return document; var nodeToKeepSpanStart = int.Parse(diagnostic.Properties["NodeToKeepSpanStart"]!, NumberStyles.Integer, CultureInfo.InvariantCulture); var nodeToKeepSpanLength = int.Parse(diagnostic.Properties["NodeToKeepSpanLength"]!, NumberStyles.Integer, CultureInfo.InvariantCulture); var logicalNotOperatorNeeded = bool.Parse(diagnostic.Properties["LogicalNotOperatorNeeded"]!); var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); if (syntaxRoot == null) return document; var nodeToKeep = syntaxRoot.FindNode(new TextSpan(nodeToKeepSpanStart, nodeToKeepSpanLength), getInnermostNodeForTie: true); if (nodeToKeep.Parent.IsKind(SyntaxKind.ParenthesizedExpression)) nodeToKeep = nodeToKeep.Parent; if (logicalNotOperatorNeeded) { nodeToKeep = PrefixUnaryExpression(SyntaxKind.LogicalNotExpression, (ExpressionSyntax)nodeToKeep); } var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); editor.ReplaceNode(nodeToFix, nodeToKeep.WithAdditionalAnnotations(Formatter.Annotation, Simplifier.Annotation)); return editor.GetChangedDocument(); } }
namespace _5.Phonebok { using System; using System.Collections.Generic; using System.Linq; public class Startup { public static void Main(string[] args) { string input = Console.ReadLine(); SortedDictionary<string, string> dict = new SortedDictionary<string, string>(); while (!input.Equals("search")) { var arguments = input.Trim() .Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries) .ToArray(); if (!dict.ContainsKey(arguments[0])) { dict.Add(arguments[0], arguments[1]); } else { dict[arguments[0]] = arguments[1]; } input = Console.ReadLine(); } while (!input.Equals("stop")) { if (dict.ContainsKey(input)) { Console.WriteLine($"{input} -> {dict[input]}"); } else { if (!input.Equals("search")) { Console.WriteLine($"Contact {input} does not exist."); } } input = Console.ReadLine(); } } } }
using System; using System.Collections.Generic; using System.Text; namespace PhonemesAndStuff { public abstract class AbstractPhoneme { public int ID { get; } public string Name { get; } public List<AbstractPhone> Allophones { get; } public AbstractPhoneme(PhonemeSupporter phonemeSupporter, List<AbstractPhone> listOfPhones) { ID = phonemeSupporter.ID; Name = phonemeSupporter.Name; Allophones = new List<AbstractPhone>(); if(phonemeSupporter.Allophones != null) { if (listOfPhones != null) { foreach (int allophoneIndex in phonemeSupporter.Allophones) { foreach (AbstractPhone phone in listOfPhones) { if (phone.ID == allophoneIndex) { Allophones.Add(phone); break; } } } } } } } }
using Microsoft.AspNetCore.Mvc; using NetCoreMvcExample.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace NetCoreMvcExample.Controllers { public class CharacterController : Controller { private ICharactersRepository _charactersRepository; public CharacterController(ICharactersRepository charactersRepository) { _charactersRepository = charactersRepository; } public IActionResult Index() { ViewData["Character"] = _charactersRepository.GetCharacters().FirstOrDefault(); return View(); } public async Task<IActionResult> GetSingle() { ViewData["Character"] = await _charactersRepository.GetSingleCharacter(); return View(); } } }
using PlatformRacing3.Server.API.Game.Commands; using PlatformRacing3.Server.Game.Client; using PlatformRacing3.Server.Game.Communication.Messages.Outgoing.Packets.Match; namespace PlatformRacing3.Server.Game.Commands.Match; internal sealed class TeleportToCommand : ICommand { private readonly CommandManager commandManager; public TeleportToCommand(CommandManager commandManager) { this.commandManager = commandManager; } public string Permission => "command.teleportto.use"; public void OnCommand(ICommandExecutor executor, string label, ReadOnlySpan<string> args) { if (args.Length is < 1 or > 2) { executor.SendMessage("Usage: /teleportto [target] <who>"); return; } using IEnumerator<ClientSession> targets = this.commandManager.GetTargets(executor, args[0]).GetEnumerator(); if (!targets.MoveNext()) { executor.SendMessage("Target not found"); return; } ClientSession target = targets.Current; if (targets.MoveNext()) { executor.SendMessage("No single target"); return; } if (target is not { MultiplayerMatchSession.MatchPlayer: { } targetMatchPlayer }) { executor.SendMessage("Target not in a match"); return; } IEnumerable<ClientSession> who; if (args.Length >= 2) { who = this.commandManager.GetTargets(executor, args[1]); } else if (executor is ClientSession session) { who = new ClientSession[] { session }; } else { executor.SendMessage("No who"); return; } double x = targetMatchPlayer.X; double y = targetMatchPlayer.Y; int i = 0; foreach (ClientSession whoSession in who) { if (whoSession is { MultiplayerMatchSession.MatchPlayer: { } matchPlayer } && matchPlayer.Match == targetMatchPlayer.Match) { i++; matchPlayer.X = x; matchPlayer.Y = y; if (matchPlayer.GetUpdatePacket(out UpdateOutgoingPacket packet)) { matchPlayer.Match.SendPacket(packet); } } } executor.SendMessage($"Effected {i} clients"); } }
/* * Bungie.Net API * * These endpoints constitute the functionality exposed by Bungie.net, both for more traditional website functionality and for connectivity to Bungie video games and their related functionality. * * OpenAPI spec version: 2.1.1 * Contact: support@bungie.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = BungieNetPlatform.Client.SwaggerDateConverter; namespace BungieNetPlatform.Model { /// <summary> /// TrendingTrendingDetail /// </summary> [DataContract] public partial class TrendingTrendingDetail : IEquatable<TrendingTrendingDetail>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="TrendingTrendingDetail" /> class. /// </summary> /// <param name="Identifier">Identifier.</param> /// <param name="EntityType">EntityType.</param> /// <param name="News">News.</param> /// <param name="Support">Support.</param> /// <param name="DestinyItem">DestinyItem.</param> /// <param name="DestinyActivity">DestinyActivity.</param> /// <param name="DestinyRitual">DestinyRitual.</param> /// <param name="Creation">Creation.</param> /// <param name="Stream">Stream.</param> public TrendingTrendingDetail(string Identifier = default(string), TrendingTrendingEntryType EntityType = default(TrendingTrendingEntryType), TrendingTrendingEntryNews News = default(TrendingTrendingEntryNews), TrendingTrendingEntrySupportArticle Support = default(TrendingTrendingEntrySupportArticle), TrendingTrendingEntryDestinyItem DestinyItem = default(TrendingTrendingEntryDestinyItem), TrendingTrendingEntryDestinyActivity DestinyActivity = default(TrendingTrendingEntryDestinyActivity), TrendingTrendingEntryDestinyRitual DestinyRitual = default(TrendingTrendingEntryDestinyRitual), TrendingTrendingEntryCommunityCreation Creation = default(TrendingTrendingEntryCommunityCreation), TrendingTrendingEntryCommunityStream Stream = default(TrendingTrendingEntryCommunityStream)) { this.Identifier = Identifier; this.EntityType = EntityType; this.News = News; this.Support = Support; this.DestinyItem = DestinyItem; this.DestinyActivity = DestinyActivity; this.DestinyRitual = DestinyRitual; this.Creation = Creation; this.Stream = Stream; } /// <summary> /// Gets or Sets Identifier /// </summary> [DataMember(Name="identifier", EmitDefaultValue=false)] public string Identifier { get; set; } /// <summary> /// Gets or Sets EntityType /// </summary> [DataMember(Name="entityType", EmitDefaultValue=false)] public TrendingTrendingEntryType EntityType { get; set; } /// <summary> /// Gets or Sets News /// </summary> [DataMember(Name="news", EmitDefaultValue=false)] public TrendingTrendingEntryNews News { get; set; } /// <summary> /// Gets or Sets Support /// </summary> [DataMember(Name="support", EmitDefaultValue=false)] public TrendingTrendingEntrySupportArticle Support { get; set; } /// <summary> /// Gets or Sets DestinyItem /// </summary> [DataMember(Name="destinyItem", EmitDefaultValue=false)] public TrendingTrendingEntryDestinyItem DestinyItem { get; set; } /// <summary> /// Gets or Sets DestinyActivity /// </summary> [DataMember(Name="destinyActivity", EmitDefaultValue=false)] public TrendingTrendingEntryDestinyActivity DestinyActivity { get; set; } /// <summary> /// Gets or Sets DestinyRitual /// </summary> [DataMember(Name="destinyRitual", EmitDefaultValue=false)] public TrendingTrendingEntryDestinyRitual DestinyRitual { get; set; } /// <summary> /// Gets or Sets Creation /// </summary> [DataMember(Name="creation", EmitDefaultValue=false)] public TrendingTrendingEntryCommunityCreation Creation { get; set; } /// <summary> /// Gets or Sets Stream /// </summary> [DataMember(Name="stream", EmitDefaultValue=false)] public TrendingTrendingEntryCommunityStream Stream { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class TrendingTrendingDetail {\n"); sb.Append(" Identifier: ").Append(Identifier).Append("\n"); sb.Append(" EntityType: ").Append(EntityType).Append("\n"); sb.Append(" News: ").Append(News).Append("\n"); sb.Append(" Support: ").Append(Support).Append("\n"); sb.Append(" DestinyItem: ").Append(DestinyItem).Append("\n"); sb.Append(" DestinyActivity: ").Append(DestinyActivity).Append("\n"); sb.Append(" DestinyRitual: ").Append(DestinyRitual).Append("\n"); sb.Append(" Creation: ").Append(Creation).Append("\n"); sb.Append(" Stream: ").Append(Stream).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as TrendingTrendingDetail); } /// <summary> /// Returns true if TrendingTrendingDetail instances are equal /// </summary> /// <param name="input">Instance of TrendingTrendingDetail to be compared</param> /// <returns>Boolean</returns> public bool Equals(TrendingTrendingDetail input) { if (input == null) return false; return ( this.Identifier == input.Identifier || (this.Identifier != null && this.Identifier.Equals(input.Identifier)) ) && ( this.EntityType == input.EntityType || (this.EntityType != null && this.EntityType.Equals(input.EntityType)) ) && ( this.News == input.News || (this.News != null && this.News.Equals(input.News)) ) && ( this.Support == input.Support || (this.Support != null && this.Support.Equals(input.Support)) ) && ( this.DestinyItem == input.DestinyItem || (this.DestinyItem != null && this.DestinyItem.Equals(input.DestinyItem)) ) && ( this.DestinyActivity == input.DestinyActivity || (this.DestinyActivity != null && this.DestinyActivity.Equals(input.DestinyActivity)) ) && ( this.DestinyRitual == input.DestinyRitual || (this.DestinyRitual != null && this.DestinyRitual.Equals(input.DestinyRitual)) ) && ( this.Creation == input.Creation || (this.Creation != null && this.Creation.Equals(input.Creation)) ) && ( this.Stream == input.Stream || (this.Stream != null && this.Stream.Equals(input.Stream)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Identifier != null) hashCode = hashCode * 59 + this.Identifier.GetHashCode(); if (this.EntityType != null) hashCode = hashCode * 59 + this.EntityType.GetHashCode(); if (this.News != null) hashCode = hashCode * 59 + this.News.GetHashCode(); if (this.Support != null) hashCode = hashCode * 59 + this.Support.GetHashCode(); if (this.DestinyItem != null) hashCode = hashCode * 59 + this.DestinyItem.GetHashCode(); if (this.DestinyActivity != null) hashCode = hashCode * 59 + this.DestinyActivity.GetHashCode(); if (this.DestinyRitual != null) hashCode = hashCode * 59 + this.DestinyRitual.GetHashCode(); if (this.Creation != null) hashCode = hashCode * 59 + this.Creation.GetHashCode(); if (this.Stream != null) hashCode = hashCode * 59 + this.Stream.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }