Пример #1
0
        public void QueueCustomers()
        {
            // the customers come in one at a time and get in line
            // waiting for the first teller to show up

            // The first customer
            localBankCustomer.name            = "J P Morgan";
            localBankCustomer.bankingActivity = BankingActivity.deposit.ToString();
            localBankCustomer.accountNumber   = 335445;
            localBankCustomer.amount          = 5600.00F;

            localBankQueue.Enqueue(localBankCustomer);

            // second customer
            localBankCustomer.name            = "Butch Cassidy";
            localBankCustomer.bankingActivity = BankingActivity.transferFunds.ToString();
            localBankCustomer.accountNumber   = 555445;
            localBankCustomer.amount          = 3500.00F;

            localBankQueue.Enqueue(localBankCustomer);

            // third customer
            localBankCustomer.name            = "John Dillinger";
            localBankCustomer.bankingActivity = BankingActivity.withdrawl.ToString();
            localBankCustomer.accountNumber   = 12345;
            localBankCustomer.amount          = 2000.00F;

            localBankQueue.Enqueue(localBankCustomer);

            // see how many people are in line
            Console.WriteLine(" ");
            Console.WriteLine("Count of Items in the Queue at the start :" + localBankQueue.Count);
            Console.WriteLine(" ");
            // now we want to remove items from the queue so we can work on them
            // the items are an object so we need to recognize that
            // put the queue data in the localBankcustomer structure

            localBankCustomer = (BankCustomer)localBankQueue.Dequeue();
            // write out
            Console.WriteLine("Name: " + localBankCustomer.name);
            Console.WriteLine("Activity: " + localBankCustomer.bankingActivity);
            Console.WriteLine("Account Number: " + localBankCustomer.accountNumber);
            Console.WriteLine("Amount: " + localBankCustomer.amount.ToString());
            Console.WriteLine("Count of Items in the Queue after first Dequeue:" + localBankQueue.Count);
            Console.WriteLine("----------------------------------------------------------------");
            Console.WriteLine(" ");
            // now we can go throught the reamainder of the bank's sustomers using a loop
            do
            {
                localBankCustomer = (BankCustomer)localBankQueue.Dequeue();
                // write out
                Console.WriteLine("Name: " + localBankCustomer.name);
                Console.WriteLine("Activity: " + localBankCustomer.bankingActivity);
                Console.WriteLine("Account Number: " + localBankCustomer.accountNumber);
                Console.WriteLine("Amount: " + localBankCustomer.amount.ToString());
                Console.WriteLine("Count of Items in the Queue after Dequeue: " + localBankQueue.Count);
                Console.WriteLine("----------------------------------------------------------------");
                Console.WriteLine(" ");
            } while (localBankQueue.Count != 0);
        }
Пример #2
0
        public static Frame Create(object val, object expr, Frame context)
        {
            Frame f;

            if (_freeList.Count > 0)
            {
                f          = (Frame)_freeList.Dequeue();
                f.Expr     = expr;
                f.Value    = val;
                f.ValueRib = context.ValueRib;
                f.Env      = context.Env;
                f.Context  = context.Context;
            }
            else
            {
                f = new Frame(val, expr, context);
            }

            if (!context.Captured)
            {
                _freeList.Enqueue(context);
            }

            return(f);
        }
Пример #3
0
        // https://youtu.be/MjCjQCCtmcE
        static void Main(string[] args)
        {
            System.Collections.Queue miQueue = new System.Collections.Queue();
            // Addicionamos objetos
            miQueue.Enqueue("Manzana");
            miQueue.Enqueue("Freza");
            miQueue.Enqueue("Pera");

            // Interactuamos
            Show.Show(miQueue);

            // Obtener el primer objeto y sacarlo del Queue
            Console.WriteLine("DeQueue {0}", miQueue.Dequeue());
            Console.WriteLine("DeQueue {0}", miQueue.Dequeue());
            Show.Show(miQueue, "Despues DeQueue");

            // Add Elementos
            miQueue.Enqueue("Limon");
            miQueue.Enqueue("Mango");
            miQueue.Enqueue("Ciruela");

            //  Obtener el primer objeto y sin sacarlo del Queue
            Console.WriteLine("Peek {0}", miQueue.Peek());

            Show.Show(miQueue, "Despues Peek");

            // Conteo de Objeto
            Console.WriteLine("Numero de Objetos {0}\n", miQueue.Count);

            // Verifica si existe un objeto
            Console.WriteLine("Hay Mango {0}", miQueue.Contains("Mango"));
            Console.WriteLine("Hay Manzana {0}", miQueue.Contains("Manzana"));

            System.Console.ReadKey();
        }
Пример #4
0
 public static void PackageShiftAndGetNew(ref byte[] raw, int index, ref System.Collections.Queue RecQueue)
 {
     if (index == 0)
     {
         for (int i = 0; i < raw.Length; i++)
         {
             raw[i] = Convert.ToByte(RecQueue.Dequeue());
         }
     }
     else if (index > 0)
     {
         Array.Copy(raw, index, raw, 0, raw.Length - index);
         for (int i = index; i > 0; i--)
         {
             raw[raw.Length - i] = Convert.ToByte(RecQueue.Dequeue());
         }
     }
     else
     {
         for (int i = 0; i < raw.Length; i++)
         {
             raw[i] = Convert.ToByte(RecQueue.Dequeue());
         }
     }
 }
Пример #5
0
        public string BreadthFirst(char start)                                  //remove from fifo visit neighbors
        {
            ResetVisited();                                                     // reset visited
            System.Text.StringBuilder output = new System.Text.StringBuilder(); // make string
            Node tempNode;                                                      // make tempnode

            System.Collections.Queue tempFifo = new System.Collections.Queue(); // make queue fifo
            tempFifo.Enqueue(nodeList[FindNode(start)]);                        // add node to que
            tempNode = (Node)tempFifo.Dequeue();                                //set node to tempnode.
            Edge ptr = tempNode.connections;

            do
            {
                if (tempFifo.Count != 0)
                {
                    tempNode = (Node)tempFifo.Dequeue();
                    ptr      = tempNode.connections; // set ptr equal to this nodes first edge
                }

                if (ptr != null) // check if visited or end of ptr list
                {
                    while (ptr != null)
                    {
                        if (nodeList[ptr.endIndex].visited != true)
                        {
                            nodeList[ptr.endIndex].visited = true;
                            output.Append(tempNode.name + "-" + nodeList[ptr.endIndex].name + "[" + ptr.weight + "] "); // append output str, startchar - next char in ptr
                            tempFifo.Enqueue(nodeList[ptr.endIndex]);
                        }
                        ptr = ptr.next; // move to next one.
                    }
                }
            } while (tempFifo.Count != 0); // while fifo is not empty
            return(output.ToString());     // return finished string
        }
Пример #6
0
 private void ExecutionAcceptKeystroke()
 {
     // Send the key that was just typed (in pause mode) to the parser for execution.
     // TODO: But then the two parsers get desynchronized???
     // TODO: But what if the current message is not a keystroke?
     upParser.Parse(((KeystrokeMessage)messageQueue.Dequeue()).Tag);
 }
Пример #7
0
        public void OnSegmentDone(object state)
        {
            pastSegmentThroughput.Enqueue(segmentAmount);
            totalSegmentQueueAmount += segmentAmount;

            if (pastSegmentThroughput.Count > 5)
            {
                totalSegmentQueueAmount -= (int)pastSegmentThroughput.Dequeue();
            }


            segmentAmount = 0;

            if (totalSegmentQueueAmount > 0)
            {
                actualRate = ((float)totalSegmentQueueAmount) / 5000.0f;
            }
            else
            {
                actualRate = 0.0f;
            }

            if (RateChange != null)
            {
                RateChange(actualRate);
            }
        }
