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); }
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]); }
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); }
private void RetrieveUsernameFromDatabase() { SafelyChangeCursor(Cursors.WaitCursor); try { UserStatus("Retrieving username"); if (_AbsintheState.TargetAttackVector != null) { _AbsintheState.Username = _AbsintheState.TargetAttackVector.GetDatabaseUsername(); lock (_ThreadGuiMutex) { _LocalGuiQueue.Enqueue(LocalGuiAction.UsernameInfo); } this.Invoke(new ThreadedSub(UnSafelyUpdateUI)); } else { UserMessage("Please initialize the system!"); SafelyChangeCursor(Cursors.Default); return; } } catch (Exception e) { UserMessage(e.ToString()); SafelyChangeCursor(Cursors.Default); throw e; } UserStatus("Username retrieved"); SafelyChangeCursor(Cursors.Default); }
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); }
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 }
/// <summary> /// Lê a atual entrada. /// </summary> private void ReadEntry() { var entryContent = (EntryContent)_reader.ReadByte(); switch (entryContent) { case EntryContent.Integer: _entryQueue.Enqueue((int)_reader.ReadUInt16()); return; case EntryContent.String: _entryQueue.Enqueue(ReadString()); return; case EntryContent.Byte: _entryQueue.Enqueue(_reader.ReadByte()); return; case EntryContent.Boolean: _entryQueue.Enqueue(_reader.ReadByte() == 1); return; case EntryContent.Empty: _entryQueue.Enqueue(new object()); return; } throw new ParserException("Error reading CGT: unknown entry-content type"); }
static void Main(string[] args) { System.Collections.Queue q = new System.Collections.Queue(); q.Enqueue(1); q.Enqueue(2); q.Enqueue(3); q.Enqueue(4); Console.WriteLine("Queue elements are:"); foreach (int i in q) { Console.Write(i + " "); } }
static void Main(string[] args) { System.Collections.Queue queue = new System.Collections.Queue(); queue.Enqueue(1); queue.Enqueue(2); queue.Enqueue(3); while (queue.Count > 0) { Console.WriteLine(queue.Dequeue()); } Console.ReadLine(); }
static void Main(string[] args) { System.Collections.Queue queue = new System.Collections.Queue(); queue.Enqueue("Fine"); queue.Enqueue("Does"); queue.Enqueue("Boy"); queue.Enqueue("Good"); queue.Enqueue("Every"); Console.WriteLine("Peek returns {0}", queue.Peek()); while (queue.Count > 0) { Console.WriteLine(queue.Dequeue()); } }
/// <summary> /// 发送消息给Bot /// </summary> /// <param name="content">内容</param> void SendMessageToBot(string content) { if (directLineClient != null || luisClient != null) { sendMessageQueue.Enqueue(content); } }
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); }
static void Main(string[] args) { System.Collections.Queue queue = new System.Collections.Queue(); queue.Enqueue(1); queue.Enqueue(2); queue.Enqueue(3); Console.WriteLine("1 in Queue:{0}", queue.Contains(1)); Console.WriteLine("Remove 1:{0}", queue.Dequeue()); Console.WriteLine("Peek1:{0}", queue.Peek()); object[] numArray = queue.ToArray(); Console.WriteLine(string.Join(", ", numArray)); }
public static Boolean GetReplicationLog(MySqlConnection conn, long id, System.Collections.Queue queue, ref string errorString) { QueryInfo query; string strSql = "SELECT DBCODE,ID,BATCHID,OBJECTTYPE,OBJECTNAME,COMMANDTYPE,COMMANDSTRING FROM sqllog WHERE ID > " + id.ToString(); strSql += " ORDER BY ID"; MySqlCommand Com = new MySqlCommand(); MySqlDataReader reader; Com.Connection = conn; try { Com.CommandText = strSql; reader = Com.ExecuteReader(); while (reader.Read()) { query.DBCode = reader["DBCODE"].ToString(); query.ID = Convert.ToInt64(reader["ID"].ToString()); query.BatchID = Convert.ToInt64(reader["BATCHID"].ToString()); query.ObjectType = reader["OBJECTTYPE"].ToString(); query.ObjectName = reader["OBJECTNAME"].ToString(); query.CommandType = reader["COMMANDTYPE"].ToString(); query.CommandString = reader["COMMANDSTRING"].ToString(); queue.Enqueue(query); } reader.Close(); } catch (MySqlException sqlEx) { errorString = sqlEx.Message; return(false); } Com.Dispose(); return(true); }
private static void EnqueueMany <T>(IReadOnlyList <T> queueItems) { var itemsQueued = 0; while (itemsQueued < queueItems.Count) { if (!TryEnterQMonitor(3)) { continue; //Could not obtain lock after 3 tries waiting 5 seconds each } Q.Enqueue(queueItems[itemsQueued]); Monitor.Pulse(Q); Monitor.Exit(Q); itemsQueued++; } }
public void Push(object client) { lock (mQueue) { mQueue.Enqueue(client); } }
// 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(); }
void worker_DoWork(object sender, DoWorkEventArgs e) { //setup worker queue string[] filenames = (string[])e.Argument; System.Collections.Queue workQueue = new System.Collections.Queue(filenames.Length); System.Collections.Queue syncQueue = System.Collections.Queue.Synchronized(workQueue); foreach (string file in filenames) { syncQueue.Enqueue(file); } //create and start the threads int numThreads = Math.Min(System.Environment.ProcessorCount, syncQueue.Count); Thread[] threads = new Thread[numThreads]; for (int i = 0; i < numThreads; i++) { threads[i] = new Thread(workThreadWork); threads[i].Start(workQueue); } //wait for all the threads to end foreach (Thread curThread in threads) { curThread.Join(); } }
public void Enqueue(ProcessInfo Info) { if (!IsQueued(Info) && !IsRunning(Info)) { processQueue.Enqueue(Info); } }
////////////////////queue handling: //add packet to queue //using lock to ensure threads do not fight with each other public void AddPacket(NetPacket packet) { lock (Packets) { Packets.Enqueue(packet); } }
public void Enqueue(object item) { lock (m_lockObjcet) { m_queue.Enqueue(item); } }
void SendArpGenericInBackground(UInt64 destinationEthernetAddress, ArpOperation arpOperation, UInt64 targetPhysicalAddress, UInt32 targetProtocolAddress) { ArpGenericData arpGenericData = new ArpGenericData(destinationEthernetAddress, arpOperation, targetPhysicalAddress, targetProtocolAddress); _sendArpGenericInBackgroundQueue.Enqueue(arpGenericData); _sendArpGenericInBackgroundEvent.Set(); }
public static void Show(string sMessage) { // If this is the first time a page has called this method then if (!m_executingPages.Contains(HttpContext.Current.Handler)) { // Attempt to cast HttpHandler as a Page. Page executingPage = HttpContext.Current.Handler as Page; if (executingPage != null) { // Create a Queue to hold one or more messages. System.Collections.Queue messageQueue = new System.Collections.Queue(); // Add our message to the Queue messageQueue.Enqueue(sMessage); // Add our message queue to the hash table. Use our page reference // (IHttpHandler) as the key. m_executingPages.Add(HttpContext.Current.Handler, messageQueue); // Wire up Unload event so that we can inject // some JavaScript for the alerts. executingPage.Unload += new EventHandler(ExecutingPage_Unload); } } else { // If were here then the method has allready been // called from the executing Page. // We have allready created a message queue and stored a // reference to it in our hastable. System.Collections.Queue queue = (System.Collections.Queue)m_executingPages[HttpContext.Current.Handler]; // Add our message to the Queue queue.Enqueue(sMessage); } }
public void Enqueue(Message message) { messageQueue.Enqueue(message); // In synchronous mode, we use the message as a lock, and we wait until the execution // thread pulses us to tell that it is done with the message. The synchronous bit is // used to control whether pulsing must happen. It is not required for correctness, // but it avoids unnecessary pulsing. if (message.Synchronous) { try { Monitor.Enter(message); messagesEnqueued.Release(); Monitor.Wait(message); } finally { Monitor.Exit(message); } } else { messagesEnqueued.Release(); } if (message.Kind == MessageKind.Keystroke && ((KeystrokeMessage)message).Motion == KeystrokeMotion.Down) { downKeystrokeWasEnqueued.Set(); } }
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); } }
void SendIcmpMessageInBackground(UInt32 destinationIPAddress, IcmpMessageType icmpMessageType, IcmpMessageCode icmpMessageCode, byte[] restOfHeader, byte[] data) { IcmpMessage icmpMessage = new IcmpMessage(destinationIPAddress, icmpMessageType, icmpMessageCode, restOfHeader, data); _sendIcmpMessagesInBackgroundQueue.Enqueue(icmpMessage); _sendIcmpMessagesInBackgroundEvent.Set(); }
/// <summary> /// Puts element into queue. /// </summary> /// <param name="data">Element to put in.</param> public void Enqueue(object data) { lock (this) { dataQueue.Enqueue(data); queueHasData.Set(); } }
public void Push(int time) { Count += 1; Total += time; Stack.Enqueue(new Uptime { Time = time, Stamp = System.DateTime.UtcNow }); }
static public void PutInstance(ASTPair p) { if (p != null) { p.reset(); instancePool_.Enqueue(p); } }
/// <summary> /// Register a callback to be called when the main loop terminates. /// </summary> /*public void OnStop( MethodDelegate method ) * { * if (method != null) * { * m_StopEvent += method; * } * }*/ /// <summary> /// Invokes a method in the main loop /// </summary> /// <param name='method'> /// The method to be executed in the main loop /// </param> /// <remarks> /// The call is asynchronous, i.e. the request will be queued and the call /// returns immediately to the calling thread. /// </remarks> public void Invoke(MethodDelegate method) { if (method != null) { m_methodQueue.Enqueue(method); m_syncEvent.Set(); } }
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); } } }
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....."); } }
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 { ; } } }
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; }
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; } }
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 { ;} } } }
private void OnLoad(object sender, EventArgs e) { log.Trace(">>>"); BackColor = ServiceScope.Get<IThemeManager>().CurrentTheme.BackColor; ServiceScope.Get<IThemeManager>().NotifyThemeChange(); // Load the Settings _gridColumns = new GridViewColumnsLyrics(); // Setup Dataview Grid dataGridViewLyrics.AutoGenerateColumns = false; dataGridViewLyrics.DataSource = _tracks; // Now Setup the columns, we want to display CreateColumns(); Localisation(); _sitesToSearch = Options.MainSettings.LyricSites; // initialize delegates _delegateLyricFound = lyricFound; _delegateLyricNotFound = lyricNotFound; _delegateThreadFinished = threadFinished; _delegateThreadException = threadException; _eventStopThread = new ManualResetEvent(false); _bgWorkerLyrics = new BackgroundWorker(); _bgWorkerLyrics.DoWork += bgWorkerLyrics_DoWork; _bgWorkerLyrics.ProgressChanged += bgWorkerLyrics_ProgressChanged; _bgWorkerLyrics.RunWorkerCompleted += bgWorkerLyrics_RunWorkerCompleted; _bgWorkerLyrics.WorkerSupportsCancellation = true; lbFinished.Visible = false; _lyricsQueue = new Queue(); dataGridViewLyrics.ReadOnly = true; foreach (TrackData track in _tracks) { string[] lyricId = new string[] {track.Artist, track.Title}; _lyricsQueue.Enqueue(lyricId); } _bgWorkerLyrics.RunWorkerAsync(); log.Trace("<<<"); }
// зв'язність графа 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; }
/// <summary> /// Constructor</summary> static Resources() { // GUI framework-specific registration is done in assemblies on which this library shouldn't depend. // Regardless, said assemblies still need to register the resources defined in here. // // Use reflection to: // - locate the any registration classes (hopefully there's at least one) // - determine whether they've begun registration (then nothing needs be done here) // - if they haven't, call their registration method from here const string kRegistrationStarted = "RegistrationStarted"; const string kRegister = "Register"; // all types named ResourceUtil var types = (from a in AppDomain.CurrentDomain.GetAssemblies() where !a.IsDynamic from t in a.GetExportedTypes() where t.Name == "ResourceUtil" select t).ToArray(); // the results of calling ResourceUtil.RegistrationStarted, for each type var regStarted = from t in types from p in t.GetProperties() where p.Name == kRegistrationStarted && p.PropertyType == typeof(bool) && p.GetGetMethod().IsPublic && p.GetGetMethod().IsStatic select (bool)(p.GetGetMethod().Invoke(null, new object[] {})); // if registration has already begun in one of these, we don't need to initiate it if (regStarted.Any(p => p)) return; // otherwise, get the registration methods var registerMethods = (from t in types from m in t.GetMethods() where m.Name == kRegister && m.IsStatic && m.IsPublic && m.ReturnType == typeof(void) && m.GetParameters().Length == 1 && m.GetParameters()[0].ParameterType == typeof(Type) select m).ToArray(); // if there's more than one registration method available, we have no idea which should be used. // The application will have to determine this, by calling one of the methods explicitly, // before execution arrives at this call path. if (registerMethods.Length > 1) { throw new InvalidOperationException( "More than one library has implemented a ResourceUtil.Register(Type type).\n" + "This is allowed, but one or the other method must be called explicitly,\n" + "before the app calls this static constructor."); } // Initiate registration. Set the RegistrationStarted property so we only auto-initiate once. var setRegStarted = from t in types from p in t.GetProperties() where p.Name == kRegistrationStarted && p.PropertyType == typeof(bool) && p.GetSetMethod().IsPublic && p.GetSetMethod().IsStatic select p; setRegStarted.First().GetSetMethod().Invoke(null, new object[] { true }); var paramQueue = new System.Collections.Queue(1); paramQueue.Enqueue(typeof(Resources)); registerMethods.First().Invoke(null, paramQueue.ToArray()); }
// ациклічність графа 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; }
//--------------------------------------------------------------------- ///<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); } } } } } }
private void OnLoad(object sender, EventArgs e) { log.Trace(">>>"); BackColor = ServiceScope.Get<IThemeManager>().CurrentTheme.BackColor; ServiceScope.Get<IThemeManager>().NotifyThemeChange(); // Load the Settings gridColumns = new GridViewColumnsLyrics(); // Setup Dataview Grid dataGridViewLyrics.AutoGenerateColumns = false; dataGridViewLyrics.DataSource = tracks; // Now Setup the columns, we want to display CreateColumns(); Localisation(); sitesToSearch = new List<string>(); if (Options.MainSettings.SearchLyricWiki) sitesToSearch.Add("LyricWiki"); if (Options.MainSettings.SearchHotLyrics) sitesToSearch.Add("HotLyrics"); if (Options.MainSettings.SearchLyrics007) sitesToSearch.Add("Lyrics007"); if (Options.MainSettings.SearchLyricsOnDemand) sitesToSearch.Add("LyricsOnDemand"); if (Options.MainSettings.SearchLyricsPlugin) sitesToSearch.Add("LyricsPluginSite"); if (Options.MainSettings.SearchActionext) sitesToSearch.Add("Actionext"); if (Options.MainSettings.SearchLyrDB) sitesToSearch.Add("LyrDB"); if (Options.MainSettings.SearchLRCFinder) sitesToSearch.Add("LrcFinder"); // initialize delegates m_DelegateLyricFound = new DelegateLyricFound(lyricFound); m_DelegateLyricNotFound = new DelegateLyricNotFound(lyricNotFound); m_DelegateThreadFinished = new DelegateThreadFinished(threadFinished); m_DelegateThreadException = new DelegateThreadException(threadException); m_EventStopThread = new ManualResetEvent(false); bgWorkerLyrics = new BackgroundWorker(); bgWorkerLyrics.DoWork += bgWorkerLyrics_DoWork; bgWorkerLyrics.ProgressChanged += bgWorkerLyrics_ProgressChanged; bgWorkerLyrics.RunWorkerCompleted += bgWorkerLyrics_RunWorkerCompleted; bgWorkerLyrics.WorkerSupportsCancellation = true; lbFinished.Visible = false; lyricsQueue = new Queue(); dataGridViewLyrics.ReadOnly = true; foreach (TrackData track in tracks) { string[] lyricId = new string[2] {track.Artist, track.Title}; lyricsQueue.Enqueue(lyricId); } bgWorkerLyrics.RunWorkerAsync(); log.Trace("<<<"); }
private void Assignment(ScriptVariable dest, string equation) { System.Collections.Queue parsed = new System.Collections.Queue(); while (equation.Length > 0) { string token = ReadToken(ref equation); if (token.Length > 0) { parsed.Enqueue(token); } } //now we have all our tokens in an array list... //time to evaluate ScriptVariable outv = ProcessData(parsed); switch (dest.Type) { case Var_Types.INT: try { dest.Value = System.Convert.ToInt64(outv.Value, System.Globalization.CultureInfo.InvariantCulture); } catch { dest.Value = 0; } break; case Var_Types.DOUBLE: try { dest.Value = System.Convert.ToDouble(outv.Value, System.Globalization.CultureInfo.InvariantCulture); } catch { dest.Value = 0D; } break; case Var_Types.STRING: try { dest.Value = System.Convert.ToString(outv.Value, System.Globalization.CultureInfo.InvariantCulture); } catch { dest.Value = "error in assingment casting from type of: " + outv.Type.ToString(); } break; default: dest.Value = outv.Value; dest.Type = outv.Type; break; } }
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; }
/* 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(); }
internal static void loadGraphicNodes(IList<LrentFile> files, Form1 a_Form) { ManagedWorld.NodeLibrary.AddToOcTree = false; pFiles = files; form = a_Form; rObjects = new System.Collections.Queue(); rObjects = System.Collections.Queue.Synchronized(rObjects); foreach (LrentFile lr in files) { foreach (ILrentObject ro in lr.Objects) rObjects.Enqueue(ro); } maxCount = rObjects.Count; HWND H = ThreadManager.CreateThread(new ParameterizedThreadStart(batch)); ThreadManager.StartThread(H, null); }
public static void Show(string sMessage) { // If this is the first time a page has called this method then if (!m_executingPages.Contains(HttpContext.Current.Handler)) { // Attempt to cast HttpHandler as a Page. Page executingPage = HttpContext.Current.Handler as Page; if (executingPage != null) { // Create a Queue to hold one or more messages. System.Collections.Queue messageQueue = new System.Collections.Queue(); // Add our message to the Queue messageQueue.Enqueue(sMessage); // Add our message queue to the hash table. Use our page reference // (IHttpHandler) as the key. m_executingPages.Add(HttpContext.Current.Handler, messageQueue); // Wire up Unload event so that we can inject // some JavaScript for the alerts. executingPage.Unload += new EventHandler(ExecutingPage_Unload); } } else { // If were here then the method has already been // called from the executing Page. // We have allready created a message queue and stored a // reference to it in our hastable. System.Collections.Queue queue = (System.Collections.Queue)m_executingPages[HttpContext.Current.Handler]; // Add our message to the Queue queue.Enqueue(sMessage); } }
public BTEnumerator(BTree tree) { m_tree = tree; m_to_be_visited = new System.Collections.Queue(); m_current = null; m_current_node = (BNode) m_tree.m_sgManager.GetSegment(m_tree.m_top_sid, m_tree.m_nodeFactory, m_tree.m_keyFactory); if (m_current_node.KeyNums >0) { for (int i=0; i<=m_current_node.KeyNums; i++) { m_to_be_visited.Enqueue(m_current_node.GetChildAt(i)); } } m_current_key_no = -1; }
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(); }
/// <summary> /// Constructor</summary> static Resources() { // Because GUI framework-specific dependencies have been removed from Atf.Gui, resource // registration has been moved to another assembly on which we cannot be dependent. Use // reflection to locate and invoke the "unknown" registration method. // // Create LINQ expression to collect all implementations of method // public static void Register(Type type); // defined in classes named "ResourceUtil" var methodInfos = from assembly in AppDomain.CurrentDomain.GetAssemblies() where assembly.FullName.StartsWith("Atf.Gui.WinForms") from type in assembly.GetExportedTypes() where type.Name == "ResourceUtil" from methodInfo in type.GetMethods() where methodInfo.Name == "Register" && methodInfo.IsStatic && methodInfo.IsPublic && methodInfo.ReturnType == typeof(void) && methodInfo.GetParameters().Length == 1 && methodInfo.GetParameters()[0].ParameterType == typeof(Type) select methodInfo; // Invoke the first found implementation of "public static void Register(Type type)" // throw an assertion if there is more than one found bool registerCalled = false; foreach (var methodInfo in methodInfos) { if (registerCalled) throw new InvalidOperationException("More than one implementation of ResourceUtil.Register(Type type) has been found. Only the first one will be called."); var paramQueue = new System.Collections.Queue(1); paramQueue.Enqueue(typeof(Resources)); methodInfo.Invoke(null, paramQueue.ToArray()); registerCalled = true; } }
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; }