Esempio n. 1
1
        public override void OnUpdate(long msec)
        {
            var g2d = Graphics2D.GetInstance ();
            var pos = g2d.GetMousePosition ();

            if (Input.GetKeyDown (KeyCode.Mouse0)) {
                var start = new Vector3 (pos.X, pos.Y, 1000);
                var end = new Vector3 (pos.X, pos.Y, -1000);
                var node = World.Pick (start, end);
                if (node != null) {
                    this.picked = node;
                    this.delta = pos - new Vector2 (node.Position.X, node.Position.Y);
                }
            }
            if (Input.GetKeyUp(KeyCode.Mouse0)) {
                this.picked = null;
            }

            if (picked != null) {
                var t = pos - delta;
                picked.Translation = new Vector3(t.X, t.Y, 0);
            }

            base.OnUpdate (msec);
        }
        public void SendPing()
        {
            engine.Add(node);
            engine.TimeOut = TimeSpan.FromMilliseconds(75);
            ManualResetEvent handle = new ManualResetEvent(false);
            engine.MessageLoop.QuerySent += delegate(object o, SendQueryEventArgs e) {
                if (!e.TimedOut && e.Query is Ping)
                    handle.Set();

                if (!e.TimedOut || !(e.Query is Ping))
                    return;

                PingResponse response = new PingResponse(node.Id, e.Query.TransactionId);
                listener.RaiseMessageReceived(response, e.EndPoint);
            };

            Assert.AreEqual(NodeState.Unknown, node.State, "#1");

            DateTime lastSeen = node.LastSeen;
            Assert.IsTrue(handle.WaitOne(1000, false), "#1a");
            Node nnnn = node;
            node = engine.RoutingTable.FindNode(nnnn.Id);
            Assert.IsTrue (lastSeen < node.LastSeen, "#2");
            Assert.AreEqual(NodeState.Good, node.State, "#3");
        }
Esempio n. 3
1
        public Comment(Node hostNode)
        {
            HostNode = hostNode;

            var scrollViewer = new ScrollViewer
            {
                HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled,
                VerticalScrollBarVisibility = ScrollBarVisibility.Visible,
                Height = 70,
                CanContentScroll = true
            };

            var textBlock = new TextBlock
            {
                Background = Brushes.Transparent,
                TextWrapping = TextWrapping.Wrap,
                Margin = new Thickness(5),
                FontSize = 12
            };

            Child = scrollViewer;
            CornerRadius = new CornerRadius(5);
            scrollViewer.Content = textBlock;


            var bindingTextToTextBlock = new Binding("Text")
            {
                Source = this,
                Mode = BindingMode.OneWay
            };
            textBlock.SetBinding(TextBlock.TextProperty, bindingTextToTextBlock);

            hostNode.SpaceCanvas.Children.Add(this);
        }
Esempio n. 4
0
 public void SelectNode(Node node)
 {
     GameObject connection = Instantiate(Resources.Load("Connection")) as GameObject;
     Connection connection_component = connection.GetComponent<Connection>();
     connection_component.InitializeWithStartNode(node);
     m_connection = connection_component;
 }
Esempio n. 5
0
 public Node()
 {
     left = null;
     right = null;
     filled = false;
     this.Rectangle = null;
 }
Esempio n. 6
0
 public override void OnMailBox(Node from, string address, object letter)
 {
     for (var i = 0; i < lineCount-1; i++) {
         GetComponent<Label> (i).Text = GetComponent<Label> (i + 1).Text;
     }
     GetComponent<Label> (lineCount - 1).Text = (string)letter;
 }
        public void PutTest()
        {
            Node node1 = new Node(mSkynet);
            Node node2 = new Node(mSkynet);
            Node node3 = new Node(mSkynet);
            node2.parent = node1.selfNode;
            node2.parentModifiedTime = Skynet.Utils.Utils.UnixTimeNow();
            Task.Run(async () => {
                ToxResponse response = await RequestProxy.sendRequest(mSkynet, new ToxRequest {
                    uuid = Guid.NewGuid().ToString(),
                    url = "node/" + node3.selfNode.uuid + "/grandParents",
                    content = JsonConvert.SerializeObject(node1.selfNode),
                    method = "put",
                    fromNodeId = node2.selfNode.uuid,
                    fromToxId = node2.selfNode.toxid,
                    toNodeId = node3.selfNode.uuid,
                    toToxId = node3.selfNode.toxid,
                    time = node2.parentModifiedTime
                });

                NodeResponse res = JsonConvert.DeserializeObject<NodeResponse>(response.content);
                Assert.AreEqual(node1.selfNode.uuid, node3.grandParents.uuid);
                Assert.AreEqual(node2.parentModifiedTime, node3.grandParentsModifiedTime);
            }).GetAwaiter().GetResult();
        }
Esempio n. 8
0
		public static void magix_viewport_load_viewport(object sender, ActiveEventArgs e)
		{
            Node ip = Ip(e.Params);
            if (ShouldInspect(ip))
            {
                AppendInspectFromResource(
                    ip["inspect"],
                    "Magix.tiedown",
                    "Magix.tiedown.hyperlisp.inspect.hl",
                    "[magix.viewport.load-viewport-dox].value");
                return;
			}

			Node node = new Node();
            node["file"].Value = "plugin:magix.file.load-from-resource";
            node["file"]["assembly"].Value = "Magix.tiedown";
            node["file"]["resource-name"].Value = "Magix.tiedown.hyperlisp.load-viewport.hl";

			RaiseActiveEvent(
				"magix.execute.execute-script",
				node);

            Control ctrl = ModuleControllerLoader.Instance.LoadActiveModule(node["params"]["viewport"].Get<string>());
            e.Params["viewport"].Value = ctrl;
        }
Esempio n. 9
0
	int GetDistance(Node nodeA, Node nodeB) {
		int dstX = Mathf.Abs (nodeA.gridX - nodeB.gridX);
		int dstY = Mathf.Abs (nodeA.gridY - nodeB.gridY);
		if (dstX > dstY)
			return 14 * dstY + 10 * (dstX - dstY);
		return 14 * dstX + 10 * (dstY - dstX);
	}
Esempio n. 10
0
        public Bullet(Node parent, string name)
            : base(parent, name)
        {
            Render = new ImageRender(this, "Render");
            Render.SetTexture(GetRoot<State>().GetService<AssetCollector>().GetAsset<Texture2D>("bullet"));
            Render.Layer = .1f;
            Render.Scale = new Vector2(.1f);
            Render.Color = Color.White;
            Render.LinkDependency(ImageRender.DEPENDENCY_BODY, Body);

            //Make our collision rectangles the size of the rendered sprite.
            Body.Bounds = Render.Bounds;
            Body.Origin = new Vector2(Render.Texture.Width / 2f, Render.Texture.Height / 2f);

            Shape = new Circle(this, "Shape", Body.Width / 2);
            Shape.Offset = new Vector2(Body.Width / 2, Body.Height / 2);
            Shape.LinkDependency(Circle.DEPENDENCY_BODY, Body);

            Collision.Group.AddMask(1);
            Collision.Pair.AddMask(2);
            Collision.Immovable = true;
            Collision.CollideEvent += collision => Recycle();
            Collision.LinkDependency(Collision.DEPENDENCY_SHAPE, Shape);
            Shape.LinkDependency(Circle.DEPENDENCY_COLLISION, Collision);

            DeathTimer = new Timer(this, "DeathTimer");
            DeathTimer.Milliseconds = 2000;
            DeathTimer.LastEvent += Recycle;
            DeathTimer.LastEvent += DeathTimer.Stop;
        }