Пример #8
0
        /// <summary>
        /// Parse the given content with the given search terms. Every search term
        /// will be processed in it's own thread to increase
        /// overall search performance.
        /// </summary>
        /// <param name="SearchTerms"></param>
        /// <param name="Content"></param>
        /// <param name="FileName"></param>
        /// <param name="FileFolder"></param>
        /// <returns></returns>
        /// <remarks>This method split the search term list into new lists with only
        /// one item per list. This single item lists are passed to a new threaded
        /// SimpleRegExCrawler class.</remarks>
        /// <seealso cref="SimpleRegExCrawler"/>
        public List <Finding> Crawl(List <RegExSearchTerm> SearchTerms, string Content, string FileName, string FileFolder)
        {
            resultQueue = new System.Collections.Queue();
            var threadCount = SearchTerms.Count;

            manualEvents = new ManualResetEvent[threadCount];


            foreach (var searchTerm in SearchTerms)
            {
                var searchTermIndex = SearchTerms.IndexOf(searchTerm);
                manualEvents[searchTermIndex] = new ManualResetEvent(false);
                ThreadPool.QueueUserWorkItem(DoWork, new object[] { searchTerm, Content, FileName, FileFolder, manualEvents[searchTermIndex] });
            }
            System.Diagnostics.Trace.TraceInformation(String.Format("Wait for threads."));
            WaitHandle.WaitAll(manualEvents);
            System.Diagnostics.Trace.TraceInformation(String.Format("Threads finished."));
            var resultList = new List <Finding>();

            //for (int i = 0; i <= resultQueue.Count; i++)
            while (resultQueue.Count > 0)
            {
                var dequed = resultQueue.Dequeue();
                resultList.AddRange(dequed as List <Finding>);
            }
            return(resultList);
        }
Пример #9
0
        public static string GetDirectory(Uri taxonomy, string searchDirectory, string defaultDirectory = "")
        {
            if (taxonomy == null)
            {
                throw new NullReferenceException();
            }

            string search = taxonomy.Host;

            int parts = InstanceOfChar(search, '.');

            var list = new System.Collections.Queue();

            // Take the host as it is.
            list.Enqueue(search);


            // Remove the sub-domain.
            //var strippedSubDomain = search.Substring(search.


            while (list.Count > 0)
            {
                var path = Path.Combine(searchDirectory, list.Dequeue().ToString());
                if (Directory.Exists(path))
                {
                    return(path);
                }
            }

            return(defaultDirectory);
        }
Пример #10
0
        /// <summary>
        /// Starts the main loop.
        /// </summary>
        public void Run()
        {
            // Start the main loop and continue until it's stopped
            m_running = true;
            while (m_running)
            {
                // Wait on Invoke or Stop methods to be called
                m_syncEvent.WaitOne();

                while (m_methodQueue.Count != 0)
                {
                    MethodDelegate method = (MethodDelegate)m_methodQueue.Dequeue();

                    try
                    {
                        // Perform the action
                        method();
                    }
                    catch (Exception e)
                    {
                        String msg = e.Message + " " + e.InnerException + " " + e.StackTrace;

                        // Send event
                        Safir.Logging.SendSystemLog(Safir.Logging.Severity.Critical,
                                                    "Unhandled Exception in MainLoop: " + msg);

                        // Terminate the application
                        //Instances.SelfInstance.MainModule.FatalError();
                    }
                }

                m_syncEvent.Reset();
            }
        }
Пример #11
0
        /// <summary>
        /// chart update thread
        /// </summary>
        private void OnChartUpdate()
        {
            clsBlueTooth.BtData data;
            int iXStep = 1; //milSec
            int i      = 0;

            double d_PreRol = -1;

            while (true)
            {
                lock (qBluetoothData.SyncRoot)
                {
                    if (qBluetoothData.Count > 0)
                    {
                        data = (clsBlueTooth.BtData)qBluetoothData.Dequeue();
                        UpdateChart(data, iXStep);

                        myData.dConsumption += data.Consumption / 10000;
                        myData.dSave        += data.Save / 10000;
                        DeUpdateLabelText(en_LabelText.EN_Consumption, myData.dConsumption.ToString("0.00"));
                        DeUpdateLabelText(en_LabelText.EN_Saving, myData.dSave.ToString("0.00"));

                        //if (i == 7) i = 0;
                        UpdateImagePeopleImage(d_PreRol, data.angle_Rol);
                        DeUpdateProgress(en_ProgressBar.PGB_Evaluate, (int)(myData.dConsumption / 10));
                        DeUpdateProgress(en_ProgressBar.PGB_Intensity, (int)data.Intensity);
                        DeUpdateProgress(en_ProgressBar.PGB_Power, (int)data.power);

                        d_PreRol = data.angle_Rol;
                    }
                }
                Thread.Sleep(5);
            }
        }
Пример #12
0
        public int NodesMin(int index_from, int index_to)
        {
            int[] status = new int[countCS];
            for (int i = 0; i < countCS; i++)
            {
                status[i] = 0;
            }

            int curr = index_from;

            status[curr] = 1;      // вершина переглянута
            System.Collections.Queue och = new System.Collections.Queue();
            och.Enqueue(curr);

            while (och.Count != 0)
            {
                curr = Convert.ToInt32(och.Dequeue());
                for (int i = 0; i < countCS; i++)
                {
                    if (matrixCS[curr, i] != 0 && status[i] == 0)
                    {
                        status[i] = 1;          // відвідали вершину
                        och.Enqueue(i);
                        if (i == index_to)
                        {
                            node_min_list.Insert(0, TopListCSNew[curr].id);
                            return(curr);
                        }
                    }
                }
            }
            return(curr);
        }
        ///* this function returns true if ping was success, and false if ping was not successful */
        //bool PingDestinationIPAddress(UInt32 destinationIPAddress)
        //{
        //    byte[] restOfHeader = new byte[4];
        //    UInt16 identifier = 0x0000;
        //    UInt16 sequenceNumber = _nextEchoRequestSequenceNumber++;
        //    restOfHeader[0] = (byte)((identifier << 8) & 0xFF);
        //    restOfHeader[1] = (byte)(identifier & 0xFF);
        //    restOfHeader[2] = (byte)((sequenceNumber << 8) & 0xFF);
        //    restOfHeader[3] = (byte)(sequenceNumber & 0xFF);
        //    /* for data, we will include a simple 8-character array.  we could alternatively send a timestamp, etc. */
        //    byte[] data = System.Text.Encoding.UTF8.GetBytes("abcdefgh");

        //    EchoRequest echoRequest = new EchoRequest(destinationIPAddress, identifier, sequenceNumber, data);
        //    lock (_outstandingEchoRequests)
        //    {
        //        _outstandingEchoRequests.Add(echoRequest);
        //    }

        //    bool echoReplyReceived = false;
        //    try
        //    {
        //        Int64 timeoutInMachineTicks = 1 * TimeSpan.TicksPerSecond; /* wait up to one second for ping to be sent */

        //        /* send ICMP echo request */
        //        SendIcmpMessage(destinationIPAddress, IcmpMessageType.Echo, IcmpMessageCode.None, restOfHeader, data, timeoutInMachineTicks);

        //        /* wait for ICMP echo reply for up to one second */
        //        echoReplyReceived = echoRequest.WaitForResponse(1000);

        //    }
        //    finally
        //    {
        //        /* remove ICMP request from collection */
        //        lock (_outstandingEchoRequests)
        //        {
        //            _outstandingEchoRequests.Remove(echoRequest);
        //        }
        //    }

        //    /* if we did not get a match, return false */
        //    return echoReplyReceived;
        //}

        void SendIcmpMessagesThread()
        {
            while (true)
            {
                _sendIcmpMessagesInBackgroundEvent.WaitOne();

                // if we have been disposed, shut down our thread now.
                if (_isDisposed)
                {
                    return;
                }

                while ((_sendIcmpMessagesInBackgroundQueue != null) && (_sendIcmpMessagesInBackgroundQueue.Count > 0))
                {
                    try
                    {
                        IcmpMessage icmpMessage = (IcmpMessage)_sendIcmpMessagesInBackgroundQueue.Dequeue();
                        SendIcmpMessage(icmpMessage.DestinationIPAddress, icmpMessage.IcmpMessageType, icmpMessage.IcmpMessageCode, icmpMessage.RestOfHeader, icmpMessage.Data, Int64.MaxValue);
                    }
                    catch (InvalidOperationException)
                    {
                        // reply queue was empty
                    }

                    // if we have been disposed, shut down our thread now.
                    if (_isDisposed)
                    {
                        return;
                    }
                }
            }
        }
