/// <summary> /// Missing mapping to P objects /// KdTree could be refactored to use P object instead of Math.Net /// /// O(k * log n) /// </summary> /// <param name="s"></param> /// <param name="origin"></param> /// <param name="k"></param> /// <param name="conf"></param> /// <returns></returns> public long UpdateKnn(IAlgorithm s, IP origin, KnnConfiguration conf) { if (conf == null) conf = new KnnConfiguration(); if (conf.SameTypeOnly) throw new NotImplementedException(); if (conf.MaxDistance.HasValue) throw new NotImplementedException(); var sw = new Stopwatch(); sw.Start(); var vector = new DenseVector(new[] { origin.X, origin.Y }); var nn = Tree.FindNearestNNeighbors(vector, conf.K).ToList(); s.Knn.Clear(); s.Knn.Origin = origin; s.Knn.K = conf.K; foreach (var i in nn) { var p = new P { X = i[0], Y = i[1] }; var dist = origin.Distance(p.X,p.Y); s.Knn.NNs.Add(new PDist {Point = p, Distance = dist}); } sw.Stop(); return sw.ElapsedMilliseconds; }
public void TestConstructor() { const string expected = "127.0.0.1"; IP ip = new IP(expected); Assert.AreEqual(expected, ip.ToString()); var test = new IP(IPAddress.Any.GetAddressBytes()); }
// Minkowski dist // if lat lon precise dist is needed, use Haversine or similar formulas // this is approx calc for clustering, no precise dist is needed public static double Distance(IP a, IP b) { // lat lon wrap, values don't seem needed to be normalized to [0;1] for better distance calc var absx = LatLonDiff(a.X, b.X); var absy = LatLonDiff(a.Y, b.Y); return Math.Pow(Math.Pow(absx, Exp) + Math.Pow(Math.Abs(absy), Exp), 1.0 / Exp); }
public void TestException() { var test = new IP(IPAddress.Any); Assert.Throws<ArgumentNullException>(() => test.AppendBytesTo(null)); Assert.Throws<ArgumentNullException>(() => new IP(new Tuple<int, byte[]>(0, new byte[] { 0 }), null)); Assert.Throws<ArgumentNullException>(() => new IP((IPAddress) null)); Assert.Throws<ArgumentException>(() => new IP(new Tuple<int, byte[]>(1, new byte[] { 1 }), new MemoryStream())); Assert.Throws<FormatException>(() => new IP("test")); }
public void display(ref IP.Core.IPCommon.IPConstants.HowUserWantTo_Exit_MainForm v_exitmode) { try { this.ShowDialog(); } catch (Exception v_e) { CSystemLog_301.ExceptionHandle(v_e); } }
public void TestEquals() { IP actual = new IP("172.0.0.1"); IP target = new IP("172.0.0.1"); IP another = new IP("172.0.0.0"); Assert.IsTrue(actual == target); Assert.AreEqual(actual, target); Assert.IsFalse(actual == another); Assert.AreNotEqual(actual, another); }
private void Go_Click(object sender, EventArgs e) { IPAddresses.Items.Clear(); try { IPAddress[] IPs = Dns.GetHostAddresses(host.Text); foreach (var IP in IPs) { IPAddresses.Items.Add(IP.ToString()); } } catch (Exception ex) { Log.wnmp_log_error(ex.Message, Log.LogSection.WNMP_MAIN); } }
private void HostToIpButton_Click(object sender, EventArgs e) { ipAddressesListBox.Items.Clear(); try { IPAddress[] IPs = Dns.GetHostAddresses(hostTextBox.Text); foreach (var IP in IPs) { ipAddressesListBox.Items.Add(IP.ToString()); } } catch (Exception ex) { Log.Error(ex.Message); } }
public byte[] GetBytes() { byte[] ip_bytes = IP.GetAddressBytes(); return(new byte[6] { ip_bytes[0], ip_bytes[1], ip_bytes[2], ip_bytes[3], (byte)((Port >> 8) & 0xFF), (byte)(Port & 0xFF) }); }
//---------------------------------------------------------------------- public IPAddress GetIPFromString(string strIP) { IPAddress ip = IPAddress.Parse("127.0.0.1"); try { ip = new IP(strIP).ToIPAddress(); } catch { } return(ip); }
/// <summary> /// Изменить IP-адрес. Метод написан с помощью Dapper. /// </summary> /// <param name="ip">IP-адрес с id адреса, который будет изменен и обновленными остальными полями.</param> public void UpdateIP(IP ip) { using (var db_connection = Connection) { var query = @" update dbo.IPs set address = @Address, mask = @Mask, subnet = @Subnet where PK_ip_id = @Id "; db_connection.Open(); db_connection.Query(query, ip); } }
private string get_ComputerIP() //현재 서버pc의 ip반환 { IPHostEntry computer = Dns.GetHostEntry(Dns.GetHostName()); foreach (IPAddress IP in computer.AddressList) { if (IP.AddressFamily == AddressFamily.InterNetwork) { return(IP.ToString()); } } return(null); }
private static string GetLocalIPAddress() { var host = Dns.GetHostEntry(Dns.GetHostName()); foreach (var IP in host.AddressList) { if (IP.AddressFamily == AddressFamily.InterNetwork) { return(IP.ToString()); } } throw new Exception("No valid network adapters in the system!"); }
// IsLinkLocalUnicast reports whether ip is a link-local // unicast address. public static bool IsLinkLocalUnicast(this IP ip) { { var ip4 = ip.To4(); if (ip4 != null) { return(ip4[0L] == 169L && ip4[1L] == 254L); } } return(len(ip) == IPv6len && ip[0L] == 0xfeUL && ip[1L] & 0xc0UL == 0x80UL); }
// IsLinkLocalMulticast reports whether ip is a link-local // multicast address. public static bool IsLinkLocalMulticast(this IP ip) { { var ip4 = ip.To4(); if (ip4 != null) { return(ip4[0L] == 224L && ip4[1L] == 0L && ip4[2L] == 0L); } } return(len(ip) == IPv6len && ip[0L] == 0xffUL && ip[1L] & 0x0fUL == 0x02UL); }
private static void SetIPv4() { foreach (IPAddress IP in Dns.GetHostAddresses(Dns.GetHostName())) { if (IP.AddressFamily == AddressFamily.InterNetwork) { LocalIPv4 = IP.ToString(); //this sectoin is only meant for LessConnect Specific Applications //TDOD Add if statement to declare a break on the form } } }
private static IPAddress GetLocalIPAddress() { var lHost = Dns.GetHostEntry(Dns.GetHostName()); foreach (var IP in lHost.AddressList) { if (IP.AddressFamily == AddressFamily.InterNetwork) { return(IPAddress.Parse(IP.ToString())); } } throw new Exception("No network adapters with an IPv4 address in the system!"); }
public override int GetHashCode() { unchecked { return(base.GetHashCode() + (Hostname.ToUpper().GetHashCode() * 3) + (IP.ToUpper().GetHashCode() * 3) + (ConnectionsAllowed.GetHashCode() * 3) + (MaximumConnections.GetHashCode() * 3) + (Name.ToUpper().GetHashCode() * 3) + (Location.ToUpper().GetHashCode() * 3) * 17); } }
// IsLoopback reports whether ip is a loopback address. public static bool IsLoopback(this IP ip) { { var ip4 = ip.To4(); if (ip4 != null) { return(ip4[0L] == 127L); } } return(ip.Equal(IPv6loopback)); }
public override int GetHashCode() { return ((SSID != null ? SSID.GetHashCode() : 0) + (Password != null ? Password.GetHashCode() : 0) + (BSSID != null ? BSSID.GetHashCode() : 0) + (Channel != null ? Channel.GetHashCode() : 0) + (IP != null ? IP.GetHashCode() : 0) + (Mask != null ? Mask.GetHashCode() : 0) + (GW != null ? GW.GetHashCode() : 0) + (DNS1 != null ? DNS1.GetHashCode() : 0) + (DNS2 != null ? DNS2.GetHashCode() : 0)); }
public void ConnectToServer() { try { _clientSocket.Connect(_ipe); Console.WriteLine("Connected to {0} @ Port:{1}.", IP.ToString(), Port.ToString()); } catch (SocketException e) { Console.WriteLine("Failed to Connect Server -{0}", e.ToString()); return; } }
// IsMulticast reports whether ip is a multicast address. public static bool IsMulticast(this IP ip) { { var ip4 = ip.To4(); if (ip4 != null) { return(ip4[0L] & 0xf0UL == 0xe0UL); } } return(len(ip) == IPv6len && ip[0L] == 0xffUL); }
private void SetTitle() { string title = Program.PROGRAMM_NAME; IPEndPoint ep = IP.QueryRoutingInterface(IPAddress.Broadcast); if (ep.Address != null) { title += " [" + ep.Address.ToString() + "]"; } this.mainWindow.Title = title; }
protected bool CheckInsertGameLog(string IDNo, string Ball) { if (CheckTimeout.IsEbankEnd()) { return(true); } else { string IP; IP = "[" + Request.ServerVariables["REMOTE_ADDR"] + "]"; if (Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != "") { IP += "[" + Request.ServerVariables["HTTP_X_FORWARDED_FOR"] + "]"; } ConnectionStringSettings connSettings = ConfigurationManager.ConnectionStrings["ConnString"]; SqlConnection conn = new SqlConnection(connSettings.ConnectionString); conn.Open(); SqlCommand cmd = new SqlCommand("usp_InsertMember", conn); cmd.CommandType = CommandType.StoredProcedure; SqlParameter parm_IDNo = new SqlParameter("@ID", SqlDbType.VarChar, 50); SqlParameter parm_Times = new SqlParameter("@Times", SqlDbType.Int); SqlParameter parm_IP = new SqlParameter("@IP", SqlDbType.VarChar, 40); parm_IDNo.Value = IDNo; parm_Times.Value = Int16.Parse(Ball); parm_IP.Value = IP.Replace("[]", ""); cmd.Parameters.Add(parm_IDNo); cmd.Parameters.Add(parm_Times); cmd.Parameters.Add(parm_IP); //Response.Write("ID=" + IDNo + "<BR>"); //Response.Write("Ball=" + Int16.Parse(Ball).ToString() + "<BR>"); //Response.Write("IP=" + IP + "<BR>"); string ReturnValue = cmd.ExecuteScalar().ToString(); //Response.Write("ReturnValue=" + ReturnValue + "<BR>"); cmd.Dispose(); conn.Close(); conn.Dispose(); if (ReturnValue == "y") { return(true); } else { return(false); } } }
private void BtSave_Click(object sender, EventArgs e) { if (!Valid()) { return; } if (string.IsNullOrEmpty(txtName.Text)) { MessageBox.Show("请为保存的配置信息取名"); txtName.Focus(); return; } #region 修改xml IP obj = null;//是否已经是现有的配置名称,是的话更新现有信息,否的话新增节点 if (tvIP.SelectedNode != null && tvIP.SelectedNode.Text != txtName.Text) { DialogResult ds = MessageBox.Show("选择是则修改所选配置为新名称,选择否则保留旧配置新增配置", "修改选择的配置信息", MessageBoxButtons.YesNo); if (ds == DialogResult.Yes) { obj = tvIP.SelectedNode.Tag as IP; GetText(obj, txtName.Text); xmlHelper.UpdateNode("IP", tvIP.SelectedNode.Text, obj); tvIP.SelectedNode.Text = obj.Name; } } else { TreeNode[] nodes = tvIP.Nodes.Find(txtName.Text, false); if (nodes.Length > 0) { obj = nodes[0].Tag as IP; GetText(obj); xmlHelper.UpdateNode("IP", obj.Name, obj); } } if (obj == null) { obj = new IP(); GetText(obj, txtName.Text); tvIP.Nodes.Add(new TreeNode { Text = obj.Name, Tag = obj }); xmlHelper.AppendNode(obj, "IP"); } #endregion RefreshTree(); if (cbTogether.Checked) { BtApply_Click(null, null); } }
private void SubnetIn_LostFocus(object sender, RoutedEventArgs e) { IP tmpIP; if (IP.TryParse(SubnetIn.Text, out tmpIP)) { a.SubnetMask = tmpIP; parent.UpdateView(); } else { SubnetIn.Text = "Invalid IP: " + SubnetIn.Text; } }
private void LocalIPIn_LostFocus(object sender, RoutedEventArgs e) { IP tmpIP; if (IP.TryParse(LocalIPIn.Text, out tmpIP)) { a.LocalIP = tmpIP; parent.UpdateView(); } else { LocalIPIn.Text = "Invalid IP: " + LocalIPIn.Text; } }
public override int GetHashCode() { unchecked { var hash = 0; hash = (hash * 397) ^ IP.GetHashCode(); hash = (hash * 397) ^ User.GetHashCode(); hash = (hash * 397) ^ Password.GetHashCode(); hash = (hash * 397) ^ Database.GetHashCode(); hash = (hash * 397) ^ DSN.GetHashCode(); hash = (hash * 397) ^ Driver.GetHashCode(); return(hash); } }
public void UP_IP_Poste() { OrdemDeServico OS = unitOfWork.OrdemDeServicoRepository.Get(os => os.NumeroOS == NUMOS).FirstOrDefault(); Assert.IsNotNull(OS); Poste poste = unitOfWork.PosteRepository.Get(p => p.OrdemDeServico.IdOrdemDeServico == OS.IdOrdemDeServico).FirstOrDefault(); Assert.IsNotNull(poste); IP ip = unitOfWork.IPRepository.Get(i => i.Poste.IdPoste == poste.IdPoste, includeProperties: "Poste").FirstOrDefault(); Assert.IsNotNull(ip); }
private void DefaultGatewayIn_LostFocus(object sender, RoutedEventArgs e) { IP tmpIP; if (IP.TryParse(DefaultGatewayIn.Text, out tmpIP)) { a.DefaultGateway = tmpIP; parent.UpdateView(); } else { DefaultGatewayIn.Text = "Invalid IP: " + DefaultGatewayIn.Text; } }
/// <summary> /// Important call the init method first / issuer must need to know the attributes /// </summary> /// <returns>Returns a JsonString with the IssuerParameters, could be shared with prover and verifier</returns> public string GetIssuerParameters() { if (ikap == null) { throw new CommunicationException("IssuingIssuer - Issuer must first be initialized. Call init method first"); } IP ip = parser.ParseJsonToObject <IP>(ikap.IssuerParameters.Serialize()); string expected = ikap.IssuerParameters.Serialize(); string result = parser.ParseObjectToJson(ip); return(parser.ParseObjectToJson(ip)); }
public HConnection(string Host, int Port) { DisposeLock = new object(); ResetHostLock = new object(); DisconnectLock = new object(); SendToClientLock = new object(); SendToServerLock = new object(); this.Host = Host; this.Port = Port; ResetHost(); Addresses = Dns.GetHostAddresses(Host).Select(IP => IP.ToString()).ToArray(); }
public void Equals1() { MAC mac = MAC.Parse("FF:FF:FF:FF:FF:FF"); string name = "Adapter 1"; IP localip = IP.Parse("192.168.1.2"); IP Subnet = IP.Parse("255.255.255.0"); IP DefaultG = IP.Parse("192.168.1.1"); IP DNS = IP.Parse("1.1.1.1"); Adapter a = new Adapter(mac, 1, name, localip, Subnet, DefaultG, DNS, 1, true); Assert.True(a.Equals(a)); }
public override string ToString() { string msg; if (IP == null) { msg = TypeName + ": " + ID; } else { msg = TypeName + ": " + ID + ", IP: " + IP.ToString(); } return(msg); }
public override int GetHashCode() { unchecked { var hashCode = Num; hashCode = (hashCode * 397) ^ (IP?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ Port; hashCode = (hashCode * 397) ^ Ping; hashCode = (hashCode * 397) ^ (Guid?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (Name?.GetHashCode() ?? 0); hashCode = (hashCode * 397) ^ (int)State; return(hashCode); } }
private HtmlDocument RequestHtmlDoc(string URl) { var num = 0; while (true) { try { RequestType Type; if (CurrentIP != null && "HTTPS" == CurrentIP.Type) { Type = RequestType.HTTPS; } else { Type = RequestType.HTTP; } string UserAgent = "Mozilla / 5.0(Windows NT 10.0; Win64; x64) AppleWebKit / 537.36(KHTML, like Gecko) Chrome / 71.0.3578.98 Safari / 537.36"; if (UseAgent == 1 && CurrentIP == null) { return(RequestHelper <HtmlDocument> .DoRequest(URl, null, false, "", "", UserAgent, string.Empty, Method.Get, null)); } else { return(RequestHelper <HtmlDocument> .DoRequest(URl, null, true, CurrentIP.IPAddress, CurrentIP.Port, UserAgent, string.Empty, Method.Get, null)); } } catch (Exception ex) { if (CurrentIP != null) { if (num <= 50) { _agentIPService.DeleteNotUseAgentIP(CurrentIP.ID); SetProxy(); } else if (num == 51) { CurrentWebProxy = null; CurrentIP = null; } else { throw new Exception("连接失败"); } num++; } } } }
public void TestEquals() { IP actual = new IP("172.0.0.1"); IP target = new IP("172.0.0.1"); IP another = new IP("172.0.0.0"); Assert.IsTrue(actual.Equals(target)); Assert.IsTrue(actual == target); // ReSharper disable EqualExpressionComparison Assert.IsTrue(actual == actual); // ReSharper restore EqualExpressionComparison Assert.AreEqual(actual, target); Assert.IsFalse(actual == another); Assert.IsTrue(actual != another); Assert.AreNotEqual(actual, another); }
// O(n * m) where m is grid cells public long UpdateKnn(IAlgorithm s, IP p, KnnConfiguration conf) { if (conf == null) conf = new KnnConfiguration(); var sw = new Stopwatch(); sw.Start(); var max = Math.Max(s.Rectangle.XGrid, s.Rectangle.YGrid); s.Knn.Clear(); s.Knn.Origin = p; s.Knn.K = conf.K; UpdateKnnGridStrategy(s, max, conf); sw.Stop(); return sw.ElapsedMilliseconds; }
public void BuildContent(IP p) { if(p==null) return; Id = p.I.ToString(); Type = p.T; Lat = p.Lat; Lon = p.Lon; var sb = new StringBuilder(); sb.AppendLine("<div>"); sb.AppendFormat("Time: {0}<br/>",DateTime.Now); sb.AppendFormat("Id: {0}<br /> Type: {1}<br />", Id, Type); sb.AppendFormat("Lat: {0} Lon: {1}", p.Lat, p.Lon); sb.AppendLine("</div>"); Content = sb.ToString(); }
static SolidColorBrush GetColor(IP p, ShapeType st = ShapeType.Default) { switch (st) { case ShapeType.Single: return Pens.DotColorSingle; case ShapeType.NearestNeighbor: if (p.Type == 1) return Pens.DotColorType1; if (p.Type == 2) return Pens.DotColorType2; if (p.Type == 3) return Pens.DotColorType3; return Pens.DotColorNearestNeighbor; case ShapeType.Selected: return Pens.DotColorSelected; case ShapeType.Default: default: if (p.Type == 1) return Pens.DotColorType1; if (p.Type == 2) return Pens.DotColorType2; if (p.Type == 3) return Pens.DotColorType3; return Pens.DotColor; // default } }
/// <summary> /// Creates a <see cref="TrapV1Pdu"/> instance with PDU elements. /// </summary> /// <param name="enterprise">Enterprise</param> /// <param name="agent">Agent address</param> /// <param name="generic">Generic trap type</param> /// <param name="specific">Specific trap type</param> /// <param name="timestamp">Time stamp</param> /// <param name="variables">Variable binds</param> public TrapV1Pdu(ObjectIdentifier enterprise, IP agent, Integer32 generic, Integer32 specific, TimeTicks timestamp, IList<Variable> variables) { if (enterprise == null) { throw new ArgumentNullException("enterprise"); } if (agent == null) { throw new ArgumentNullException("agent"); } if (generic == null) { throw new ArgumentNullException("generic"); } if (specific == null) { throw new ArgumentNullException("specific"); } if (timestamp == null) { throw new ArgumentNullException("timestamp"); } if (variables == null) { throw new ArgumentNullException("variables"); } Enterprise = enterprise; AgentAddress = agent; _generic = generic; _specific = specific; TimeStamp = timestamp; _varbindSection = Variable.Transform(variables); Variables = variables; }
/// <summary> /// O(n * k * logk) // much faster than O(n logn) for k << n /// </summary> /// <param name="s"></param> /// <param name="p"></param> /// <param name="conf"></param> /// <returns></returns> public override long UpdateKnn(IAlgorithm s, IP p, KnnConfiguration conf) { if (conf == null) conf = new KnnConfiguration(); var sw = new Stopwatch(); sw.Start(); s.Knn.Clear(); s.Knn.Origin = p; s.Knn.K = conf.K; //var all = new List<IPDist>(); var sortedList2 = new SortedList2(); var n = s.Points.Count; for (var i = 0; i < n; i++) { var p1 = s.Points[i]; if (p.Equals(p1)) continue; // don't include origin if (conf.SameTypeOnly && p.Type != p1.Type) continue; // only same type used var dist = p.Distance(p1.X, p1.Y); if (dist >= conf.MaxDistance) continue; var pdist = new PDist { Point = p1, Distance = dist }; //all.Add(pdist); sortedList2.Add(pdist, conf.K); } //s.Knn.NNs = all.OrderBy(i => i.Distance).Take(conf.K).ToList(); // O(n logn) s.Knn.NNs = sortedList2.GetAll(); // O(n * k * logk) sw.Stop(); return sw.ElapsedMilliseconds; }
public long UpdateKnn(IP p, KnnConfiguration configuration) { UpdateIndex(p); return Strategy.UpdateKnn(this, p, configuration); }
// Used when p position has been updated public void UpdatePosition(IP p) { this.GridContainer.UpdatePosition(p); }
public void Add(IP p) { Data.Add(p); }
// Primarily used for updating position, insert p into grid public void UpdatePosition(IP p) { var b = Remove(p); // remove prev position UpdateIndex(p); // update ref var set = GetSet(p); set.Add(p); // add new position }
// To work properly it requires the p is already normalized public static int[] GetPointMappedIds(IP p, Boundary grid, double deltax, double deltay) { var relativeX = p.X - grid.Minx; var relativeY = p.Y - grid.Miny; int idx, idy; // Naive version, lon points near 180 and lat points near 90 are not clustered together //idx = (int)(relativeX / deltax); //idy = (int)(relativeY / deltay); // end Naive version /* You have to draw a line with longitude values 180, -180 on papir to understand this e.g. _deltaX = 20 longitude 150 170 180 -170 -150 | | | | idx = 7 8 9 -9 -8 -10 here we want idx 8, 9, -10 and -9 be equal to each other, we set them to idx=8 then the longitudes from 170 to -170 will be clustered together */ var overlapMapMinX = (int)(LatLonInfo.MinLonValue / deltax) - 1; var overlapMapMaxX = (int)(LatLonInfo.MaxLonValue / deltax); // The deltaX = 20 example scenario, then set the value 9 to 8 and -10 to -9 // Similar to if (LatLonInfo.MaxLonValue % deltax == 0) without floating presicion issue if (Math.Abs(LatLonInfo.MaxLonValue % deltax - 0) < Numbers.Epsilon) { overlapMapMaxX--; overlapMapMinX++; } var idxx = (int)(p.X / deltax); if (p.X < 0) idxx--; if (Math.Abs(LatLonInfo.MaxLonValue % p.X - 0) < Numbers.Epsilon) { if (p.X < 0) idxx++; else idxx--; } if (idxx == overlapMapMinX) idxx = overlapMapMaxX; idx = idxx; // Latitude never wraps around with Google Maps, ignore 90, -90 wrap-around for latitude idy = (int)(relativeY / deltay); return new[] { idx, idy }; }
public void UpdateIndex(IP p) { this.GridContainer.UpdateIndex(p); }
public TrapV1Pdu(uint[] enterprise, IP agent, Integer32 generic, Integer32 specific, TimeTicks timestamp, IList<Variable> variables) : this(new ObjectIdentifier(enterprise), agent, generic, specific, timestamp, variables) { }
public List<IP> GetRing(IP p, int ring) { if (ring == 0) return GetSet(p).ToList(); var center = p.GridIndex; var indexes = new HashSet<GridIndex>(); for (var i = -ring; i <= ring; i++) { // add horizontal indexes.Add(new GridIndex { X = center.X + i, Y = center.Y - ring }); indexes.Add(new GridIndex { X = center.X + i, Y = center.Y + ring }); // add vertical indexes.Add(new GridIndex { X = center.X - ring, Y = center.Y + i }); indexes.Add(new GridIndex { X = center.X + ring, Y = center.Y + i }); } var list = new List<IP>(); foreach (var i in indexes.Where(IsValidGridIndex)) list.AddRange(Grid.Get(i)); return list; }
public static bool IsInside(Boundary b, IP p) { return IsInside(b.Minx, b.Miny, b.Maxx, b.Maxy, p.X, p.Y, false, false); }
public bool Remove(IP p) { var set = GetSet(p); return set.Remove(p); // remove }
// Single detect // 20 nearest boxes public List<IP> GetGridNeighborContent(IP p) { var i = p.GridIndex; // nearest neighbor var n = new GridIndex { X = i.X, Y = i.Y - 1 }; var ne = new GridIndex { X = i.X + 1, Y = i.Y - 1 }; var e = new GridIndex { X = i.X + 1, Y = i.Y }; var se = new GridIndex { X = i.X + 1, Y = i.Y + 1 }; var s = new GridIndex { X = i.X, Y = i.Y + 1 }; var sw = new GridIndex { X = i.X - 1, Y = i.Y + 1 }; var w = new GridIndex { X = i.X - 1, Y = i.Y }; var nw = new GridIndex { X = i.X - 1, Y = i.Y - 1 }; // outer north var nnw = new GridIndex { X = i.X - 1, Y = i.Y - 2 }; var nn = new GridIndex { X = i.X, Y = i.Y - 2 }; var nne = new GridIndex { X = i.X + 1, Y = i.Y - 2 }; // outer east var nee = new GridIndex { X = i.X + 2, Y = i.Y - 1 }; var ee = new GridIndex { X = i.X + 2, Y = i.Y }; var see = new GridIndex { X = i.X + 2, Y = i.Y + 1 }; // outer south var sse = new GridIndex { X = i.X + 1, Y = i.Y + 2 }; var ss = new GridIndex { X = i.X, Y = i.Y + 2 }; var ssw = new GridIndex { X = i.X - 1, Y = i.Y + 2 }; // outer west var sww = new GridIndex { X = i.X - 2, Y = i.Y - 1 }; var ww = new GridIndex { X = i.X - 2, Y = i.Y }; var nww = new GridIndex { X = i.X - 2, Y = i.Y + 1 }; var list = new List<IP>(); GridIndex gi; if (IsValidGridIndex(gi = n)) list.AddRange(Grid.Get(gi)); if (IsValidGridIndex(gi = ne)) list.AddRange(Grid.Get(gi)); if (IsValidGridIndex(gi = e)) list.AddRange(Grid.Get(gi)); if (IsValidGridIndex(gi = se)) list.AddRange(Grid.Get(gi)); if (IsValidGridIndex(gi = s)) list.AddRange(Grid.Get(gi)); if (IsValidGridIndex(gi = sw)) list.AddRange(Grid.Get(gi)); if (IsValidGridIndex(gi = w)) list.AddRange(Grid.Get(gi)); if (IsValidGridIndex(gi = nw)) list.AddRange(Grid.Get(gi)); if (IsValidGridIndex(gi = nnw)) list.AddRange(Grid.Get(gi)); if (IsValidGridIndex(gi = nn)) list.AddRange(Grid.Get(gi)); if (IsValidGridIndex(gi = nne)) list.AddRange(Grid.Get(gi)); if (IsValidGridIndex(gi = nee)) list.AddRange(Grid.Get(gi)); if (IsValidGridIndex(gi = ee)) list.AddRange(Grid.Get(gi)); if (IsValidGridIndex(gi = see)) list.AddRange(Grid.Get(gi)); if (IsValidGridIndex(gi = sse)) list.AddRange(Grid.Get(gi)); if (IsValidGridIndex(gi = ss)) list.AddRange(Grid.Get(gi)); if (IsValidGridIndex(gi = ssw)) list.AddRange(Grid.Get(gi)); if (IsValidGridIndex(gi = sww)) list.AddRange(Grid.Get(gi)); if (IsValidGridIndex(gi = ww)) list.AddRange(Grid.Get(gi)); if (IsValidGridIndex(gi = nww)) list.AddRange(Grid.Get(gi)); return list; }
protected GridIndex Delta(IP a) { var x = (int)((_rect.XO + a.X) / DX); var y = (int)((_rect.YO + a.Y) / DY); if (x < 0 || y < 0) throw new ApplicationException( string.Format("Algo error: {0}", MethodBase.GetCurrentMethod()) ); return new GridIndex { X = x, Y = y }; }
private void ProcessHelloPacket(HelloPacket pkt) { db = new Database(); //Console.Out.WriteLine(pkt.GUID + ": " + pkt.Password); if ((account = db.Verify(pkt.GUID, pkt.Password)) == null) { Console.WriteLine(@"Account not verified."); account = Database.CreateGuestAccount(pkt.GUID); if (account == null) { Console.WriteLine(@"Account is null!"); SendPacket(new FailurePacket { Message = "Invalid account." }); Disconnect(); db.Dispose(); return; } } if ((ip = db.CheckIp(skt.RemoteEndPoint.ToString().Split(':')[0])) == null) { Console.WriteLine(@"Error checking IP"); SendPacket(new FailurePacket { Message = "Error with IP." }); Disconnect(); db.Dispose(); return; } Console.WriteLine(@"Client trying to connect!"); ConnectedBuild = pkt.BuildVersion; if (!RealmManager.TryConnect(this)) { if (CheckAccountInUse(account.AccountId) != false) { Console.WriteLine(@"Account in use: " + account.AccountId + @" " + account.Name); account = null; SendPacket(new FailurePacket { Message = "Account in use! Retrying..." }); Disconnect(); db.Dispose(); return; } account = null; SendPacket(new FailurePacket { Message = "Failed to connect." }); Disconnect(); Console.WriteLine(@"Failed to connect."); } else { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(@"Client loading world"); Console.ForegroundColor = ConsoleColor.White; var world = RealmManager.GetWorld(pkt.GameId); if (world == null) { SendPacket(new FailurePacket { Message = "Invalid world." }); Disconnect(); Console.WriteLine(@"Invalid world"); } Console.ForegroundColor = ConsoleColor.Yellow; try { Console.WriteLine(@"Client joined world " + world.Id); } catch { Console.WriteLine(@"Error! World is null"); } Console.ForegroundColor = ConsoleColor.White; if (world.Id == -6) //Test World (world as Test).LoadJson(pkt.MapInfo); else if (world.IsLimbo) world = world.GetInstance(this); var seed = (uint) ((long) Environment.TickCount*pkt.GUID.GetHashCode())%uint.MaxValue; Random = new wRandom(seed); targetWorld = world.Id; if (!ConnectedBuildStartsWith(clientVer)) { SendPacket(new TextPacket { BubbleTime = 1, Stars = -1, Name = "", Text = "Your client is outdated. Visit http://forum.zerorealms.com to get the latest one!" }); Disconnect(); /*SendPacket(new TextBoxPacket { Button1 = "Okay", Message = "Your client is outdated, Click <font color=\"white\"><b><a href='http://forum.zerorealms.com'>Here</a></b></font> to get the latest one!", Title = "Outdated Client!", Type = "NewClient" });*/ } SendPacket(new MapInfoPacket { Width = world.Map.Width, Height = world.Map.Height, Name = world.Name, Seed = seed, Background = world.Background, AllowTeleport = world.AllowTeleport, ShowDisplays = world.ShowDisplays, Music = world.GetMusic(Random), ClientXML = world.ClientXML, ExtraXML = world.ExtraXML, SendMusic = ConnectedBuildStartsWith(clientVer) }); stage = ProtocalStage.Handshaked; } }
public static double Haversine(IP p1, IP p2) { return Haversine(p1.Y, p1.X, p2.Y, p2.X); }
public G(IA a, IO o, IP p) { o.Result += a.Process; a.Result += p.Process; }
private void ProcessHelloPacket(HelloPacket pkt) { if (isGuest) Disconnect(); db = new Database(); // Console.Out.WriteLine(pkt.GUID + ": " + pkt.Password); // Console.Out.WriteLine(pkt.GUID + ": " + account.AccountId + @" " + account.Name); if ((account = db.Verify(pkt.GUID, pkt.Password)) == null) { Console.WriteLine(@"Account not verified."); account = Database.CreateGuestAccount(pkt.GUID); if (account == null) { Console.WriteLine(@"Account is null!"); SendPacket(new FailurePacket { Message = "Invalid account." }); Disconnect(); return; } } if ((ip = db.CheckIp(skt.RemoteEndPoint.ToString().Split(':')[0])) == null) { Console.WriteLine(@"Error checking IP"); SendPacket(new FailurePacket { Message = "Error with IP." }); Disconnect(); return; } Console.WriteLine(@"Client trying to connect!" + account.AccountId + @" " + account.Name); ConnectedBuild = pkt.BuildVersion; if (!RealmManager.TryConnect(this)) { if (CheckAccountInUse(account.AccountId) != false) { Console.WriteLine(@"Account in use: " + account.AccountId + @" " + account.Name); account = null; SendPacket(new FailurePacket { Message = "Account in use! Retrying..." }); Disconnect(); return; } account = null; SendPacket(new FailurePacket { Message = "Failed to connect." }); Disconnect(); Console.WriteLine(@"Failed to connect."); } else { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(@"Client loading world"); Console.ForegroundColor = ConsoleColor.White; var world = RealmManager.GetWorld(pkt.GameId); if (world == null) { SendPacket(new FailurePacket { Message = "Invalid world, Restart your Client." }); Disconnect(); Console.WriteLine(@"Invalid world"); } Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(@"Client joined world " + world.Id); Console.ForegroundColor = ConsoleColor.White; if (world.Id == -6) //Test World (world as Test).LoadJson(pkt.MapInfo); else if (world.IsLimbo) world = world.GetInstance(this); var seed = (uint) ((long) Environment.TickCount*pkt.GUID.GetHashCode())%uint.MaxValue; Random = new wRandom(seed); targetWorld = world.Id; SendPacket(new MapInfoPacket { Width = world.Map.Width, Height = world.Map.Height, Name = world.Name, Seed = seed, Background = world.Background, AllowTeleport = world.AllowTeleport, ShowDisplays = world.ShowDisplays, ClientXML = world.ClientXML, ExtraXML = world.ExtraXML }); stage = ProtocalStage.Handshaked; } }
public MySet<IP> GetSet(IP p) { return this.Grid.Get(p.GridIndex); }
// Don't insert p into grid, only update public void UpdateIndex(IP p) { var d = Delta(p); p.GridIndex = d; // update ref }