Esempio n. 11
0
 public SolverValidator(Solver solver, NodeCollection nodes, Node root, IPositionLookupTable<Node> transpositionTable)
 {
     this.solver = solver;
     this.nodes = nodes;
     this.root = root;
     this.transpositionTable = transpositionTable;
 }
Esempio n. 12
0
 public Tilemap(Node parent, string name, Texture2D tileTexture, Point size, Point tileSize)
     : base(parent, name)
 {
     Body = new Body(this, "Body");
     Render = new TilemapRender(this, "TilemapRender", tileTexture, size, tileSize);
     Render.LinkDependency(TilemapRender.DEPENDENCY_BODY, Body);
 }
Esempio n. 13
0
        public void doNeighborListUpdate(Node.NodeList neighborList)
        {
            Debug.WriteLine("doNeighborListUpdate");

                        lock (neighborListLock)
                        {
                                neighborListView.Items.Clear();

                                neighborListView.BeginUpdate();

                                Debug.WriteLine("Looping through neighbors");
                                foreach (Haggle.Node neighbor in neighborList.AsArray())
                                {
                                        string ifaceStr = "";
                                        Debug.WriteLine("Adding neighbor " + neighbor.GetName());
                                        ListViewItem neighItem = new ListViewItem(neighbor.GetName());
                                        foreach (Node.Interface iface in neighbor.InterfacesArray())
                                        {
                                                ifaceStr += iface.GetIdentifierStr() + ",";
                                        }

                                        char[] tc = { ',' };
                                        neighItem.SubItems.Add(ifaceStr.TrimEnd(tc));
                                        neighborListView.Items.Add(neighItem);

                                }
                                neighborListView.EndUpdate();
                                Debug.WriteLine("Neighborlist update end");
                        }
        }
Esempio n. 14
0
    private static void SaveAllConncectedComponents(Node<int> node,
        HashSet<int> visitedNodes, List<string> connectedComponents)
    {
        string graphs = string.Empty;
        Stack<Node<int>> nodesStack = new Stack<Node<int>>();
        nodesStack.Push(node);

        while (nodesStack.Count > 0)
        {
            Node<int> currentNode = nodesStack.Pop();
            visitedNodes.Add(currentNode.Value);
            graphs += " -> " + currentNode.Value;

            foreach (var child in currentNode.Children)
            {
                if (!visitedNodes.Contains(child.Value))
                {
                    visitedNodes.Add(child.Value);
                    nodesStack.Push(child);
                }
            }
        }

        connectedComponents.Add(graphs.Substring(4));
    }
 public static void ElecticityUpdate(Game game, Node center)
 {
     Node tmp = center;
     int Volt = game.getScore();
     int In = game.getScore();
     ElectricityCalcul(tmp, ref Volt, In, true, tmp);
 }
 static void ElectricityCalcul(Node actual, ref int VoltageColector, int Intensity, bool previous, Node From)
 {
     if (VoltageColector <= 0 || previous ==  false ||  actual._activatedByPlayer == false || Intensity == 0)
     {
         actual._activated = false;
     }
     else
     {
         if (VoltageColector < actual.getCost())
         {
            actual._activated = false;
         }
         else
         {
            actual._activated = true;
            actual._intensity = Intensity;
            VoltageColector = VoltageColector - actual.getCost();
         }
     }
     int localVoltage  = VoltageColector;
     actual._peerOut.ForEach(delegate(Node other)
     {
       if (other != From)
         ElectricityCalcul(other, ref localVoltage, (int)actual.energyDiv(), actual._activated, actual);
         });
     VoltageColector = localVoltage;
 }
Esempio n. 17
0
        /*
         * actual implementation of sandbox
         */
        private static void SandboxCode(Node pars, Node ip)
        {
            // storing and clearing old whitelist
            // and checking to see that no keyword not previously whitelisted has been whitelisted
            Node oldWhitelist = null;
            if (pars.Contains("_whitelist"))
            {
                foreach (Node idx in ip["whitelist"])
                {
                    if (!pars["_whitelist"].Contains(idx.Name))
                        throw new HyperlispExecutionErrorException("cannot [whitelist] an active event that was blacklisted in a previous [sandbox]");
                }
                oldWhitelist = pars["_whitelist"].Clone();
                pars["_whitelist"].Clear();
            }

            // setting new whitelist
            pars["_whitelist"].AddRange(ip["whitelist"].Clone());
            try
            {
                pars["_ip"].Value = ip["code"];
                RaiseActiveEvent(
                    "magix.execute",
                    pars);
            }
            finally
            {
                pars["_whitelist"].UnTie();
                if (oldWhitelist != null)
                    pars["_whitelist"].AddRange(oldWhitelist);
            }
        }
Esempio n. 18
0
 internal Node AddNode()
 {
     var nd = new Node();
     nd.Index = Nodes.Count;
     Nodes.Add(nd);
     return nd;
 }
Esempio n. 19
0
 //sets the ai nodes
 void setNodes(Node n,Node e,Node s,Node w)
 {
     this.n = n;
     this.e = e;
     this.s = s;
     this.w = w;
 }
        public static void Run()
        {
            // Initialize scene object
            Scene scene = new Scene();

            // Initialize Node class object
            Node cubeNode = new Node("cube");

            // Call Common class create mesh method to set mesh instance
            Mesh mesh = Common.CreateMesh();

            // Point node to the Mesh geometry
            cubeNode.Entity = mesh;

            // Set rotation
            cubeNode.Transform.Rotation = Quaternion.FromRotation(new Vector3(0, 1, 0), new Vector3(0.3, 0.5, 0.1));

            // Set translation
            cubeNode.Transform.Translation = new Vector3(0, 0, 20);

            // Add cube to the scene
            scene.RootNode.ChildNodes.Add(cubeNode);

            // The path to the documents directory.
            string MyDir = RunExamples.GetDataDir_GeometryAndHierarchy();
            MyDir = MyDir + "TransformationToNode.fbx";

            // Save 3D scene in the supported file formats
            scene.Save(MyDir, FileFormat.FBX7400ASCII);

            Console.WriteLine("\nTransformation added successfully to node.\nFile saved at " + MyDir);
        }
Esempio n. 21
0
        public void Test_Distance()
        {
            var node1 = new Node ("Node1");
            var col1 = new CollisionObject ();
            col1.Shape = new BoxShape (1, 1, 1);
            node1.Attach (col1);

            var node2 = new Node ("Node2");
            var col2 = new CollisionObject ();
            col2.Shape = new BoxShape (1, 1, 1);
            node2.Attach (col2);

            var wld = new World ();
            wld.AddChild (node1);
            wld.AddChild (node2);

            node1.Translate (0, 0, 0);
            node2.Translate (0, 0, 0);
            Assert.AreEqual (0, wld.Distance (node1, node2));

            node1.Translate (0, 0, 0);
            node2.Translate (10, 0, 0);
            Assert.AreEqual (8, wld.Distance (node1, node2), 0.01f);

            node1.Rotate (0, 0, 0, 0);
            node2.Rotate (45, 0, 0, 1);
            Assert.AreEqual (7.6f, wld.Distance (node1, node2), 0.01f);

            node1.Detach (col1);
            node2.Detach (col2);
            Assert.AreEqual (Single.NaN, wld.Distance (node1, node2), 0.01f);
        }