Пример #14
0
        /// <summary>
        /// Iterates through the given file list an spawn a new thread per file for peforming the RegEx search.
        /// </summary>
        /// <param name="FileList"></param>
        /// <param name="SearchTermList"></param>
        /// <param name="Crawler"></param>
        /// <returns></returns>
        public List <Finding> Iterate(List <FileInfo> FileList, List <RegExSearchTerm> SearchTermList, IRegExCrawler Crawler)
        {
            var start = DateTime.Now;

            resultQueue = new System.Collections.Queue();
            var chunkedFileLists = ChunkBy(FileList, maxThreads);

            foreach (var chunkedList in chunkedFileLists)
            {
                SpawnThreads(chunkedList, SearchTermList, Crawler);
            }
            var duration = DateTime.Now - start;

            System.Diagnostics.Trace.TraceInformation(String.Format("Duration: {0}:{1}:{2} ", duration.Hours, duration.Minutes, duration.Seconds));

            var resultList = new List <Finding>();

            //for (int i = 0; i <= resultQueue.Count; i++)
            while (resultQueue.Count > 0)
            {
                System.Diagnostics.Trace.TraceInformation(String.Format("ResultQueueCount: {0} ", resultQueue.Count));
                resultList.AddRange((List <Finding>)resultQueue.Dequeue());
            }

            System.Diagnostics.Trace.TraceInformation(String.Format("ResultListCount: {0} ", resultList.Count));
            return(resultList);
        }
        void SendArpGenericThread()
        {
            while (true)
            {
                _sendArpGenericInBackgroundEvent.WaitOne();

                // if we have been disposed, shut down our thread now.
                if (_isDisposed)
                {
                    return;
                }

                while ((_sendArpGenericInBackgroundQueue != null) && (_sendArpGenericInBackgroundQueue.Count > 0))
                {
                    try
                    {
                        ArpGenericData arpGenericData = (ArpGenericData)_sendArpGenericInBackgroundQueue.Dequeue();
                        SendArpGeneric(arpGenericData.DestinationEthernetAddress, arpGenericData.ArpOperaton, arpGenericData.TargetPhysicalAddress, arpGenericData.TargetProtocolAddress, Int64.MaxValue);
                    }
                    catch (InvalidOperationException)
                    {
                        // reply queue was empty
                    }

                    // if we have been disposed, shut down our thread now.
                    if (_isDisposed)
                    {
                        return;
                    }
                }
            }
        }
Пример #16
0
 // Poll the queue.
 private void PollQueue()
 {
     while (activeStreams.Count > 0)
     {
         queuedItem.WaitOne();
         while (queue.Count > 0)
         {
             StreamData data = (StreamData)queue.Dequeue();
             if (data.end)
             {
                 lock (activeStreams)
                 {
                     activeStreams.Remove(data.handle);
                 }
             }
             if (DataReceived != null)
             {
                 DataReceived(data);
             }
         }
     }
     if (Complete != null)
     {
         Complete();
     }
 }
Пример #17
0
        private static void bfs(List <Node> node, int sourceNode, int N)
        {
            System.Collections.Queue q = new System.Collections.Queue(N);
            q.Enqueue(sourceNode);
            int[] visited         = new int[N + 1];
            int[] levelFromSource = new int[N + 1];

            int level = 0;

            visited[sourceNode]         = 1;
            levelFromSource[sourceNode] = level;

            while (q.Count != 0)
            {
                //Dequeue the element
                int n = Convert.ToInt32(q.Dequeue());// Remove first element

                //get all node associated with this node which are not visisted yet
                var childNodes = node[n];
                level = levelFromSource[n] + 1;

                for (int i = 0; i < childNodes.Next.Count; i++)
                {
                    if (visited[childNodes.Next[i]] != 1)// if not visited yet
                    {
                        q.Enqueue(childNodes.Next[i]);
                        visited[childNodes.Next[i]]         = 1;
                        levelFromSource[childNodes.Next[i]] = level;
                    }
                }
            }
            Console.WriteLine(levelFromSource[N]);
        }
Пример #18
0
        private void DoTask()
        {
            new System.Threading.Tasks.TaskFactory().StartNew(new Action(() =>
            {
                SetText("视频监控已启动...");
                while (true)
                {
                    if (_queue.Count > 0)
                    {
                        var task = _queue.Dequeue() as VideoTask;
                        if (task == null)
                        {
                            continue;
                        }

                        SetText("启动任务-{0}", task.VideoUrl);

                        task.UploadVideo();
                    }

                    System.Threading.Tasks.Task.Delay(5000).Wait();
                    SetText("视频监控在运行...");
                }
            }));
        }
Пример #19
0
 /// <summary>
 /// Unregisters this instance.
 /// </summary>
 private static void Unregister()
 {
     lock (CurrentlyVisible)
     {
         CurrentlyVisible.Dequeue();
     }
 }
Пример #20
0
        /// <summary>
        /// Wait for the semaphore to be signalled.
        /// </summary>
        /// <param name="timeout">Millisecond time-out - return if time-out expires</param>
        /// <returns>bool - returns true if semaphore signalled within time-out or false otherwise.</returns>
        public bool Wait(uint timeout)
        {
            // Ensure that we have a sensible minimum timeout
            // 0 = no timeout
            if ((timeout != 0) &&
                (timeout < _pollInterval))
            {
                // timeout must be at least 1 poll interval
                timeout = _pollInterval;
            }
            uint localTimeout = timeout;

            bool signalled = true;

            while (_queue.Count == 0)
            {
                System.Threading.Thread.Sleep((int)_pollInterval);

                if (timeout != 0)
                {
                    // Decrement the time-out
                    localTimeout -= _pollInterval;
                    if (localTimeout <= 0)
                    {
                        // If timeout expired then return false
                        return(false);
                    }
                }
            }
            _queue.Dequeue();

            return(signalled);
        }
Пример #21
0
        public static void CreateReplicationLog(MySqlConnection conn, System.Collections.Queue sqlCommands, ref string errorString)
        {
            if (sqlCommands.Count == 0)
            {
                return;
            }
            MySqlCommand cmd;
            QueryInfo    query;
            string       strSql;

            do
            {
                query   = (QueryInfo)sqlCommands.Dequeue();
                strSql  = "INSERT INTO REPLICATIONLOG(DBCODE,ID,BATCHID,OBJECTTYPE,OBJECTNAME,COMMANDTYPE,COMMANDSTRING)";
                strSql += " VALUES ('" + query.DBCode + "','" + query.ID + "','" + query.BatchID + "','" + query.ObjectType + "','" + query.ObjectName + "','";
                strSql += query.CommandType + "',\"" + query.CommandString + "\"" + ")";
                try
                {
                    cmd             = new MySqlCommand(strSql, conn);
                    cmd.CommandType = System.Data.CommandType.Text;
                    cmd.ExecuteNonQuery();
                }
                catch (MySqlException e)
                {
                    errorString = e.Message;
                }
            }while (sqlCommands.Count != 0);
        }
Пример #22
0
 // Our page has finished rendering so lets output the JavaScript to produce the alert's
 private static void ExecutingPage_Unload(object sender, EventArgs e)
 {
     // Get our message queue from the hashtable
     System.Collections.Queue queue = (System.Collections.Queue)m_executingPages[HttpContext.Current.Handler];
     if (queue != null)
     {
         System.Text.StringBuilder sb = new System.Text.StringBuilder();
         // How many messages have been registered?
         int iMsgCount = queue.Count;
         // Use StringBuilder to build up our client slide JavaScript.
         sb.Append("<script language='javascript'>");
         // Loop round registered messages
         string sMsg;
         while (iMsgCount-- > 0)
         {
             sMsg = (string)queue.Dequeue();
             sMsg = sMsg.Replace("\n", "\\n");
             sMsg = sMsg.Replace("\"", "'");
             sb.Append(@"alert( """ + sMsg + @""" );");
         }
         // Close our JS
         sb.Append(@"</script>");
         // Were done, so remove our page reference from the hashtable
         m_executingPages.Remove(HttpContext.Current.Handler);
         // Write the JavaScript to the end of the response stream.
         HttpContext.Current.Response.Write(sb.ToString());
     }
 }
 private void run()
 {
     while (keepRunning)
     {
         if (RunningProcesses < MaxRunningProcesses && processQueue.Count > 0)
         {
             ProcessInfo  processInfo = (ProcessInfo)processQueue.Dequeue();
             AgentProcess newProcess  = new AgentProcess();
             newProcess.Application    = processInfo.Application;
             newProcess.Arguments      = processInfo.Arguments;
             newProcess.MaxMemoryUsage = MaxPerProcessMemoryUsage;
             newProcess.MaxRuntime     = MaxPerProcessRuntime;
             newProcess.Priority       = ProcessPriority;
             newProcess.VerboseLogging = VerboseLogging;
             newProcess.Started       += new EventHandler(Process_Started);
             newProcess.Stopped       += new EventHandler(Process_Stopped);
             newProcess.Stopping      += new EventHandler(Process_Stopping);
             newProcess.Start();
         }
         for (int i = runningProcesses.Count - 1; i > -1; i--)
         {
             try
             {
                 AgentProcess p = (AgentProcess)runningProcesses[i];
                 if (!p.IsHealthy)
                 {
                     OnProcessNotHealthy(p);
                 }
             }
             catch {}
         }
         System.Threading.Thread.Sleep(1000);
     }
 }
Пример #24
0
 /// <summary>
 /// 添加一个消息
 /// </summary>
 public void PushData(Message ci)
 {
     mutex.WaitOne();
     if (BufferSize > 0 && BufferSize <= cmdq.Count)
     {
         Message c = cmdq.Peek() as Message;
         if (c != null && c.type == MsgQueue.msgtype_Send)
         {
             LostCount++;
             cmdq.Dequeue();
         }
     }
     cmdq.Enqueue(ci);
     evt.Set();
     mutex.ReleaseMutex();
 }
Пример #25
0
        // FIFO (First In, First Out)
        public Queue()
        {
            Console.WriteLine("=> Queue");

            System.Collections.Queue numbers = new System.Collections.Queue();

            foreach (int number in new int[] { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21 })
            {
                numbers.Enqueue(number);
                Console.WriteLine("Number: {0} has joined the queue.", number); // entra na fila
            }

            Console.Write("Iterator: ");
            foreach (int number in numbers)
            {
                Console.Write("{0} ", number);
            }

            Console.WriteLine();

            while (numbers.Count > 0)
            {
                int value = (int)numbers.Dequeue();
                Console.WriteLine("Number: {0} has left the queue.", value);
            }

            Console.WriteLine();
        }
Пример #26
0
        /* ------------------------------------- Private Methods ----------------------------------- */


        /// <summary> Removes the first element. Returns null if no elements in queue.
        /// Always called with add_mutex locked (we don't have to lock add_mutex ourselves)
        /// </summary>
        protected object removeInternal(System.Collections.Queue queue)
        {
            object obj = null;

            lock (mutex)
            {
                int count = queue.Count;
                if (count > 0)
                {
                    obj = queue.Dequeue();
                }
                else
                {
                    return(null);
                }

                size--;
                if (size < 0)
                {
                    size = 0;
                }

                if (peekInternal() == endMarker)
                {
                    closed = true;
                }
            }

            return(obj);
        }
Пример #27
0
        /// <summary>
        /// The script for recording new .wav samples demands the next arguments:
        /// directoryPath of the output .wav files,
        /// secondsToRecordPerWavFile,
        /// </summary>
        public void Record()
        {
            string recordsDirectoryName = $"{Path.DirectorySeparatorChar}{mRecordsDirectory}";

            string[] argument = new string[]
            {
                recordsDirectoryName,
                RecordLengthInSec.ToString()
            };

            //ProcessExecutor.ExecuteProcess(RECORD_EXE_NAME, argument); // TODO uncomment.

            // TODO delete from here.
            string path = @"C:\Users\Dor Shaar\Desktop\splitted_cut_DorMaximovPopcorn";

            string[] files = Directory.GetFiles(path);
            System.Collections.Queue queue = new System.Collections.Queue(files);

            System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
            stopwatch.Start();
            while (queue.Count > 0)
            {
                if (stopwatch.ElapsedMilliseconds >= 3000)
                {
                    FilePath filePath = FilePath.CreateFilePath((string)queue.Dequeue());
                    File.Move(filePath.FileFullPath, $@"{mRecordsDirectory}\{filePath.Name}");
                    System.Console.WriteLine($"Copied:{filePath.FileFullPath}");
                    stopwatch.Restart();
                }
            }

            // TODO delete to here.
        }
 public object Pop()
 {
     lock (mQueue)
     {
         WcfTcpClient <T> result;
         if (mQueue.Count > 0)
         {
             result = (WcfTcpClient <T>)mQueue.Dequeue();
         }
         else
         {
             result = createClient();
         }
         result.Reset();
         return(result);
     }
 }
Пример #29
0
 static public ASTPair GetInstance()
 {
     if (instancePool_.Count > 0)
     {
         return((ASTPair)instancePool_.Dequeue());
     }
     return(new ASTPair());
 }
 /// <summary>
 /// Refreshes the asset database on the main thread when refreshAssetDatabaseComplete
 /// is set.
 /// </summary>
 private static void PumpUpdateQueue()
 {
     while (updateQueue.Count > 0)
     {
         var action = (System.Action)updateQueue.Dequeue();
         action();
     }
 }
Пример #31
0
 public static void BreathFirstSearch(TreeAndGraph.BinaryTreeNode root)
 {
     System.Collections.Queue q = new System.Collections.Queue();
     q.Enqueue(root);
     while (q.Count!=0)
     {
         TreeAndGraph.BinaryTreeNode btn = (TreeAndGraph.BinaryTreeNode)q.Dequeue();
         System.Console.WriteLine(btn.Data);
         if (btn.LeftNode != null)
         {
             q.Enqueue(btn.LeftNode);
         }
         if (btn.RightNode != null)
         {
             q.Enqueue(btn.RightNode);
         }
     }
 }
Пример #32
0
        public void SearchKeyword(SearchTransaction searchTransaction)
        {
            queueKeywords = new System.Collections.Queue();

            try
            {

                //pour chaque keyword on lance le search dans un thread séparé
                foreach (Keyword k in searchTransaction.Keywords)
                {
                    KeywordCollection keyword = null;
                    SearchTransaction searchTrans = null;
                    keyword = new KeywordCollection();
                    keyword.Add(k);
                    searchTrans = new SearchTransaction(searchTransaction.IdTransaction, keyword, searchTransaction.MinFileFromPeerFilter, searchTransaction.IpAcceptRangeCollection);
                    queueKeywords.Enqueue(searchTrans);
                }

                // regrouping of results for this transaction
                // will raise the CompletResultHandler event when we received one results for each keyword
                G2SearchResultRegrouping searchRegrouping = new G2SearchResultRegrouping(searchTransaction, searchTransaction.Keywords.Count, false);
                searchRegrouping.CompletResult += new CompletResultHandler(searchRegrouping_CompletResult);
                searchResultRegroupingKeyword_.Add(searchRegrouping);

                while (queueKeywords.Count > 0)
                {

                    SearchTransaction srchTrans = (SearchTransaction)queueKeywords.Dequeue();

                    G2Log.Write("Starting Transaction - Keyword :" + srchTrans.Keywords[0].KeywordName.ToString());
                    searchManager.NewSearch(srchTrans);

                    // on attends 30sec ?????????????????????????
                    //System.Threading.Thread.Sleep(30000);
                }
            }
            catch
            {
               G2Log.Write("Erreur niveau manager.....");
            }
        }
Пример #33
0
        static void TerminalServertask()
        {
            System.Collections.Queue que = new System.Collections.Queue(10);
            while (true)
            {

                try
                {
                    string str = System.Console.ReadLine();
                    foreach (TcpClient tcp in TcpClients)
                    {
                        try
                        {
                            System.IO.StreamWriter sw = new System.IO.StreamWriter(tcp.GetStream(),System.Text.Encoding.Unicode);
                            sw.WriteLine(str);
                            sw.Flush();
                        }
                        catch (Exception)
                        {
                            que.Enqueue(tcp);
                        }
                    }

                    for (int i = 0; i < que.Count; i++)
                    {
                        TcpClient client = (TcpClient)que.Dequeue();
                        TcpClients.Remove(client);
                        client.Close();

                    }

                }
                catch
                {
                    ;
                }
            }
        }
Пример #34
0
        /// <summary>
        /// Iterates through the given file list an spawn a new thread per file for peforming the RegEx search.
        /// </summary>
        /// <param name="FileList"></param>
        /// <param name="SearchTermList"></param>
        /// <param name="Crawler"></param>
        /// <returns></returns>
        public List<Finding> Iterate(List<FileInfo> FileList, List<RegExSearchTerm> SearchTermList, IRegExCrawler Crawler)
        {
            var start = DateTime.Now;
            resultQueue = new System.Collections.Queue();
            var chunkedFileLists = ChunkBy(FileList, maxThreads);
            foreach (var chunkedList in chunkedFileLists)
            {
                SpawnThreads(chunkedList, SearchTermList, Crawler);
            }
            var duration = DateTime.Now - start;
            System.Diagnostics.Trace.TraceInformation(String.Format("Duration: {0}:{1}:{2} ", duration.Hours, duration.Minutes, duration.Seconds));

            var resultList = new List<Finding>();
            //for (int i = 0; i <= resultQueue.Count; i++)
            while (resultQueue.Count > 0)
            {
                System.Diagnostics.Trace.TraceInformation(String.Format("ResultQueueCount: {0} ", resultQueue.Count));
                resultList.AddRange((List<Finding>)resultQueue.Dequeue());
            }

            System.Diagnostics.Trace.TraceInformation(String.Format("ResultListCount: {0} ", resultList.Count));
            return resultList;
        }
Пример #35
0
        /// <summary>
        /// Parse the given content with the given search terms. Every search term
        /// will be processed in it's own thread to increase 
        /// overall search performance.
        /// </summary>
        /// <param name="SearchTerms"></param>
        /// <param name="Content"></param>
        /// <param name="FileName"></param>
        /// <param name="FileFolder"></param>
        /// <returns></returns>
        /// <remarks>This method split the search term list into new lists with only
        /// one item per list. This single item lists are passed to a new threaded
        /// SimpleRegExCrawler class.</remarks>
        /// <seealso cref="SimpleRegExCrawler"/>
        public List<Finding> Crawl(List<RegExSearchTerm> SearchTerms, string Content, string FileName, string FileFolder)
        {
            resultQueue = new System.Collections.Queue();
            var threadCount = SearchTerms.Count;
            manualEvents = new ManualResetEvent[threadCount];

            foreach (var searchTerm in SearchTerms)
            {
                var searchTermIndex = SearchTerms.IndexOf(searchTerm);
                manualEvents[searchTermIndex] = new ManualResetEvent(false);
                ThreadPool.QueueUserWorkItem(DoWork, new object[] { searchTerm, Content, FileName, FileFolder, manualEvents[searchTermIndex]});
            }
            System.Diagnostics.Trace.TraceInformation(String.Format("Wait for threads."));
            WaitHandle.WaitAll(manualEvents);
            System.Diagnostics.Trace.TraceInformation(String.Format("Threads finished."));
            var resultList = new List<Finding>();
            //for (int i = 0; i <= resultQueue.Count; i++)
            while(resultQueue.Count > 0)
            {
                var dequed = resultQueue.Dequeue();
                resultList.AddRange(dequed as List<Finding>);
            }
            return resultList;
        }
        //---------------------------------------------------------------------
        ///<summary>
        ///Spread from Epicenters to outbreak zone using either a fixed radius method
        ///or a percolation method with variable neighborhood sizes.
        ///</summary>
        //---------------------------------------------------------------------
        private static void SpreadEpicenters(IAgent agent,
                                            List<Location> iSites,
                                            int BDAtimestep)
        {
            //PlugIn.ModelCore.UI.WriteLine("Spreading to New Epicenters.  There are {0} initiation sites.", iSites.Count);

            if(iSites == null)
                PlugIn.ModelCore.UI.WriteLine("ERROR:  The newSiteList is empty.");
            int dispersalDistance = agent.DispersalRate * BDAtimestep;

            foreach(Location siteLocation in iSites)
            {
                Site initiationSite = PlugIn.ModelCore.Landscape.GetSite(siteLocation);

                if(agent.DispersalTemp == DispersalTemplate.MaxRadius)
                {

                    foreach (RelativeLocation relativeLoc in agent.DispersalNeighbors)
                    {
                        Site neighbor = initiationSite.GetNeighbor(relativeLoc);
                        if (neighbor != null && neighbor.IsActive)
                            agent.OutbreakZone[neighbor] = Zone.Newzone;
                    }
                }
                if(agent.DispersalTemp != DispersalTemplate.MaxRadius)
                {
                    //PlugIn.ModelCore.UI.WriteLine("   Begin Percolation Spread to Neighbors.");
                    //Queue<Site> sitesToConsider = new Queue<Site>();
                    System.Collections.Queue sitesToConsider = new System.Collections.Queue();
                    sitesToConsider.Enqueue(initiationSite);

                    while (sitesToConsider.Count > 0 )
                    {
                        //PlugIn.ModelCore.UI.WriteLine("   There are {0} neighbors being processed.", sitesToConsider.Count);

                        Site site = (Site)sitesToConsider.Dequeue();
                        agent.OutbreakZone[site] = Zone.Newzone;

                        foreach (RelativeLocation relativeLoc in agent.DispersalNeighbors)
                        {
                            Site neighbor = site.GetNeighbor(relativeLoc);

                            //Do not spread to inactive neighbors:
                            if(neighbor == null || !neighbor.IsActive)
                                continue;
                            //Do NOT spread to neighbors that have already been targeted for
                            //disturbance:
                            if (agent.OutbreakZone[neighbor] == Zone.Newzone)
                                continue;
                            //Check for duplicates:
                            if (sitesToConsider.Contains(neighbor))
                                continue;

                            //PlugIn.ModelCore.UI.WriteLine("Distance between neighbor and center = {0}.", DistanceBetweenSites(neighbor, initiationSite));
                            //PlugIn.ModelCore.UI.WriteLine("SV={0:0.0}.", SiteVars.Vulnerability[neighbor]);
                            //PlugIn.ModelCore.UI.WriteLine("Threshold={0:0.0}.", agent.EpidemicThresh);
                            if(DistanceBetweenSites(neighbor, initiationSite) <= dispersalDistance
                                && SiteVars.Vulnerability[neighbor] > agent.EpidemicThresh)
                            {
                                sitesToConsider.Enqueue(neighbor);
                            }
                        }
                    }
                }
            }

        }
Пример #37
0
        public static Control FindControl(Control oControl, string id)
        {
            try
            {
                Control c = oControl.NamingContainer.FindControl(id);

                if (c != null) return c;

                // Incase we are in a container ourselves!!
                c = oControl.NamingContainer.Parent.NamingContainer.FindControl(id);

                if (c != null) return c;

                // Give up...look in the entire form!!
                System.Collections.Queue q = new System.Collections.Queue();
                q.Enqueue(oControl.Page.Form);

                while (q.Count > 0)
                {
                    Control oParent = (Control)q.Dequeue();
                    c = oParent.NamingContainer.FindControl(id);
                    if (c != null) return c;

                    foreach (Control oChild in oParent.Controls)
                        q.Enqueue(oChild);
                }
            }
            catch (Exception ex)
            {
                Trace.Write(ex);
            }

            return null;
        }
Пример #38
0
        /*
        public override  void UpdateImage(object sender, Image image)
        {
            Control c = (Control)sender;
            Graphics gImg = Graphics.FromImage(image);
            gImg.DrawLine(pen, ptStart.X, ptStart.Y, ptEnd.X, ptEnd.Y);
            gImg.Dispose();
            c.Invalidate();
        }
        */
        protected void FillFlood(Control c, Point node, Image image)
        {
            Color target_color = Color.Empty;
            Color color_of_node = Color.Empty;
            Color replacement_color = Color.Empty;
            Bitmap tmpBmp = new Bitmap(image);

            //Set Q to the empty queue
            System.Collections.Queue q = new System.Collections.Queue();

            //replacement_color is opposite color of node
            try
            {
                target_color = tmpBmp.GetPixel(node.X, node.Y);
                replacement_color = Color.FromArgb(Byte.MaxValue - target_color.R,
                                                    Byte.MaxValue - target_color.G,
                                                    Byte.MaxValue - target_color.B);
            }
            catch (ArgumentOutOfRangeException aore)
            {
                return;
            }

            //Add node to the end of Q
            q.Enqueue(node);

            Graphics gBmp = Graphics.FromImage(image);
            Graphics gTmp = Graphics.FromImage(tmpBmp);

            Pen aPen = new Pen(replacement_color, 1);

            //For each element n of Q
            while (q.Count > 0)
            {
                Point n = (Point)q.Dequeue();

                //If the color of n is not equal to target_color, skip this iteration.
                try
                {
                    color_of_node = tmpBmp.GetPixel(n.X, n.Y);
                    if (color_of_node.Equals(target_color) == false)
                    {
                        continue;
                    }
                }
                catch (ArgumentOutOfRangeException aore)
                {
                    continue;
                }

                //Set w and e equal to n.
                Point w = n;
                Point e = n;

                //Move w to the west until the color of the node w no longer matches target_color.
                Color west_node_color = Color.Empty;
                do
                {
                    try
                    {
                        west_node_color = tmpBmp.GetPixel(--w.X, w.Y);
                    }
                    catch (ArgumentOutOfRangeException aore)
                    {
                        w.X++;
                        break;
                    }
                }
                while (west_node_color.Equals(target_color));

                //Move e to the east until the color of the node e no longer matches target_color.
                Color east_node_color = Color.Empty;
                do
                {
                    try
                    {
                        east_node_color = tmpBmp.GetPixel(++e.X, e.Y);
                    }
                    catch (ArgumentOutOfRangeException aore)
                    {
                        e.X--;
                        break;
                    }
                }
                while (east_node_color.Equals(target_color));

                //Set the color of node s between w and e to replacement_color
                gBmp.DrawLine(pen, w, e);
                gTmp.DrawLine(aPen, w, e);
                c.Invalidate(new Rectangle(w.X, w.Y, e.X - w.X, 1));

                //For each node n2 between w and e.
                int y = w.Y - 1;
                bool isLine = false;
                for (int x = w.X; x <= e.X; x++)
                {
                    //If the color of node at the north of n is target_color, add that node to the end of Q.
                    try
                    {
                        Color test = tmpBmp.GetPixel(x, y);
                        if (tmpBmp.GetPixel(x, y).Equals(target_color))
                        {
                            if (isLine == false)
                            {
                                q.Enqueue(new Point(x, y));
                                isLine = true;
                            }
                        }
                        else
                        {
                            isLine = false;
                        }
                    }
                    catch (ArgumentOutOfRangeException aore)
                    {
                        break;
                    }
                }
                y = w.Y + 1;
                isLine = false;
                for (int x = w.X; x <= e.X; x++)
                {
                    //If the color of node at the north of n is target_color, add that node to the end of Q.
                    try
                    {
                        if (tmpBmp.GetPixel(x, y).Equals(target_color))
                        {
                            if (isLine == false)
                            {
                                q.Enqueue(new Point(x, y));
                                isLine = true;
                            }
                        }
                        else
                        {
                            isLine = false;
                        }
                    }
                    catch (ArgumentOutOfRangeException aore)
                    {
                        break;
                    }
                }
            }/* while */
            aPen.Dispose();
            gBmp.Dispose();
            gTmp.Dispose();
        }
Пример #39
0
        public int NodesMin(int index_from, int index_to)
        {
            int[] status = new int[countCS];
            for (int i = 0; i < countCS; i++)
                status[i] = 0;

            int curr = index_from;
            status[curr] = 1;      // вершина переглянута
            System.Collections.Queue och = new System.Collections.Queue();
            och.Enqueue(curr);

            while (och.Count != 0)
            {
                curr = Convert.ToInt32(och.Dequeue());
                for (int i = 0; i < countCS; i++)
                    if (matrixCS[curr, i] != 0 && status[i] == 0)
                    {
                        status[i] = 1;          // відвідали вершину
                        och.Enqueue(i);
                        if (i == index_to)
                        {
                            node_min_list.Insert(0, TopListCSNew[curr].id);
                            return curr;
                        }
                    }
            }
            return curr;
        }
        public static void MostrarColeccionesNoGenerics()
        {
            Console.Clear();
            Console.WriteLine("******************************");
            Console.WriteLine("*****Pilas No Genéricas*******");
            Console.WriteLine("******************************");
            Console.ReadLine();

            //DECLARO E INSTANCIO UNA COLECCION DE TIPO LIFO
            System.Collections.Stack pila = new System.Collections.Stack();

            pila.Push(1);
            pila.Push(2);
            pila.Push(3);
            pila.Push(4);

            Console.WriteLine("Agrego elementos a la pila...");
            Console.WriteLine("Utilizo pila.Push()");
            Console.WriteLine("Orden de los elementos: 1 - 2 - 3 - 4");
            Console.ReadLine();

            Console.WriteLine("Muestro el primer elemento de la pila...");
            Console.WriteLine("Utilizo pila.Peek()");
            Console.ReadLine();

            Console.WriteLine(pila.Peek());
            Console.ReadLine();

            Console.WriteLine("Muestro todos los elementos de la pila...");
            Console.WriteLine("Recorro con un foreach. No saco los elementos de la pila.");
            Console.ReadLine();

            foreach (int elemento in pila)
            {
                Console.WriteLine(elemento);
            }

            Console.ReadLine();

            Console.WriteLine("Desapilo todos los elementos de la pila...");
            Console.WriteLine("Utilizo pila.Pop(). Recorro con un for");
            Console.ReadLine();

            int cantidad = pila.Count;

            for (int i = 0; i < cantidad; i++)
            {
                Console.WriteLine("Elemento {0} = {1}", i, pila.Pop());
            }

            Console.ReadLine();

            Console.WriteLine("Cantidad de elementos en la pila = {0}", pila.Count);
            Console.ReadLine();

            Console.Clear();
            Console.WriteLine("******************************");
            Console.WriteLine("****Colas No Genéricas********");
            Console.WriteLine("******************************");
            Console.ReadLine();

            System.Collections.Queue cola = new System.Collections.Queue();

            cola.Enqueue(1);
            cola.Enqueue(2);
            cola.Enqueue(3);
            cola.Enqueue(4);

            Console.WriteLine("Agrego elementos a la cola...");
            Console.WriteLine("Utilizo pila.Enqueue()");
            Console.WriteLine("Orden de los elementos: 1 - 2 - 3 - 4");
            Console.ReadLine();

            Console.WriteLine("Muestro el primer elemento de la cola...");
            Console.WriteLine("Utilizo cola.Peek()");
            Console.ReadLine();

            Console.WriteLine(cola.Peek());
            Console.ReadLine();

            Console.WriteLine("Muestro todos los elementos de la cola...");
            Console.WriteLine("Recorro con un foreach");
            Console.ReadLine();

            foreach (int elemento in cola)
            {
                Console.WriteLine(elemento);
            }

            Console.ReadLine();

            Console.WriteLine("Saco todos los elementos de la cola...");
            Console.WriteLine("Utilizo cola.Dequeue(). Recorro con un for");
            Console.ReadLine();

            cantidad = cola.Count;

            for (int i = 0; i < cantidad; i++)
            {
                Console.WriteLine("Elemento {0} = {1}", i, cola.Dequeue());
            }

            Console.ReadLine();

            Console.WriteLine("Cantidad de elementos en la cola = {0}", cola.Count);
            Console.ReadLine();

            Console.Clear();
            Console.WriteLine("******************************");
            Console.WriteLine("******Listas Dinamicas********");
            Console.WriteLine("******************************");
            Console.ReadLine();

            System.Collections.ArrayList vec = new System.Collections.ArrayList();

            vec.Add(1);
            vec.Add(4);
            vec.Add(3);
            vec.Add(2);

            Console.WriteLine("Agrego elementos al ArrayList...");
            Console.WriteLine("Utilizo vec.Add()");
            Console.WriteLine("Orden de los elementos: 1 - 4 - 3 - 2");
            Console.ReadLine();

            Console.WriteLine("Muestro todos los elementos del ArrayList...");
            Console.WriteLine("Recorro con un foreach");
            Console.ReadLine();

            foreach (int elemento in vec)
            {
                Console.WriteLine(elemento);
            }

            Console.ReadLine();

            Console.WriteLine("Ordeno los elementos del ArrayList...");
            Console.WriteLine("Utilizo vec.Sort(). Recorro con un for");
            Console.ReadLine();

            vec.Sort();

            cantidad = vec.Count;

            for (int i = 0; i < cantidad; i++)
            {
                Console.WriteLine("Elemento {0} = {1}", i, vec[i]);
            }

            Console.ReadLine();

            Console.WriteLine("Ordeno los elementos del ArrayList...");
            Console.WriteLine("Utilizo vec.Reverse(). Recorro con un for");
            Console.ReadLine();

            vec.Reverse();

            cantidad = vec.Count;

            for (int i = 0; i < cantidad; i++)
            {
                Console.WriteLine("Elemento {0} = {1}", i, vec[i]);
            }

            Console.ReadLine();

            Console.Clear();
            Console.WriteLine("******************************");
            Console.WriteLine("*********HashTable************");
            Console.WriteLine("******************************");
            Console.ReadLine();

            System.Collections.Hashtable ht = new System.Collections.Hashtable();

            ht.Add(1, "valor 1");
            ht.Add(4, "valor 4");
            ht.Add(3, "valor 3");
            ht.Add(2, "valor 2");

            Console.WriteLine("Agrego elementos al HashTable...");
            Console.WriteLine("Utilizo vec.Add()");
            Console.WriteLine("Orden de los elementos: 1 - 4 - 3 - 2");
            Console.ReadLine();

            Console.WriteLine("Muestro todos los elementos del HashTable...");
            Console.WriteLine("Recorro con un for");
            Console.ReadLine();

            cantidad = ht.Count;

            for (int i = 1; i <= cantidad; i++)
            {
                Console.WriteLine("Elemento {0} = {1}", i, ht[i]);
            }

            Console.ReadLine();
        }
Пример #41
0
        private ScriptVariable ProcessData(System.Collections.Queue equation)
        {
            System.Collections.ArrayList tmpvars = new System.Collections.ArrayList();

            ScriptVariable outv = new ScriptVariable();
            outv.Type = Var_Types.ASSIGNABLE;

            ScriptVariable outi;

            System.Collections.Queue neweq = new System.Collections.Queue();

            //lets process all the paran bullshit first
            while (equation.Count > 0)
            {
                string token1 = equation.Dequeue().ToString();

                if (token1 == "(")
                {
                    int pcnt = 1;

                    System.Collections.Queue subeq = new System.Collections.Queue();

                    while (pcnt != 0)
                    {
                        string ntoken = equation.Dequeue().ToString();

                        if (ntoken == "(")
                        {
                            pcnt++;
                        }
                        if (ntoken == ")")
                        {
                            pcnt--;
                        }
                        if (pcnt != 0)
                        {
                            subeq.Enqueue(ntoken);
                        }
                    }

                    outi = new ScriptVariable();
                    outi.Type = Var_Types.ASSIGNABLE;
                    outi = ProcessData(subeq);

                    outi.Name = Globals.SCRIPT_OUT_VAR + Globals.Rando.Next(int.MaxValue);
                    while (VariableExists(outi.Name))
                    {
                        outi.Name = Globals.SCRIPT_OUT_VAR + Globals.Rando.Next(int.MaxValue);
                    }
                    tmpvars.Add(outi.Name);
                    Add_Variable(outi, StackHeight);

                    neweq.Enqueue(outi.Name);
                }
                else
                {
                    neweq.Enqueue(token1);
                }
            }

            //now we have a queue of pure tokens with no parans
            while (neweq.Count > 0)
            {
                string token1 = neweq.Dequeue().ToString();

                if (neweq.Count == 0)
                {
                    //we only had 1 parameter
                    outv = Get_Var(token1);
                }
                else
                {
                    outi = new ScriptVariable();
                    outi.Type = Var_Types.ASSIGNABLE;

                    string token2 = neweq.Dequeue().ToString();

                    if (isUnaryOp(token1.ToUpperInvariant()))
                    {
                        EvaluateUnary(outi, token1.ToUpperInvariant(), token2);
                    }
                    else if (isBinaryOp(token2.ToUpperInvariant()))
                    {
                        string token3 = neweq.Dequeue().ToString();

                        EvaluateBinary(outi, token2.ToUpperInvariant(), token1, token3);
                    }

                    //add our created value to the stack
                    outi.Name = Globals.SCRIPT_OUT_VAR + Globals.Rando.Next(int.MaxValue);
                    while (VariableExists(outi.Name))
                    {
                        outi.Name = Globals.SCRIPT_OUT_VAR + Globals.Rando.Next(int.MaxValue);
                    }
                    tmpvars.Add(outi.Name);
                    Add_Variable(outi, StackHeight);

                    //now we need to push this variable to the front of our queue via a temporary queue
                    System.Collections.Queue tmpeq = new System.Collections.Queue();
                    tmpeq.Enqueue(outi.Name);
                    while (neweq.Count > 0)
                    {
                        tmpeq.Enqueue(neweq.Dequeue());
                    }
                    neweq = tmpeq;
                }

            }

            //delete all our temporary variables
            foreach (string name in tmpvars)
            {
                Script_DELETE(name);
            }

            return outv;
        }
Пример #42
0
        static void insertQueryHandler(ref QueryBuilder newQuery, string sqlStr)
        {
            try
            {
                newQuery.setType(ABSTRACTQUERYTYPES.InsertQuery);
                string[] tokens = sqlStr.Split(' ');
                System.Collections.Queue fieldQueue = new System.Collections.Queue(15);
                for (int i = 0; i < tokens.Length; i++)
                {
                    string tokenPeek = tokens[i];
                    if (tokens[i].Equals("into")) //Next token will be the tablename
                        newQuery.addSource(tokens[++i]);
                    if ((tokens[i].Equals("(")) && (!tokens[i - 2].Equals("values")))
                    { //fieldlist
                        // process fieldlist
                        string fieldname;
                        i++;    //just move forward to the tagset.
                        while (!tokens[i].Equals(")"))
                        {
                            fieldname = tokens[i++];
                            if (fieldname.Trim().Substring(fieldname.Length - 1).Equals(","))
                                fieldname = fieldname.Trim().Substring(0, fieldname.Trim().Length - 1);
                            foreach(string field in fieldname.Split(','))
                            fieldQueue.Enqueue(field);
                        }

                        string test = tokens[i + 1];

                    }
                    else if ((tokens[i + 1].Equals("(")) && (tokens[i].ToLower().Equals("values")))
                    { //valuelist
                        // process valuelist
                        i++; i++;
                        string restOfString = "";
                        while (i < tokens.Length)
                            restOfString += tokens[i++] + " ";

                        int strquoteon = 0;
                        string fieldVal = "";
                        bool quotedType = false;
                        for (int x = 0; x < restOfString.Length; x++)
                        {
                            if ((restOfString[x].Equals('\'')) & (strquoteon == 0))
                            {
                                strquoteon = 1;
                                quotedType = true;
                                //x++;    //skip the quote
                                fieldVal = "";

                                //fieldVal += restOfString[x];
                            }
                            else if ((strquoteon == 0) & ((restOfString[x].Equals(',')) | (restOfString[x].Equals(')'))))
                            {
                                string fieldname = (string)fieldQueue.Dequeue();
                                // Make sure we're not quoting.

                                newQuery.addField(new AField(fieldname, fieldVal.Trim()));
                                fieldVal = "";
                                quotedType = false;
                            }
                            else if (x > 0)
                            {
                                if ((restOfString[x].Equals('\'')) & !((restOfString[x - 1].Equals('\\'))))
                                {
                                    strquoteon = 0;
                                    //fieldVal += restOfString[x];
                                }
                                else
                                {
                                    if (!((strquoteon == 0) && (quotedType == true)))
                                        fieldVal += restOfString[x];
                                }
                            }
                            else
                            {

                                fieldVal += restOfString[x];
                            }

                        }

                        break;
                    }
                }
            }
            catch (Exception e)
            {
                newQuery = null;
            }
        }
Пример #43
0
        void DataRepairTask()
        {
            System.Collections.ArrayList aryThread = new System.Collections.ArrayList();

            System.Data.Odbc.OdbcConnection cn = new System.Data.Odbc.OdbcConnection(Comm.DB2.Db2.db2ConnectionStr);
            System.Data.Odbc.OdbcCommand cmd = new System.Data.Odbc.OdbcCommand();
            cmd.CommandTimeout = 120;
            StRepairData rpd=null;//=new StRepairData();

            cmd.Connection = cn;

              System.Collections.Queue queue = new System.Collections.Queue();

              int dayinx = 1;
            while (true)
            {
                Comm.TC.VDTC tc;

                if (!IsLoadTcCompleted )
                {
                    System.Threading.Thread.Sleep(1000);
                    continue;
                }

                try
                {
                  //  cn= new System.Data.Odbc.OdbcConnection(Comm.DB2.Db2.db2ConnectionStr);
                    while (this.dbServer.getCurrentQueueCnt() > 50)
                        System.Threading.Thread.Sleep(1000 * 10);
                    cn.Open();
                    ConsoleServer.WriteLine("Repair task begin!");
                    cmd.Connection = cn;
                 //   string sqlGetRepair = "select * from (SELECT t1.DEVICENAME, t1.TIMESTAMP ,trycnt,datavalidity FROM TBLVDDATA1MIN t1 inner join tbldeviceconfig t2 on t1.devicename=t2.devicename WHERE  mfccid='{0}'  and comm_state <> 3  and  t1.TIMESTAMP between '{1}' and '{2}' and trycnt<3 fetch first 300 row only  )  where  DATAVALIDITY = 'N' order by trycnt,timestamp desc  ";
                    string sqlGetRepair = "select t1.DEVICENAME, TIMESTAMP ,trycnt,datavalidity,comm_state from TBLVDDATA1MIN  t1 inner join tblDeviceConfig t2 on t1.devicename=t2.devicename where mfccid='{0}' and  TIMESTAMP between '{1}' and '{2}' and trycnt <1 and datavalidity='N' and comm_state=1  and enable='Y'  order by timestamp desc  fetch first 300  row only ";

                    cmd.CommandText = string.Format(sqlGetRepair,mfccid, Comm.DB2.Db2.getTimeStampString(System.DateTime.Now.AddDays(-dayinx)), Comm.DB2.Db2.getTimeStampString(System.DateTime.Now.AddDays(-dayinx+1).AddMinutes(-10)));
                    System.Data.Odbc.OdbcDataReader rd = cmd.ExecuteReader();

                    while (rd.Read())
                    {
                         string devName="" ;
                          DateTime dt ;
                          devName = rd[0] as string;
                          dt = System.Convert.ToDateTime(rd[1]);
                            queue.Enqueue(new StRepairData(dt,devName));

                    }
                    rd.Close();

                    ConsoleServer.WriteLine("total:" + queue.Count + " to repair!");
                    if (queue.Count < 300)
                    {
                        dayinx++;
                        if (dayinx ==4)
                            dayinx = 1;

                    }
                    if(queue.Count<10)
                        System.Threading.Thread.Sleep(1000 * 60);

                    aryThread.Clear();
                    while (queue.Count!=0)
                    {
                        try
                        {

                             rpd =(StRepairData)queue.Dequeue() ;
                             if (Program.mfcc_vd.manager.IsContains(rpd.devName))
                                 tc = (Comm.TC.VDTC)Program.mfcc_vd.manager[rpd.devName];
                             else

                                 continue;

                             if (!tc.IsConnected)
                             {
                                 dbServer.SendSqlCmd(string.Format("update tbldeviceconfig  set comm_state=3 where devicename='{0}' ", rpd.devName));

                                 continue;
                             }

                            System.Threading.Thread th= new System.Threading.Thread(Repair_job);
                            aryThread.Add(th);
                            th.Start(rpd);

                            if (aryThread.Count >= 5)
                            {
                                for (int i = 0; i < aryThread.Count; i++)

                                    ((System.Threading.Thread)aryThread[i]).Join();

                                aryThread.Clear();
                            }

                        //   ConsoleServer.WriteLine("==>repair:" + rpd.devName + "," + rpd.dt.ToString());

                        }
                        catch (Exception ex)
                        {
                            ConsoleServer.WriteLine( ex.Message + ex.StackTrace);

                        }
                    }

                    for (int i = 0; i < aryThread.Count; i++)

                        ((System.Threading.Thread)aryThread[i]).Join();

                    aryThread.Clear();

                }
                catch (Exception x)
                {
                    ConsoleServer.WriteLine(x.Message+ x.StackTrace);
                }
                finally
                {
                    try
                    {
                        cn.Close();
                    }
                    catch { ;}
                }

            }
        }
Пример #44
0
        // ациклічність графа
        public bool NodeIsAcyclic(int currNode, int algorithm, bool is_mess_show)
        {
            int n = TopList.Count;
            int[] status = new int[n];
            int[,] matrix = Matrix(algorithm);
            for (int i = 0; i < n; i++)
                status[i] = 0;

            int curr = currNode;
            System.Collections.Queue och = new System.Collections.Queue();
            och.Enqueue(curr);
            all_neighbors_nodes.Clear();

            while (och.Count != 0)
            {
                curr = Convert.ToInt32(och.Dequeue());
                all_neighbors_nodes.Add(curr);
                for (int i = 0; i < n; i++)
                    if (matrix[curr, i] != 0 &&  status[i] == 0)
                    {
                        status[i] = 1;          // відвідали вершину
                        och.Enqueue(i);
                        if (och.Contains(currNode))
                        {
                            if (is_mess_show)
                                MessageBox.Show("Цикл в " + TopList[currNode].id + " вершині");
                            return false;
                        }
                    }
            }
            return true; 
        }
Пример #45
0
        // зв'язність графа
        public bool IsConnect(bool is_mess_show)
        {
            int n = TopList.Count;
            int[] status = new int[n];
            int[,] matrix = new int[n, n];
            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < n; j++)
                    matrix[i, j] = 0;
                status[i] = 0;
            }

            foreach (edge_view line in edgeList)
                for (int i = 0; i < n; i++)
                    for (int j = 0; j < n; j++)
                        if (TopList[i].id == line.From.id)
                            if (TopList[j].id == line.To.id)
                            {
                                matrix[i, j] = 1;
                                matrix[j, i] = 1;
                            }

            int curr = 0;
            status[curr] = 1;      // вершина переглянута
            System.Collections.Queue och = new System.Collections.Queue();
            och.Enqueue(curr);
 
            while (och.Count != 0)
            {
                curr = Convert.ToInt32(och.Dequeue());
                for (int i = 0; i < n; i++)
                    if (matrix[curr, i] != 0 && status[i] == 0)
                    {
                        status[i] = 1;          // відвідали вершину
                        och.Enqueue(i);
                    }
            }
            if (endSeek(status) == true)
            {
                if (is_mess_show)
                    MessageBox.Show("Граф зв'язний");
                return true;
            }
            else
                MessageBox.Show("Граф не зв'язний");
            return false;
        }