Esempio n. 22
0
        public void Test_Overlap()
        {
            var node1 = new Node ("Node1");
            var col1 = new CollisionObject ();
            col1.Shape = new BoxShape (1, 1, 1);
            node1.Attach (col1);

            var node2 = new Node ("Node1");
            var col2 = new CollisionObject ();
            col2.Shape = new BoxShape (1, 1, 1);
            node2.Attach (col2);

            var wld = new World ();
            wld.AddChild (node1);
            wld.AddChild (node2);

            node1.Translate (0, 0, 0);
            node2.Translate (0, 0, 0);
            Assert.AreEqual (true, wld.Overlap (node1, node2));

            node1.Translate (0, 0, 0);
            node2.Translate (10, 0, 0);
            Assert.AreEqual (false, wld.Overlap (node1, node2));

            node1.Rotate (0, 0, 0, 0);
            node2.Rotate (45, 0, 0, 1);
            Assert.AreEqual (false, wld.Overlap (node1, node2));

            node1.Detach (col1);
            node2.Detach (col2);
            Assert.AreEqual (false, wld.Overlap (node1, node2));
        }
Esempio n. 23
0
 public DoorSensor(Node node)
     : base(node)
 {
     node.GetCommandClass<Basic>().Changed += Basic_Changed;
     node.GetCommandClass<SensorBinary>().Changed += SensorBinary_Changed;
     node.GetCommandClass<SensorAlarm>().Changed += SensorAlarm_Changed;
 }
        private void CreateControls(Node node)
        {
            foreach(Node idx in node)
            {
                string caption = idx["Caption"].Get<string>();
                string value = idx["Value"].Get<string>();
                string type = idx["Type"].Get<string>();
                int position = idx["Position"].Get<int>();

                Panel pnl = new Panel();
                pnl.CssClass = "bordered-panel";

                Label cpt = new Label();
                cpt.CssClass = "label-caption";
                cpt.Text = caption;
                pnl.Controls.Add(cpt);

                Label val = new Label();
                val.CssClass = "label-value";
                val.Text = value;
                pnl.Controls.Add(val);

                // Rooting...
                wrpPnl.Controls.Add(pnl);
            }
        }
Esempio n. 25
0
		/// <summary>
		/// Validates and constructs generic entities out of an ambiguous generic definition entity.
		/// </summary>
		private IEntity ConstructAmbiguousEntity(Node constructionNode, Ambiguous ambiguousDefinition, IType[] typeArguments)
		{
			var checker = new GenericConstructionChecker(typeArguments, constructionNode); 
			var matches = new List<IEntity>(ambiguousDefinition.Entities);
			bool reportErrors = false;
			foreach (Predicate<IEntity> check in checker.Checks)
			{
				matches = matches.Collect(check);

				if (matches.Count == 0)
				{
					Errors.Add(checker.Errors[0]); // only report first error, assuming the rest are superfluous
					return TypeSystemServices.ErrorEntity;
				}

				if (reportErrors)
					checker.ReportErrors(Errors);

				checker.DiscardErrors();

				// We only want full error reporting once we get down to a single candidate
				if (matches.Count == 1)
					reportErrors = true;
			}

			IEntity[] constructedMatches = Array.ConvertAll<IEntity, IEntity>(matches.ToArray(), def => MakeGenericEntity(def, typeArguments));
			return Entities.EntityFromList(constructedMatches);
		}
Esempio n. 26
0
        public void Test_CollideWith()
        {
            var node1 = new Node ("Node1");
            node1.Attach(new CollisionObject ());
            node1.CollisionObject.Shape = new BoxShape (1, 1, 1);
            node1.GroupID = 1;

            var node2 = new Node ("Node2");
            node2.Attach (new CollisionObject ());
            node2.CollisionObject.Shape = new BoxShape (1, 1, 1);
            node2.GroupID = 2;

            var wld = new World ();
            wld.AddChild (node1);
            wld.AddChild (node2);

            node1.CollisionObject.CollideWith = -1;
            Assert.AreEqual (true, wld.Overlap (node1, node2));

            node1.CollisionObject.CollideWith = 1;
            Assert.AreEqual (false, wld.Overlap (node1, node2));

            node1.CollisionObject.CollideWith = 2;
            Assert.AreEqual (true, wld.Overlap (node1, node2));

            node1.CollisionObject.CollideWith = 2;
            node1.CollisionObject.IgnoreWith = 2;
            Assert.AreEqual (false, wld.Overlap (node1, node2));
        }
Esempio n. 27
0
        public MoshParser(ILexer lexer)
        {
            m_startRuleToken = new Token { TokenType = TokenType.NEW_RULE };
            m_tree = new Node<string>();
            m_lexer = lexer;
            m_consumed = new Stack<Token>();
            m_err = new Queue<Error>();

            // Setup rule pre-calling conditions
            m_rulePreHook = name =>
                                {
                                    if (m_tree.Value == null)
                                    {
                                        m_tree.Value = name;
                                        return m_tree;
                                    }

                                    var tempNode = m_tree;
                                    var newTopNode = m_tree.AddChild(name);
                                    m_tree = newTopNode;
                                    return tempNode;
                                };

            // Setup rule post-calling conditions
            m_rulePostHook = node => m_tree = node;
        }
Esempio n. 28
0
 public void Setup()
 {
     listener = new TestListener();
     node = new Node(NodeId.Create(), new IPEndPoint(IPAddress.Any, 0));
     engine = new DhtEngine(listener);
     //engine.Add(node);
 }
Esempio n. 29
0
        public NodeViewModel(Node node, Vector location, IControlTypesResolver controlTypesResolver)
        {
            Node = node;
            Title = node.Title;
            Location = new CanvasPoint(location);
            ControlTypesResolver = controlTypesResolver;

            foreach (var pin in node.InputPins)
            {
                AddInputPin(pin);
            }

            foreach (var pin in node.OutputPins)
            {
                AddOutputPin(pin);
            }

            node.Processed += OnNodeProcessed;
            node.PinsChanged += OnNodePinsChanged;

            _disposable = Disposable.Create(() =>
            {
                node.PinsChanged -= OnNodePinsChanged;
                node.Processed -= OnNodeProcessed;
            });
        }
Esempio n. 30
0
        public void CircularDependency_ThrowsCircularDependencyException_Test()
        {
            var a = new Node<object>("a");
            var b = new Node<object>("b");
            var c = new Node<object>("c");
            var d = new Node<object>("d");
            var e = new Node<object>("e");

            a.Edges.Add(b); // a depends on b
            a.Edges.Add(d); // a depends on d
            b.Edges.Add(c); // b depends on c
            b.Edges.Add(e); // b depends on e
            c.Edges.Add(d); // c depends on d
            c.Edges.Add(e); // c depends on e
            d.Edges.Add(b); // d depends on b

            var resolved = new List<Node<object>>();

            CircularDependencyException<object> exception = null;
            try
            {
                a.ResolveDependencies();
            }
            catch (CircularDependencyException<object> ex)
            {
                exception = ex;
            }

            Assert.NotNull(exception);
            Assert.Equal(d, exception.A);
            Assert.Equal(b, exception.B);
        }
Esempio n. 31
0
        private void GrowTable(Tables tables)
        {
            const int maxArrayLength = 0X7FEFFFFF;
            var locksAcquired = 0;
            try
            {
                // The thread that first obtains _locks[0] will be the one doing the resize operation
                AcquireLocks(0, 1, ref locksAcquired);

                // Make sure nobody resized the table while we were waiting for lock 0:
                if (tables != _tables)
                {
                    // We assume that since the table reference is different, it was already resized (or the budget
                    // was adjusted). If we ever decide to do table shrinking, or replace the table for other reasons,
                    // we will have to revisit this logic.
                    return;
                }

                // Compute the (approx.) total size. Use an Int64 accumulation variable to avoid an overflow.
                long approxCount = 0;
                for (var i = 0; i < tables.CountPerLock.Length; i++)
                {
                    approxCount += tables.CountPerLock[i];
                }

                //
                // If the bucket array is too empty, double the budget instead of resizing the table
                //
                if (approxCount < tables.Buckets.Length / 4)
                {
                    _budget = 2 * _budget;
                    if (_budget < 0)
                    {
                        _budget = int.MaxValue;
                    }
                    return;
                }

                // Compute the new table size. We find the smallest integer larger than twice the previous table size, and not divisible by
                // 2,3,5 or 7. We can consider a different table-sizing policy in the future.
                var newLength = 0;
                var maximizeTableSize = false;
                try
                {
                    checked
                    {
                        // Double the size of the buckets table and add one, so that we have an odd integer.
                        newLength = tables.Buckets.Length * 2 + 1;

                        // Now, we only need to check odd integers, and find the first that is not divisible
                        // by 3, 5 or 7.
                        while (newLength % 3 == 0 || newLength % 5 == 0 || newLength % 7 == 0)
                        {
                            newLength += 2;
                        }

                        Debug.Assert(newLength % 2 != 0);

                        if (newLength > maxArrayLength)
                        {
                            maximizeTableSize = true;
                        }
                    }
                }
                catch (OverflowException)
                {
                    maximizeTableSize = true;
                }

                if (maximizeTableSize)
                {
                    newLength = maxArrayLength;

                    // We want to make sure that GrowTable will not be called again, since table is at the maximum size.
                    // To achieve that, we set the budget to int.MaxValue.
                    //
                    // (There is one special case that would allow GrowTable() to be called in the future: 
                    // calling Clear() on the ConcurrentHashSet will shrink the table and lower the budget.)
                    _budget = int.MaxValue;
                }

                // Now acquire all other locks for the table
                AcquireLocks(1, tables.Locks.Length, ref locksAcquired);

                var newLocks = tables.Locks;

                // Add more locks
                if (_growLockArray && tables.Locks.Length < MaxLockNumber)
                {
                    newLocks = new object[tables.Locks.Length * 2];
                    Array.Copy(tables.Locks, 0, newLocks, 0, tables.Locks.Length);
                    for (var i = tables.Locks.Length; i < newLocks.Length; i++)
                    {
                        newLocks[i] = new object();
                    }
                }

                var newBuckets = new Node[newLength];
                var newCountPerLock = new int[newLocks.Length];

                // Copy all data into a new table, creating new nodes for all elements
                for (var i = 0; i < tables.Buckets.Length; i++)
                {
                    var current = tables.Buckets[i];
                    while (current != null)
                    {
                        var next = current.Next;
                        GetBucketAndLockNo(current.Hashcode, out int newBucketNo, out int newLockNo, newBuckets.Length, newLocks.Length);

                        newBuckets[newBucketNo] = new Node(current.Item, current.Hashcode, newBuckets[newBucketNo]);

                        checked
                        {
                            newCountPerLock[newLockNo]++;
                        }

                        current = next;
                    }
                }

                // Adjust the budget
                _budget = Math.Max(1, newBuckets.Length / newLocks.Length);

                // Replace tables with the new versions
                _tables = new Tables(newBuckets, newLocks, newCountPerLock);
            }
            finally
            {
                // Release all locks that we took earlier
                ReleaseLocks(0, locksAcquired);
            }
        }
Esempio n. 32
0
        public void Filter(List <string> companyNames)
        {
            List <Company>           retainedCompanies         = new List <Company>();
            List <Division>          retainedDivisions         = new List <Division>();
            List <Station>           retainedStations          = new List <Station>();
            List <Station>           stationsToRemove          = new List <Station>();
            List <Node>              retainedNodes             = new List <Node>();
            List <Node>              nodesToRemove             = new List <Node>();
            List <LineSegment>       lineSegmentsToRemove      = new List <LineSegment>();
            List <TransmissionLine>  transmissionLinesToRemove = new List <TransmissionLine>();
            List <CircuitBreaker>    circuitBreakersToRemove   = new List <CircuitBreaker>();
            List <Shunt>             shuntsToRemove            = new List <Shunt>();
            List <Transformer>       transformersToRemove      = new List <Transformer>();
            List <TransformerTap>    retainedTaps = new List <TransformerTap>();
            List <ParentTransformer> parentTransformersToRemove = new List <ParentTransformer>();

            Console.WriteLine("1");
            // Line segments, companies, stations
            Parallel.ForEach(m_lineSegments, (lineSegment) =>
            {
                string fromNodeId   = $"{lineSegment.FromStationName}_{lineSegment.FromNodeId}";
                string toNodeId     = $"{lineSegment.ToStationName}_{lineSegment.ToNodeId}";
                Node fromNode       = m_nodes.Find(x => $"{x.StationName}_{x.Id}" == fromNodeId);
                Node toNode         = m_nodes.Find(x => $"{x.StationName}_{x.Id}" == toNodeId);
                Company fromCompany = GetNodeCompany(fromNode);
                Company toCompany   = GetNodeCompany(toNode);

                Station fromStation = m_stations.Find(x => x.Name == lineSegment.FromStationName);
                Station toStation   = m_stations.Find(x => x.Name == lineSegment.ToStationName);

                if (companyNames.Contains(fromCompany.Name) || companyNames.Contains(toCompany.Name))
                {
                    if (!retainedStations.Contains(fromStation))
                    {
                        retainedStations.Add(fromStation);
                    }
                    if (!retainedStations.Contains(toStation))
                    {
                        retainedStations.Add(toStation);
                    }
                    if (!retainedNodes.Contains(fromNode))
                    {
                        retainedNodes.Add(fromNode);
                    }
                    if (!retainedNodes.Contains(toNode))
                    {
                        retainedNodes.Add(toNode);
                    }
                    if (!retainedCompanies.Contains(fromCompany))
                    {
                        retainedCompanies.Add(fromCompany);
                    }
                    if (!retainedCompanies.Contains(toCompany))
                    {
                        retainedCompanies.Add(toCompany);
                    }
                }
                else
                {
                    if (!lineSegmentsToRemove.Contains(lineSegment))
                    {
                        lineSegmentsToRemove.Add(lineSegment);
                    }
                    if (!stationsToRemove.Contains(fromStation))
                    {
                        stationsToRemove.Add(fromStation);
                    }
                    if (!stationsToRemove.Contains(toStation))
                    {
                        stationsToRemove.Add(toStation);
                    }
                }
            });

            Console.WriteLine("2");
            // Transmission Lines
            foreach (LineSegment lineSegment in lineSegmentsToRemove)
            {
                TransmissionLine transmissionLine = m_transmissionLines.Find(x => x.Id == lineSegment.TransmissionLineId);
                if (!transmissionLinesToRemove.Contains(transmissionLine))
                {
                    transmissionLinesToRemove.Add(transmissionLine);
                }
            }

            Console.WriteLine("3");
            // Nodes
            foreach (Station station in stationsToRemove)
            {
                List <Node> stationNodes = m_nodes.FindAll(x => x.StationName == station.Name);
                foreach (Node node in stationNodes)
                {
                    if (!nodesToRemove.Contains(node))
                    {
                        nodesToRemove.Add(node);
                    }
                }
            }

            Console.WriteLine("4");
            // Divisions
            foreach (Station station in retainedStations)
            {
                List <Node> stationNodes = m_nodes.FindAll(x => x.StationName == station.Name);
                foreach (Node node in stationNodes)
                {
                    Division division = m_divisions.Find(x => x.Name == node.DivisionName);

                    if (!retainedDivisions.Contains(division))
                    {
                        retainedDivisions.Add(division);
                    }
                }
            }

            Console.WriteLine("5");
            // Circuit breakers
            foreach (CircuitBreaker breaker in m_circuitBreakers)
            {
                Station parentStation = m_stations.Find(x => x.Name == breaker.StationName);
                if (stationsToRemove.Contains(parentStation))
                {
                    if (!circuitBreakersToRemove.Contains(breaker))
                    {
                        circuitBreakersToRemove.Add(breaker);
                    }
                }
            }


            Console.WriteLine("6");
            // shunts
            foreach (Shunt shunt in m_shunts)
            {
                Station parentStation = m_stations.Find(x => x.Name == shunt.StationName);
                if (stationsToRemove.Contains(parentStation))
                {
                    if (!shuntsToRemove.Contains(shunt))
                    {
                        shuntsToRemove.Add(shunt);
                    }
                }
            }

            Console.WriteLine("7");
            // Transformers and Transformer Taps
            foreach (Transformer transformer in m_transformers)
            {
                Station parentStation = m_stations.Find(x => x.Name == transformer.StationName);
                if (stationsToRemove.Contains(parentStation))
                {
                    if (!transformersToRemove.Contains(transformer))
                    {
                        transformersToRemove.Add(transformer);
                    }
                }
                else
                {
                    TransformerTap fromTap = m_transformerTaps.Find(x => x.Id == transformer.FromNodeTap);
                    TransformerTap toTap   = m_transformerTaps.Find(x => x.Id == transformer.ToNodeTap);
                    if (!retainedTaps.Contains(fromTap))
                    {
                        retainedTaps.Add(fromTap);
                    }
                    if (!retainedTaps.Contains(toTap))
                    {
                        retainedTaps.Add(toTap);
                    }
                }
            }
            Console.WriteLine("8");
            // Parent Transformer
            foreach (Transformer transformer in transformersToRemove)
            {
                ParentTransformer parentTransformer = m_parentTransformers.Find(x => x.Id == transformer.Parent);
                if (!parentTransformersToRemove.Contains(parentTransformer))
                {
                    parentTransformersToRemove.Add(parentTransformer);
                }
            }
            m_companies       = retainedCompanies;
            m_divisions       = retainedDivisions;
            m_transformerTaps = retainedTaps;

            Console.WriteLine("9");
            foreach (Station station in stationsToRemove)
            {
                m_stations.Remove(station);
            }

            foreach (LineSegment lineSegment in lineSegmentsToRemove)
            {
                m_lineSegments.Remove(lineSegment);
            }

            foreach (Node node in nodesToRemove)
            {
                m_nodes.Remove(node);
            }

            foreach (Shunt shunt in shuntsToRemove)
            {
                m_shunts.Remove(shunt);
            }

            foreach (CircuitBreaker breaker in circuitBreakersToRemove)
            {
                m_circuitBreakers.Remove(breaker);
            }

            foreach (Transformer transformer in transformersToRemove)
            {
                m_transformers.Remove(transformer);
            }

            foreach (ParentTransformer transformer in parentTransformersToRemove)
            {
                m_parentTransformers.Remove(transformer);
            }

            foreach (TransmissionLine transmissionLine in transmissionLinesToRemove)
            {
                m_transmissionLines.Remove(transmissionLine);
            }
        }
Esempio n. 33
0
    void Update()
    {
        //Clear influecing nodes!
        foreach (Node node in nodes)
        {
            node.InfluencingAttractors.Clear();
        }

        List <int>  attractorRemovalIndexes = new List <int>();
        List <Node> addedNodes = new List <Node>(); //All new nodes

        //Debug.Log("Amount of attractors [" + attractors.Count + "], Anmount of nodes [" + nodes.Count + "]", gameObject);

        //Check every attractor on nearby nodes
        for (int attractorIndex = 0; attractorIndex < attractors.Count; attractorIndex++)
        {
            Attractor attractor = attractors[attractorIndex];
            attractor.AttractingNode = null;

            //Check if there was an previous distance
            float shortestDistanceSquared = float.MaxValue;
            if (attractor.PreviousAttractingNode != null)
            {
                shortestDistanceSquared = (attractor.Position - attractor.PreviousAttractingNode.Position).sqrMagnitude;
                //Debug.Log("Previous node found! Tested distance squared= " + shortestDistanceSquared, gameObject);
            }

            bool removed = false;

            //Get closest node -> Influencing nodes
            for (int nodeIndex = 0; nodeIndex < nodes.Count; nodeIndex++)
            {
                Node  node = nodes[nodeIndex];
                float newDistanceSquared = (attractor.Position - node.Position).SqrMagnitude();
                //Debug.Log("New distance towards attractor" + newDistanceSquared, gameObject);

                //Check if attractor needs to be removed
                if (newDistanceSquared <= attractorKillDistance)
                {
                    //Debug.Log("Attractor will be removed", gameObject);
                    attractorRemovalIndexes.Add(attractorIndex);
                    removed = true;
                    break;
                }

                //Check if attractor is in attraction radius
                if (newDistanceSquared <= attractionRadius)
                {
                    if (shortestDistanceSquared >= newDistanceSquared)
                    {
                        //Debug.Log("Attractor will attract node", gameObject);
                        shortestDistanceSquared = newDistanceSquared;

                        if (attractor.AttractingNode != null)
                        {
                            attractor.AttractingNode.InfluencingAttractors.Remove(attractor);
                        }

                        attractor.AttractingNode = node;
                        node.InfluencingAttractors.Add(attractor);
                    }
                }
            }

            if (!removed)
            {
                //If there was no new node found (could be because of a smaller distance) but there was a previous valid node

                //BUG SPLASH!!!!

                //if (attractor.AttractingNode == null && attractor.PreviousAttractingNode != null)
                //{
                //    GameObject newBranch = Instantiate(branch, gameObject.transform.position + (Vector3)attractor.PreviousAttractingNode.Position, new Quaternion(), attractor.PreviousAttractingNode.Branch.transform);


                //    GrowingSpline branchSpline = newBranch.GetComponent<GrowingSpline>();

                //    branchSpline.GrowthDirection = (attractor.Position - attractor.PreviousAttractingNode.Position).normalized;
                //    branchSpline.SpriteShape = branchGrowthController.gameObject.GetComponent<GrowingSpline>().SpriteShape;


                //    BranchController newBranchController = newBranch.GetComponent<BranchController>();

                //    addedNodes.Add(newBranchController.BranchTopNode);
                //    newBranchController.NodeOffset = attractor.PreviousAttractingNode.Position;
                //}
            }
            else
            {
                attractor.AttractingNode = null; // node got deleted! Needs to be here otherwise next frame a new branch would appear
            }


            //Set previous node for next frame
            if (attractor.AttractingNode != null)
            {
                attractor.PreviousAttractingNode = new Node(attractor.AttractingNode);
            }
            else
            {
                attractor.PreviousAttractingNode = null;
            }
        }

        //Remove the attractors that need to be removed
        foreach (int removalIndex in attractorRemovalIndexes)
        {
            attractors.RemoveAt(removalIndex);
        }

        //Add all new nodes
        foreach (Node node in addedNodes)
        {
            nodes.Add(node);
        }


        //Check if still growing branches
        if (GetComponentInChildren <GrowingSpline>() == null)
        {
            Destroy(gameObject);
        }
    }
Esempio n. 34
0
 /// <summary>
 /// Finds all current nodes.
 /// </summary>
 /// <param name="expression">The expression.</param>
 /// <returns>The current nodes.</returns>
 public IEnumerable <VariableNode> CurrentNodes(Node expression) => Build(expression).Where(n => n.NodeType == NodeTypes.Current);
Esempio n. 35
0
 /// <summary>
 /// Finds all voltage nodes.
 /// </summary>
 /// <param name="expression">The expression node.</param>
 /// <returns>The voltage nodes.</returns>
 public IEnumerable <VariableNode> VoltageNodes(Node expression) => Build(expression).Where(n => n.NodeType == NodeTypes.Voltage);
 public Node CreateNodeClient(NodeConnectionParameters parameters)
 {
     return(Node.Connect(Network.RegTest, "127.0.0.1:" + this.ports[0].ToString(), parameters));
 }
 public Node CreateNodeClient()
 {
     return(Node.Connect(Network.RegTest, "127.0.0.1:" + this.ports[0].ToString()));
 }
Esempio n. 38
0
 public Node(Node other)
 {
     this.Position = other.Position;
     this.Branch   = other.Branch;
 }
Esempio n. 39
0
 private void Arg_OnValueUpdated(Node n)
 {
     UpdateInputs();
 }
Esempio n. 40
0
 private void SelectedFunction_OnOutputSet(Node n)
 {
     UpdateInputs();
 }
Esempio n. 41
0
 private void SelectedFunction_OnArgRemoved(Node n)
 {
     n.OnValueUpdated -= Arg_OnValueUpdated;
     UpdateInputs();
 }
Esempio n. 42
0
 private void SelectedFunction_OnArgAdded(Node n)
 {
     n.OnValueUpdated += Arg_OnValueUpdated;
     UpdateInputs();
 }
Esempio n. 43
0
 // Update is called once per frame
 void Update()
 {
     if (player != null)
     {
         if (player.IsAtTarget())
         {
             Node node = GetOverlap(player);
             if (node != null && node.risk > 0 && node != actionedNode)
             {
                 actionedNode = node;
             }
             if (node != null)
             {
                 Goal goal = node.gameObject.GetComponent <Goal>();
                 if (goal != null)
                 {
                     reachedGoal = goal;
                 }
                 Pickup pickup = node.pickup;
                 if (pickup != null && !pickup.consumed)
                 {
                     if (pickup.type == Pickup.PickupType.HEALTH)
                     {
                         pickup.Consume();
                         node.UpdateRiskText();
                         explosionHandler.PickupPlant(pickup.gameObject.transform.position + new Vector3(0, 0.4f, 0.4f));
                         playerHealth += pickup.amount;
                     }
                 }
                 GameInfo gameInfo = node.gameObject.GetComponentInChildren <GameInfo>();
                 if (gameInfo != null && !gameInfo.isShown)
                 {
                     ConvoHandler convoHandler = FindObjectOfType <ConvoHandler>();
                     convoHandler.ShowInfo(gameInfo);
                     gameInfo.Consume();
                 }
             }
         }
         if (waypoints.Count > 0)
         {
             if (waypoints.Count > 1)
             {
                 player.targetPos = waypoints[waypoints.Count - 1].transform.position;
             }
             else
             {
                 if (selectedNode != null && selectedNode.risk > 0)
                 {
                     Vector3 direction = Vector3.Normalize(selectedNode.transform.position - selectedPlayer.transform.position);
                     selectedPlayer.targetPos = selectedNode.transform.position - (direction * 1f);
                 }
                 else
                 {
                     player.targetPos = waypoints[waypoints.Count - 1].transform.position;
                 }
             }
             if (player.IsAtTarget())
             {
                 waypoints.Remove(waypoints[waypoints.Count - 1]);
             }
         }
     }
     if (isRolling)
     {
         diceResult = UnityEngine.Random.Range(1, 7);
     }
     else
     {
         diceResult = -100;
     }
 }
Esempio n. 44
0
        public override void AssignParentNode(Node n)
        {
            base.AssignParentNode(n);

            OnParentSet();
        }
Esempio n. 45
0
        private bool AddInternal(T item, int hashcode, bool acquireLock)
        {
            while (true)
            {
                var tables = _tables;

                GetBucketAndLockNo(hashcode, out int bucketNo, out int lockNo, tables.Buckets.Length, tables.Locks.Length);

                var resizeDesired = false;
                var lockTaken = false;
                try
                {
                    if (acquireLock)
                        Monitor.Enter(tables.Locks[lockNo], ref lockTaken);

                    // If the table just got resized, we may not be holding the right lock, and must retry.
                    // This should be a rare occurrence.
                    if (tables != _tables)
                    {
                        continue;
                    }

                    // Try to find this item in the bucket
                    Node previous = null;
                    for (var current = tables.Buckets[bucketNo]; current != null; current = current.Next)
                    {
                        Debug.Assert(previous == null && current == tables.Buckets[bucketNo] || previous.Next == current);
                        if (hashcode == current.Hashcode && _comparer.Equals(current.Item, item))
                        {
                            return false;
                        }
                        previous = current;
                    }

                    // The item was not found in the bucket. Insert the new item.
                    Volatile.Write(ref tables.Buckets[bucketNo], new Node(item, hashcode, tables.Buckets[bucketNo]));
                    checked
                    {
                        tables.CountPerLock[lockNo]++;
                    }

                    //
                    // If the number of elements guarded by this lock has exceeded the budget, resize the bucket table.
                    // It is also possible that GrowTable will increase the budget but won't resize the bucket table.
                    // That happens if the bucket table is found to be poorly utilized due to a bad hash function.
                    //
                    if (tables.CountPerLock[lockNo] > _budget)
                    {
                        resizeDesired = true;
                    }
                }
                finally
                {
                    if (lockTaken)
                        Monitor.Exit(tables.Locks[lockNo]);
                }

                //
                // The fact that we got here means that we just performed an insertion. If necessary, we will grow the table.
                //
                // Concurrency notes:
                // - Notice that we are not holding any locks at when calling GrowTable. This is necessary to prevent deadlocks.
                // - As a result, it is possible that GrowTable will be called unnecessarily. But, GrowTable will obtain lock 0
                //   and then verify that the table we passed to it as the argument is still the current table.
                //
                if (resizeDesired)
                {
                    GrowTable(tables);
                }

                return true;
            }
        }
 public static bool InvalidateByNode(Node node)
 {
     return ApplicationStorage.Instance.InvalidateByNodeInternal(node);
 }
Esempio n. 47
0
 public async Task<Measure> GetBatteryLevel()
 {
     var value = (await Node.GetCommandClass<Battery>().Get()).Value;
     return new Measure(value, Unit.Percentage);
 }
Esempio n. 48
0
 public Company GetNodeCompany(Node node)
 {
     return(m_companies.Find(x => x.Name == node.CompanyName));
 }
Esempio n. 49
0
 public async Task<TimeSpan> GetWakeUpInterval()
 {
     return (await Node.GetCommandClass<WakeUp>().GetInterval()).Interval;
 }
Esempio n. 50
0
 public async Task Sleep()
 {
     await Node.GetCommandClass<WakeUp>().NoMoreInformation();
 }
        private Dictionary<ExitPoint, List<Node>> findPathsToEnd(Node endNode, Cluster endCluster)
        {

            return null;
        }
Esempio n. 52
0
 public async Task SetWakeUpInterval(TimeSpan value)
 {
     var controllerNodeID = await Node.Controller.GetNodeId();
     await Node.GetCommandClass<WakeUp>().SetInterval(value, controllerNodeID);
 }
Esempio n. 53
0
        internal void ReloadMapping(RelayNodeClusterDefinition relayNodeClusterDefinition, RelayNodeConfig newConfig, ForwardingConfig forwardingConfig)
        {
            _minimumId = relayNodeClusterDefinition.MinId;
            _maximumId = relayNodeClusterDefinition.MaxId;

            //figure out if anything changed. if it did, rebuild
            bool rebuild = false;

            ushort newLocalZone = newConfig.GetLocalZone();

            if (newLocalZone != _localZone)
            {
                rebuild    = true;
                _localZone = newLocalZone;
            }
            else
            {
                if ((_zoneDefinitions == null && newConfig.RelayNodeMapping.ZoneDefinitions != null) ||
                    (_zoneDefinitions != null && newConfig.RelayNodeMapping.ZoneDefinitions == null) ||
                    (_zoneDefinitions != null && !_zoneDefinitions.Equals(newConfig.RelayNodeMapping.ZoneDefinitions)))
                {
                    rebuild          = true;
                    _zoneDefinitions = newConfig.RelayNodeMapping.ZoneDefinitions;
                }
            }


            int effectiveSize = (!_meInThisCluster ? Nodes.Count : Nodes.Count + 1);

            //if there's a different number of nodes, we definitely have to rebuild
            if (relayNodeClusterDefinition.RelayNodes.Length != effectiveSize)
            {
                if (log.IsInfoEnabled)
                {
                    log.InfoFormat("Number of nodes in a cluster in group {0} changed from {1} to {2}, rebuilding", _nodeGroup.GroupName, effectiveSize, relayNodeClusterDefinition.RelayNodes.Length);
                }
                rebuild = true;
            }
            else
            {
                //if any of the nodes we do have aren't in the config, rebuild
                foreach (Node node in Nodes)
                {
                    if (!relayNodeClusterDefinition.ContainsNode(node.EndPoint.Address, node.EndPoint.Port))
                    {
                        if (log.IsInfoEnabled)
                        {
                            log.InfoFormat("Node {0} is no longer found in its cluster in group {1}, rebuilding.",
                                           node, _nodeGroup.GroupName);
                        }
                        rebuild = true;
                        break;
                    }
                }

                if (!rebuild && _meInThisCluster)
                {
                    if (!relayNodeClusterDefinition.ContainsNode(Me.EndPoint.Address, Me.EndPoint.Port))
                    {
                        if (log.IsInfoEnabled)
                        {
                            log.InfoFormat("Node {0} (this machine) is no longer found in its cluster in group {1}, rebuilding.",
                                           Me, _nodeGroup.GroupName);
                        }
                        rebuild = true;
                    }
                }

                //or if there are any nodes in the config that aren't here, rebuild
                if (!rebuild)
                {
                    foreach (RelayNodeDefinition nodeDefinition in relayNodeClusterDefinition.RelayNodes)
                    {
                        if (!ContainsNode(nodeDefinition))
                        {
                            if (log.IsInfoEnabled)
                            {
                                log.InfoFormat("Node {0} is defined in the new config but does not exist in this cluster in group {1}, rebuilding.",
                                               nodeDefinition, _nodeGroup.GroupName);
                            }
                            rebuild = true;
                            break;
                        }
                    }
                }
            }

            if (rebuild)
            {
                List <Node> newNodes = new List <Node>();

                RelayNodeDefinition meDefinition = newConfig.GetMyNode();
                DispatcherQueue     nodeInQueue, nodeOutQueue;

                if (meDefinition != null)
                {
                    GetMessageQueuesFor(GetMessageQueueNameFor(meDefinition), relayNodeClusterDefinition,
                                        NodeManager.Instance.InMessageDispatcher, NodeManager.Instance.OutMessageDispatcher,
                                        out nodeInQueue, out nodeOutQueue);
                    //Me is in the new config
                    //Either create it new or overwrite the old one
                    Me = new Node(meDefinition, _nodeGroup, this, forwardingConfig,
                                  nodeInQueue, nodeOutQueue);
                }
                else
                {
                    //me is NOT in the new config.
                    Me = null;
                }
                ushort maxDetectedZone = _localZone;
                foreach (RelayNodeDefinition nodeDefinition in relayNodeClusterDefinition.RelayNodes)
                {
                    if (nodeDefinition != meDefinition)
                    {
                        GetMessageQueuesFor(GetMessageQueueNameFor(nodeDefinition), relayNodeClusterDefinition,
                                            NodeManager.Instance.InMessageDispatcher, NodeManager.Instance.OutMessageDispatcher,
                                            out nodeInQueue, out nodeOutQueue);

                        Node node = new Node(nodeDefinition, _nodeGroup, this, forwardingConfig,
                                             nodeInQueue, nodeOutQueue);

                        newNodes.Add(node);

                        if (node.Zone > maxDetectedZone)
                        {
                            maxDetectedZone = node.Zone;
                        }
                    }
                }
                Nodes        = newNodes;
                _nodesByZone = CalculateNodesByZone(Nodes, maxDetectedZone);
                lock (_chooseLock)
                {
                    ChosenNode = null;
                }
                ChosenZoneNodes = new Dictionary <ushort, Node>();
            }
            else
            {
                //just reload the configs to get any new network or queue settings
                bool   hitMe    = false;
                string meString = String.Empty;
                if (Me != null)
                {
                    meString = Me.ToString();
                }
                for (int i = 0; i < relayNodeClusterDefinition.RelayNodes.Length; i++)
                {
                    string definitionString = relayNodeClusterDefinition.RelayNodes[i].Host + ":" + relayNodeClusterDefinition.RelayNodes[i].Port;
                    if (definitionString == meString && Me != null)
                    {
                        hitMe = true;
                        Me.ReloadMapping(relayNodeClusterDefinition.RelayNodes[i], forwardingConfig);
                    }
                    else
                    {
                        Nodes[(hitMe ? i - 1 : i)].ReloadMapping(relayNodeClusterDefinition.RelayNodes[i], forwardingConfig);
                    }
                }
                lock (_chooseLock)
                {
                    ChosenNode = null;
                }
            }
        }
Esempio n. 54
0
        public BatteryDevice(Node node)
            : base(node)
        {
            node.GetCommandClass<WakeUp>().Changed += WakeUp_Changed;

        }
Esempio n. 55
0
        public override IAnalysisSet GetMember(Node node, AnalysisUnit unit, string name)
        {
            IAnalysisSet res = null;

            switch (name)
            {
            case "Any":
                res = AnalysisSet.Empty;
                break;

            case "Callable":
            case "Generic":
            case "Optional":
            case "Tuple":
            case "Union":
            case "Container":
            case "ItemsView":
            case "Iterable":
            case "Iterator":
            case "KeysView":
            case "Mapping":
            case "MappingView":
            case "MutableMapping":
            case "MutableSequence":
            case "MutableSet":
            case "Sequence":
            case "ValuesView":
            case "Dict":
            case "List":
            case "Set":
            case "FrozenSet":
            case "NamedTuple":
            case "Generator":
            case "ClassVar":
                res = new TypingTypeInfo(name, _inner.GetMember(node, unit, name)?.FirstOrDefault());
                break;

            case "AbstractSet": break;

            case "GenericMeta": break;

            // As our purposes are purely informational, it's okay to
            // "round up" to the nearest type. That said, proper protocol
            // support would be nice to implement.
            case "ContextManager": break;

            case "Hashable": break;

            case "Reversible": break;

            case "SupportsAbs": break;

            case "SupportsBytes": res = GetBuiltin(BuiltinTypeId.Bytes); break;

            case "SupportsComplex": res = GetBuiltin(BuiltinTypeId.Complex); break;

            case "SupportsFloat": res = GetBuiltin(BuiltinTypeId.Float); break;

            case "SupportsInt": res = GetBuiltin(BuiltinTypeId.Int); break;

            case "SupportsRound": break;

            case "Sized": break;

            case "Counter": res = Import("collections", "Counter", node, unit); break;

            case "Deque": res = Import("collections", "deque", node, unit); break;

            case "DefaultDict": res = Import("collections", "defaultdict", node, unit); break;

            case "Type": res = GetBuiltin(BuiltinTypeId.Type); break;

            case "ByteString": res = GetBuiltin(BuiltinTypeId.Bytes); break;

            case "AnyStr": res = GetBuiltin(BuiltinTypeId.Unicode).Union(GetBuiltin(BuiltinTypeId.Bytes), canMutate: false); break;

            case "Text": res = GetBuiltin(BuiltinTypeId.Str); break;

            // TypeVar is not actually a synonym for NewType, but it is close enough for our purposes
            case "TypeVar":
            case "NewType": res = GetFunction(node, unit, name, NewType_Call); break;

                // The following are added depending on presence
                // of their non-generic counterparts in stdlib:
                // Awaitable
                // AsyncIterator
                // AsyncIterable
                // Coroutine
                // Collection
                // AsyncGenerator
                // AsyncContextManager
            }

            return(res ?? _inner.GetMember(node, unit, name));
        }
        private Dictionary<ExitPoint, List<Node>> findPathsFromStart(Node startNode, Cluster startCluster)
        {

            return null;
        }
Esempio n. 57
0
		protected override void OnContextMenuOpening(ContextMenuEventArgs e) {
			if (Node != null)
				Node.ShowContextMenu(e);
		}
Esempio n. 58
0
        //Export excel as json
        public byte[] ExportFileAsJson(byte[] file)
        {
            try
            {
                Node startNode = new Node(), aux, lastNode = startNode, endNode = null;
                startNode.name = "ROOT";

                byte[]        bin       = file;
                List <string> excelData = new List <string>();


                //create a new Excel package in a memorystream
                using (MemoryStream stream = new MemoryStream(bin))
                    using (ExcelPackage excelPackage = new ExcelPackage(stream))
                    {
                        //loop all worksheets
                        foreach (ExcelWorksheet worksheet in excelPackage.Workbook.Worksheets)
                        {
                            //loop all rows
                            for (int i = 2; i <= worksheet.Dimension.End.Row; i++)
                            {
                                //loop all columns in a row
                                for (int j = worksheet.Dimension.Start.Column; j <= worksheet.Dimension.End.Column; j++)
                                {
                                    //add the cell data to the List
                                    if (worksheet.Cells[i, j].Value != null)
                                    {
                                        string[] rowReader;
                                        //check if first or second column
                                        if (j % 2 != 0)
                                        {
                                            //split first row by '.'
                                            rowReader = worksheet.Cells[i, j].Value.ToString().Split('.');

                                            for (int k = 0; k < rowReader.Length; k++)
                                            {
                                                if (!lastNode.childs.ContainsKey(rowReader[k]))
                                                {
                                                    aux           = new Node();
                                                    aux.name      = rowReader[k];
                                                    aux.parent    = lastNode;
                                                    aux.height    = aux.parent.height + 1;
                                                    aux.getNumber = lastNode.childsNumber + 1;
                                                    lastNode.childs.Add(aux.name, aux);
                                                    lastNode.childsNumber++;
                                                    lastNode = aux;
                                                    endNode  = aux;
                                                }
                                                else
                                                {
                                                    lastNode = lastNode.childs[rowReader[k]];
                                                    endNode  = lastNode;
                                                }
                                            }

                                            lastNode = startNode;
                                        }
                                        else
                                        {
                                            endNode.value = worksheet.Cells[i, j].Value.ToString();
                                        }
                                    }
                                }
                            }
                        }
                    }

                // Set a variable to the Documents path.
                string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

                BinaryFormatter bf = new BinaryFormatter();
                using (var convertByte = new MemoryStream())
                {
                    string testFail = PrintTree(startNode, true, startNode.childsNumber);
                    Console.WriteLine(testFail);
                    //Convert tree to json in string
                    //Convert the string to json object
                    JObject o = JObject.Parse(PrintTree(startNode, true, startNode.childsNumber));

                    bf.Serialize(convertByte, JsonConvert.SerializeObject(o));
                    return(convertByte.ToArray());
                }
            }
            catch (Exception e)
            {
                throw new Exception("Error! Something went wrong!" + e);
            }
        }
Esempio n. 59
0
 private void MovePlayerAction(Player player, Node node)
 {
     lastValidPosition = player.transform.position;
     player.targetPos  = node.transform.position;
 }
Esempio n. 60
0
 public Node(T item, int hashcode, Node next)
 {
     Item = item;
     Hashcode = hashcode;
     Next = next;
 }