/// <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); }
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()); } } }
public Boolean initReplicate() { testMail.fromID = "*****@*****.**"; testMail.fromPass = "******"; testMail.toID = "*****@*****.**"; clsStatus.UdpateStatusText("Loading Application...\r\n"); System.Threading.Thread.Sleep(500); replicationQueue = new System.Collections.Queue(); if (string.IsNullOrEmpty(settings.serverName)) { clsStatus.UdpateStatusText("Invalid Setting\r\n"); return(false); } MainDBInfo.ServerName = settings.serverName; MainDBInfo.DBName = settings.dbName; MainDBInfo.DBPort = settings.dbPort; MainDBInfo.DBUser = settings.userName; MainDBInfo.DBPWD = settings.password; MainDBInfo.ConnectionString = clsDBUtility.CreateConnectionString(MainDBInfo); try { clsStatus.ClearStatusText(); clsStatus.UdpateStatusText("Connecting to Master Database...\r\n"); System.Threading.Thread.Sleep(500); MainDBConn = new MySqlConnection(MainDBInfo.ConnectionString); MainDBConn.Open(); dbCode = clsDBUtility.GetConnectedDatabaseCode(MainDBInfo.ServerName, MainDBInfo.DBName, MainDBInfo.DBPort, MainDBConn, ref errorMessage); if (dbCode == null) { clsStatus.UdpateStatusText("Unable to locate current database from the list\r\n"); System.Threading.Thread.Sleep(500); return(false); } clsStatus.UdpateStatusText("Successfully Connected to Master Database\r\n"); System.Threading.Thread.Sleep(500); clsStatus.UdpateStatusText("Fetching data from Master Database\r\n"); System.Threading.Thread.Sleep(500); LogDBInfo = clsDBUtility.GetLogDBDetails(MainDBConn, dbCode, ref errorMessage); LogDBInfo.DBUser = settings.userName; LogDBInfo.DBPWD = settings.password; clsDBUtility.GetReplicationLogDBInfo(MainDBConn, dbCode, ref errorMessage, ref slaveDatabaseInfo); clsStatus.UdpateStatusText("Closing Master Database Connection...\r\n"); System.Threading.Thread.Sleep(500); MySqlConnection.ClearPool(MainDBConn); MainDBConn.Close(); MainDBConn.Dispose(); clsStatus.UdpateStatusText("Successfully Closed Master Database Connection.\r\n\r\n\r\n"); System.Threading.Thread.Sleep(500); LogDBInfo.ConnectionString = clsDBUtility.CreateConnectionString(LogDBInfo); } catch (MySqlException sqlEx) { clsStatus.UdpateStatusText(sqlEx.Message + "\n\r\n\r"); return(false); } return(true); }
// 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(); }
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 ArpResolver(EthernetInterface ethernetInterface) { // save a reference to our ethernet interface; we will use this to send ARP fraems _ethernetInterface = ethernetInterface; // create our ARP cache _arpCache = new System.Collections.Hashtable(); /* write fixed ARP frame parameters (which do not change) to our ARP frame buffer */ /* Hardware Type: 0x0001 (Ethernet) */ _arpFrameBuffer[0] = (byte)((HARDWARE_TYPE_ETHERNET >> 8) & 0xFF); _arpFrameBuffer[1] = (byte)(HARDWARE_TYPE_ETHERNET & 0xFF); /* Protocol Type: 0x0800 (IPv4) */ _arpFrameBuffer[2] = (byte)((PROTOCOL_TYPE_IPV4 >> 8) & 0xFF); _arpFrameBuffer[3] = (byte)(PROTOCOL_TYPE_IPV4 & 0xFF); /* Hardware Address Size: 6 bytes */ _arpFrameBuffer[4] = HARDWARE_ADDRESS_SIZE; /* Protocol Address Size: 4 bytes */ _arpFrameBuffer[5] = PROTOCOL_ADDRESS_SIZE; /* fixed values for index and count (passed to EthernetInterface.Send(...) with _arpFrameBuffer */ _indexArray[0] = 0; _countArray[0] = ARP_FRAME_BUFFER_LENGTH; // start our "send ARP replies" thread _sendArpGenericInBackgroundQueue = new System.Collections.Queue(); _sendArpGenericInBackgroundThread = new Thread(SendArpGenericThread); _sendArpGenericInBackgroundThread.Start(); // enable our "cleanup ARP cache" timer (fired every 60 seconds) _cleanupArpCacheTimer = new Timer(CleanupArpCache, null, 60000, 60000); // wire up the incoming ARP frame handler _ethernetInterface.ARPFrameReceived += _ethernetInterface_ARPFrameReceived; }
// We need this to make the use of the property as an attribute // light-weight. This allows us to delay initialize everything we // need to fully function as a ContextProperty. internal virtual void InitIfNecessary() { lock (this) { if (_asyncWorkEvent == null) { // initialize thread pool event to non-signaled state. _asyncWorkEvent = new AutoResetEvent(false); _workItemQueue = new Queue(); _asyncLcidList = new ArrayList(); WaitOrTimerCallback callBackDelegate = new WaitOrTimerCallback(this.DispatcherCallBack); // Register a callback to be executed by the thread-pool // each time the event is signaled. _waitHandle = ThreadPool.RegisterWaitForSingleObject( _asyncWorkEvent, callBackDelegate, null, // state info _timeOut, false); // bExecuteOnlyOnce } } }
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 }
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); } }
private Task RunTask(System.Collections.Queue syncQueue, FitnessFunction fitnessFunctionDelegate, int taskId) { //create a simple task that calls the locally defined Evaluate function var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; //.Net 4.5 option //var task = Task.Run (() => EvaluateTask (syncQueue, fitnessFunctionDelegate, taskId, token), token); //.Net 4.0/4.5 option var task = new Task(() => EvaluateTask(syncQueue, fitnessFunctionDelegate, taskId, token), token); task.Start(); task.ContinueWith(t => { var exception = t.Exception; if (OnEvaluationException != null && t.Exception != null) { var message = new StringBuilder(); foreach (var ex in t.Exception.InnerExceptions) { message.Append(ex.Message); message.Append("\r\n"); } var eventArgs = new ExceptionEventArgs("RunTask", message.ToString()); OnEvaluationException(this, eventArgs); } }, TaskContinuationOptions.OnlyOnFaulted); return(task); }
private Metadata.JobMetadata toJobMetadata(MethodInfo tm, object[] defaultValue = null, string recurringJobId = null, string queue = null) { var _defaultValue = new System.Collections.Queue(defaultValue ?? new object[] { }); var getQueue = new Func <string, string>(_queue => string.IsNullOrWhiteSpace(_queue) ? States.EnqueuedState.DefaultQueue : _queue); return(new Metadata.JobMetadata { Type = tm.ReflectedType, Queue = getQueue(queue), MethodInfo = tm, Parameters = tm.GetParameters() //.Where(parameterInfo => parameterInfo.ParameterType != typeof(Server.PerformContext) && parameterInfo.ParameterType != typeof(IJobCancellationToken)) .Select(f => new { Parameter = f, DisplayData = f.GetCustomAttribute <Metadata.DisplayDataAttribute>(true) }) .Select(f => new Metadata.JobParameter { Name = f?.Parameter?.Name, ParameterType = f?.Parameter?.ParameterType, LabelText = f?.DisplayData?.LabelText ?? f?.Parameter?.Name, PlaceholderText = f?.DisplayData?.PlaceholderText ?? f?.Parameter?.Name, DescriptionText = f?.DisplayData?.DescriptionText, IsMultiLine = f?.DisplayData?.IsMultiLine, ConvertType = f?.DisplayData?.ConvertType, DefaultValue = f?.DisplayData?.DefaultValue, //_defaultValue.Count > 0 ? _defaultValue.Dequeue() : null //IsDisabled = f?.DisplayData?.IsDisabled, CssClasses = f?.DisplayData?.CssClasses, }).ToArray(), Description = tm.GetCustomAttribute <System.ComponentModel.DescriptionAttribute>()?.Description ?? tm.Name, DisplayName = tm.GetCustomAttribute <System.ComponentModel.DisplayNameAttribute>()?.DisplayName ?? recurringJobId }); }
public void QueuePeek(DefinedQueue localQeue) { BankCustomer tempCustomer = new BankCustomer(); tempCustomer = (BankCustomer)localQeue.Peek(); Console.WriteLine("The next Customer in line: " + tempCustomer.name); }
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); }
/// <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); }
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); }
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); }
private bool m_disposed = false; // Track whether Dispose has been called. /// <summary> /// Constructor. /// </summary> public MainLoop() { // Create the wait event m_syncEvent = new System.Threading.AutoResetEvent(false); // Create a synchronized thread safe queue m_methodQueue = System.Collections.Queue.Synchronized(m_notSyncdmethodQueue); }
public AllObjectCollections( System.Collections.ArrayList prop0, System.Collections.IEnumerable prop1, System.Collections.ICollection prop2, System.Collections.IList prop3, System.Collections.Hashtable prop4, System.Collections.IDictionary prop5, System.Collections.Specialized.HybridDictionary prop6, System.Collections.Specialized.NameValueCollection prop7, System.Collections.BitArray prop8, System.Collections.Queue prop9, System.Collections.Stack prop10, System.Collections.SortedList prop11) { Prop0 = prop0; Prop1 = prop1; Prop2 = prop2; Prop3 = prop3; Prop4 = prop4; Prop5 = prop5; Prop6 = prop6; Prop7 = prop7; Prop8 = prop8; Prop9 = prop9; Prop10 = prop10; Prop11 = prop11; }
public static void MostrarCola(System.Collections.Queue pila) { foreach (int intA in pila) { Console.WriteLine(intA); } }
// 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()); } }
// 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(); }
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(); } }
/* ------------------------------------- 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); }
/// <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. }
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]); }
private void CreateQueue() { Queue = new System.Collections.Queue(); foreach (string key in map.Keys) { QueueObject(key); } }
public void Disassemble(IPipelineContext pContext, IBaseMessage pInMsg) { IBaseMessagePart bodyPart = pInMsg.BodyPart; if (bodyPart != null) { _qOutMessages = _decompressionManager.DecompressAndSpliMessage(pInMsg, pContext); } }
//struct EchoRequest //{ // public UInt32 DestinationIPAddress; // public UInt16 Identifier; // public UInt16 SequenceNumber; // public byte[] Data; // AutoResetEvent _responseReceivedEvent; // public EchoRequest(UInt32 destinationIPAddress, UInt16 identifier, UInt16 sequenceNumber, byte[] data) // { // this.DestinationIPAddress = destinationIPAddress; // this.Identifier = identifier; // this.SequenceNumber = sequenceNumber; // this.Data = data; // _responseReceivedEvent = new AutoResetEvent(false); // } // public bool WaitForResponse(Int32 millisecondsTimeout) // { // return _responseReceivedEvent.WaitOne(millisecondsTimeout, false); // } // internal void SetResponseReceived() // { // _responseReceivedEvent.Set(); // } //} //System.Collections.ArrayList _outstandingEchoRequests = new System.Collections.ArrayList(); //object _outstandingEchoRequestsLock = new object(); //UInt16 _nextEchoRequestSequenceNumber = 0; internal ICMPv4Handler(IPv4Layer ipv4Layer) { _ipv4Layer = ipv4Layer; // start our "send ICMP messages transmission" thread _sendIcmpMessagesInBackgroundQueue = new System.Collections.Queue(); _sendIcmpMessagesInBackgroundThread = new Thread(SendIcmpMessagesThread); _sendIcmpMessagesInBackgroundThread.Start(); }
static StackObject *Ctor_0(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject *__ret = ILIntepreter.Minus(__esp, 0); var result_of_this_method = new System.Collections.Queue(); return(ILIntepreter.PushObject(__ret, __mStack, result_of_this_method)); }
public static Advertisement POP(AdvertisementSectionPosition advertisementSectionPosition) { if (Queue != null && Queue.Count > 0) { return((Advertisement)Queue.Dequeue()); } Queue = GetViewAbleAdvertisements(advertisementSectionPosition); return(Queue.Count == 0 ? null : POP(advertisementSectionPosition)); }
/// <summary> /// Muestra el contenido de un Queue /// </summary> /// <param name="Queue">Muestra un Array Queue</param> /// <param name="algumento">Muestra un texto por delante</param> /// <param name="salto">Un salto de linia</param> public void Show (System.Collections.Queue Queue, System.String algumento = "", int salto = 1) { foreach (string fruta in Queue) { System.Console.Write("{1}->{0}\n", fruta, algumento); } LineasEsp.Salto(salto); }
/// <summary> /// Class constructor. /// </summary> /// <param name="pollInterval">Millisecond interval to sleep between polls.</param> public Semaphore(uint pollInterval) { // Set up the semaphore _queue = System.Collections.Queue.Synchronized(new System.Collections.Queue()); // Ensure that we have a sensible minimum poll interval if (pollInterval < 10) { pollInterval = 10; } _pollInterval = pollInterval; }
public Secondarythread(mainForm form, SemaphoreSlim semaphore) { this.form = form; this.cmdSemaphore = semaphore; this.productBirdfarmSem = new SemaphoreSlim(0); this.productMainSectionSem = new SemaphoreSlim(0); this.productAirplaneSem = new SemaphoreSlim(0); this.productNavalGunSem = new SemaphoreSlim(0); this.mainSectionSem = new SemaphoreSlim(0); this.airplaneSem = new SemaphoreSlim(0); this.navalGunSem = new SemaphoreSlim(0); this._MainSectionQueue = new System.Collections.Queue(); this._AirplaneQueue = new System.Collections.Queue(); this._NavalGunQueue = new System.Collections.Queue(); }
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); } } }
/// <summary> /// ���� /// </summary> public main() { InitializeComponent(); this.SizeChanged += new EventHandler(main_SizeChanged); this.notifyIcon1.DoubleClick += new EventHandler(notifyIcon1_DoubleClick); _posQueue = new System.Collections.Queue(); _pageQueue = new System.Collections.Queue(); _taskTimer = new System.Threading.Timer(new TimerCallback(CheckTime)); _taskTimer.Change(0, 1000); IList<Log> logs = Log.GetLogs(); if (logs.Count != 0) { this.label20.Text = logs[logs.Count - 1].EndTime.ToString(); this.label22.Text = logs[logs.Count - 1].ErrorSiteCount.ToString(); this.label24.Text = logs[logs.Count - 1].CheckSiteCount.ToString(); } }
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....."); } }
internal Connection(ref System.Net.Sockets.TcpClient TCPClient, ref Logger logger) { log = logger; log.Context = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName + "." + System.Reflection.MethodBase.GetCurrentMethod().Name; m_TCPClient = TCPClient; m_bConnected = true; m_iBufferMaxLength = 2048; m_iBufferLength = 0; m_bytesIncomingBuffer = new byte[m_iBufferMaxLength]; m_bDone = false; m_ThreadReceiveDataAndEnqueue = new System.Threading.Thread(new System.Threading.ThreadStart(this.ReceiveDataAndEnqueue)); m_ThreadDequeAndExecute = new System.Threading.Thread(new System.Threading.ThreadStart(this.DequeAndExecuteCommands)); m_ThreadIsConnectionAlive = new System.Threading.Thread(new System.Threading.ThreadStart(this.IsConnectionAlive)); m_qCommands = System.Collections.Queue.Synchronized(new System.Collections.Queue()); m_EventThreadComplete = new System.Threading.ManualResetEvent[] { new System.Threading.ManualResetEvent(false), new System.Threading.ManualResetEvent(false) }; m_bStarted = false; }
public Connection(ref System.Net.Sockets.TcpClient TCPClient, System.Threading.ManualResetEvent eventChannelConnectionComplete, ref CarverLab.Utility.Logger logger) { log = logger; log.Context = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName + "." + System.Reflection.MethodBase.GetCurrentMethod().Name; m_TCPClient = TCPClient; m_bConnected = false; m_iBufferMaxLength = 2048; m_iBufferLength = 0; m_bytesIncomingBuffer = new byte[m_iBufferMaxLength]; m_bDone = false; m_ThreadReceiveDataAndEnqueue = new System.Threading.Thread(new System.Threading.ThreadStart(this.ReceiveDataAndEnqueue)); m_ThreadAutomaticDequeue = new System.Threading.Thread(new System.Threading.ThreadStart(this.DequeCommands)); m_ThreadIsConnectionAlive = new System.Threading.Thread(new System.Threading.ThreadStart(this.IsConnectionAlive)); m_qCommands = System.Collections.Queue.Synchronized(new System.Collections.Queue()); m_EventChannelConnectionComplete = eventChannelConnectionComplete; m_EventChannelConnectionComplete.Reset(); m_EventMessageAvailable = new System.Threading.AutoResetEvent(false); m_EventThreadComplete = new System.Threading.ManualResetEvent(false); m_bIsRunning = false; m_bAutomaticDequeueingSuspended = false; m_EventAutomaticQueueing = new System.Threading.ManualResetEvent(true); }
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 { ; } } }
/// <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; }
/// <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; }
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 { ;} } } }
/* 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(); }
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("<<<"); }
// We need this to make the use of the property as an attribute // light-weight. This allows us to delay initialize everything we // need to fully function as a ContextProperty. internal virtual void InitIfNecessary() { lock(this) { if (_asyncWorkEvent == null) { // initialize thread pool event to non-signaled state. _asyncWorkEvent = new AutoResetEvent(false); _workItemQueue = new Queue(); _asyncLcidList = new ArrayList(); WaitOrTimerCallback callBackDelegate = new WaitOrTimerCallback(this.DispatcherCallBack); // Register a callback to be executed by the thread-pool // each time the event is signaled. _waitHandle = ThreadPool.RegisterWaitForSingleObject( _asyncWorkEvent, callBackDelegate, null, // state info _timeOut, false); // bExecuteOnlyOnce } } }
internal CommandEventArgs(byte [] byteRawData, System.Collections.Queue qCommands) { m_byteRawData = byteRawData; m_qCommands = System.Collections.Queue.Synchronized(new System.Collections.Queue(qCommands)); }
/// <summary> /// Class constructor. /// </summary> public TriggerQueue() { _queue = System.Collections.Queue.Synchronized(new System.Collections.Queue()); }
/// <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 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; }
public CommandEventArgs(byte [] byteRawData, ref System.Collections.Queue qCommands) { m_byteRawData = byteRawData; // m_qCommands = System.Collections.Queue.Synchronized(new System.Collections.Queue(qCommands)); m_qCommands = qCommands; }
public Agent(string name) { InitializeComponent(); this.characterName = name; this.cachedBitmapImageDictionary = new Dictionary<string, BitmapImage>(); this.cachedMotionList = new List<Motion>(); this.fadeStoryboardDictionary = new Dictionary<Storyboard, Window>(); this.imageStoryboardDictionary = new Dictionary<Image, Storyboard>(); this.queue = new System.Collections.Queue(); this.motionQueue = new Queue<Motion>(); this.ContextMenu = new ContextMenu(); MenuItem opacityMenuItem = new MenuItem(); MenuItem scalingMenuItem = new MenuItem(); MenuItem refreshMenuItem = new MenuItem(); MenuItem topmostMenuItem = new MenuItem(); MenuItem showInTaskbarMenuItem = new MenuItem(); MenuItem muteMenuItem = new MenuItem(); MenuItem charactersMenuItem = new MenuItem(); MenuItem updateMenuItem = new MenuItem(); MenuItem exitMenuItem = new MenuItem(); double opacity = 1; double scale = 2; opacityMenuItem.Header = Properties.Resources.Opacity; do { MenuItem menuItem = new MenuItem(); menuItem.Header = String.Concat(((int)Math.Floor(opacity * 100)).ToString(System.Globalization.CultureInfo.CurrentCulture), Properties.Resources.Percent); menuItem.Tag = opacity; menuItem.Click += new RoutedEventHandler(delegate { foreach (Window window in Application.Current.Windows) { Agent agent = window as Agent; if (agent != null) { agent.opacity = (double)menuItem.Tag; Storyboard storyboard1 = new Storyboard(); DoubleAnimation doubleAnimation1 = new DoubleAnimation(agent.Opacity, agent.opacity, TimeSpan.FromMilliseconds(500)); foreach (KeyValuePair<Storyboard, Window> kvp in agent.fadeStoryboardDictionary) { kvp.Key.Stop(kvp.Value); } agent.fadeStoryboardDictionary.Clear(); if (agent.Opacity < agent.opacity) { SineEase sineEase = new SineEase(); sineEase.EasingMode = EasingMode.EaseOut; doubleAnimation1.EasingFunction = sineEase; } else if (agent.Opacity > agent.opacity) { SineEase sineEase = new SineEase(); sineEase.EasingMode = EasingMode.EaseIn; doubleAnimation1.EasingFunction = sineEase; } doubleAnimation1.CurrentStateInvalidated += new EventHandler(delegate (object s, EventArgs e) { if (((Clock)s).CurrentState == ClockState.Filling) { agent.Opacity = agent.opacity; storyboard1.Remove(agent); agent.fadeStoryboardDictionary.Remove(storyboard1); } }); storyboard1.Children.Add(doubleAnimation1); Storyboard.SetTargetProperty(doubleAnimation1, new PropertyPath(Window.OpacityProperty)); agent.fadeStoryboardDictionary.Add(storyboard1, agent); agent.BeginStoryboard(storyboard1, HandoffBehavior.SnapshotAndReplace, true); if (agent.balloon.Opacity != 1) { Storyboard storyboard2 = new Storyboard(); DoubleAnimation doubleAnimation2 = new DoubleAnimation(agent.balloon.Opacity, 1, TimeSpan.FromMilliseconds(500)); SineEase sineEase = new SineEase(); sineEase.EasingMode = EasingMode.EaseOut; doubleAnimation2.EasingFunction = sineEase; doubleAnimation2.CurrentStateInvalidated += new EventHandler(delegate (object s, EventArgs e) { if (((Clock)s).CurrentState == ClockState.Filling) { agent.balloon.Opacity = 1; storyboard2.Remove(agent.balloon); agent.fadeStoryboardDictionary.Remove(storyboard2); } }); storyboard2.Children.Add(doubleAnimation2); Storyboard.SetTargetProperty(doubleAnimation2, new PropertyPath(Window.OpacityProperty)); agent.fadeStoryboardDictionary.Add(storyboard2, agent.balloon); agent.balloon.BeginStoryboard(storyboard2, HandoffBehavior.SnapshotAndReplace, true); } } } }); opacityMenuItem.Items.Add(menuItem); opacity -= 0.1; } while (Math.Floor(opacity * 100) > 0); scalingMenuItem.Header = Properties.Resources.Scaling; do { MenuItem menuItem = new MenuItem(); menuItem.Header = String.Concat(((int)Math.Floor(scale * 100)).ToString(System.Globalization.CultureInfo.CurrentCulture), Properties.Resources.Percent); menuItem.Tag = scale; menuItem.Click += new RoutedEventHandler(delegate { foreach (Window window in Application.Current.Windows) { Agent agent = window as Agent; if (agent != null) { agent.scale = (double)menuItem.Tag; foreach (Character character in from character in Script.Instance.Characters where character.Name.Equals(agent.characterName) select character) { Storyboard storyboard = new Storyboard(); DoubleAnimation doubleAnimation1 = new DoubleAnimation(agent.ZoomScaleTransform.ScaleX, agent.scale, TimeSpan.FromMilliseconds(500)); DoubleAnimation doubleAnimation2 = new DoubleAnimation(agent.ZoomScaleTransform.ScaleY, agent.scale, TimeSpan.FromMilliseconds(500)); DoubleAnimation doubleAnimation3 = new DoubleAnimation(agent.LayoutRoot.Width, character.Size.Width * agent.scale, TimeSpan.FromMilliseconds(500)); DoubleAnimation doubleAnimation4 = new DoubleAnimation(agent.LayoutRoot.Height, character.Size.Height * agent.scale, TimeSpan.FromMilliseconds(500)); if (agent.scaleStoryboard != null) { agent.scaleStoryboard.Stop(agent.LayoutRoot); } if (agent.ZoomScaleTransform.ScaleX < agent.scale) { SineEase sineEase = new SineEase(); sineEase.EasingMode = EasingMode.EaseOut; doubleAnimation1.EasingFunction = sineEase; } else if (agent.ZoomScaleTransform.ScaleX > agent.scale) { SineEase sineEase = new SineEase(); sineEase.EasingMode = EasingMode.EaseIn; doubleAnimation1.EasingFunction = sineEase; } if (agent.ZoomScaleTransform.ScaleY < agent.scale) { SineEase sineEase = new SineEase(); sineEase.EasingMode = EasingMode.EaseOut; doubleAnimation2.EasingFunction = sineEase; } else if (agent.ZoomScaleTransform.ScaleY > agent.scale) { SineEase sineEase = new SineEase(); sineEase.EasingMode = EasingMode.EaseIn; doubleAnimation2.EasingFunction = sineEase; } if (agent.LayoutRoot.Width < character.Size.Width * agent.scale) { SineEase sineEase = new SineEase(); sineEase.EasingMode = EasingMode.EaseOut; doubleAnimation3.EasingFunction = sineEase; } else if (agent.LayoutRoot.Width > character.Size.Width * agent.scale) { SineEase sineEase = new SineEase(); sineEase.EasingMode = EasingMode.EaseIn; doubleAnimation3.EasingFunction = sineEase; } if (agent.LayoutRoot.Height < character.Size.Height * agent.scale) { SineEase sineEase = new SineEase(); sineEase.EasingMode = EasingMode.EaseOut; doubleAnimation4.EasingFunction = sineEase; } else if (agent.LayoutRoot.Height > character.Size.Height * agent.scale) { SineEase sineEase = new SineEase(); sineEase.EasingMode = EasingMode.EaseIn; doubleAnimation4.EasingFunction = sineEase; } storyboard.CurrentStateInvalidated += new EventHandler(delegate (object s, EventArgs e) { if (((Clock)s).CurrentState == ClockState.Filling) { agent.ZoomScaleTransform.ScaleX = agent.scale; agent.ZoomScaleTransform.ScaleY = agent.scale; foreach (Character c in from c in Script.Instance.Characters where c.Name.Equals(agent.characterName) select c) { agent.LayoutRoot.Width = c.Size.Width * agent.scale; agent.LayoutRoot.Height = c.Size.Height * agent.scale; } storyboard.Remove(agent.LayoutRoot); agent.scaleStoryboard = null; } }); storyboard.Children.Add(doubleAnimation1); storyboard.Children.Add(doubleAnimation2); storyboard.Children.Add(doubleAnimation3); storyboard.Children.Add(doubleAnimation4); Storyboard.SetTargetProperty(doubleAnimation1, new PropertyPath("(0).(1).(2)", ContentControl.ContentProperty, Canvas.RenderTransformProperty, ScaleTransform.ScaleXProperty)); Storyboard.SetTargetProperty(doubleAnimation2, new PropertyPath("(0).(1).(2)", ContentControl.ContentProperty, Canvas.RenderTransformProperty, ScaleTransform.ScaleYProperty)); Storyboard.SetTargetProperty(doubleAnimation3, new PropertyPath(ContentControl.WidthProperty)); Storyboard.SetTargetProperty(doubleAnimation4, new PropertyPath(ContentControl.HeightProperty)); agent.scaleStoryboard = storyboard; agent.LayoutRoot.BeginStoryboard(storyboard, HandoffBehavior.SnapshotAndReplace, true); } } } }); scalingMenuItem.Items.Add(menuItem); scale -= 0.25; } while (Math.Floor(scale * 100) > 0); refreshMenuItem.Header = Properties.Resources.Refresh; refreshMenuItem.Click += new RoutedEventHandler(delegate { foreach (Window window in Application.Current.Windows) { Agent agent = window as Agent; if (agent != null) { agent.Render(); } } }); topmostMenuItem.Header = Properties.Resources.Topmost; topmostMenuItem.IsCheckable = true; topmostMenuItem.Click += new RoutedEventHandler(delegate { foreach (Window window in Application.Current.Windows) { if (window is Agent && window == Application.Current.MainWindow) { window.Topmost = topmostMenuItem.IsChecked; } } }); showInTaskbarMenuItem.Header = Properties.Resources.ShowInTaskbar; showInTaskbarMenuItem.IsCheckable = true; showInTaskbarMenuItem.Click += new RoutedEventHandler(delegate { foreach (Window window in Application.Current.Windows) { if (window is Agent) { window.ShowInTaskbar = showInTaskbarMenuItem.IsChecked; } } }); muteMenuItem.Header = Properties.Resources.Mute; muteMenuItem.IsCheckable = true; muteMenuItem.Click += new RoutedEventHandler(delegate { foreach (Window window in Application.Current.Windows) { Agent agent = window as Agent; if (agent != null) { agent.isMute = muteMenuItem.IsChecked; } } }); charactersMenuItem.Header = Properties.Resources.Characters; updateMenuItem.Header = Properties.Resources.Update; updateMenuItem.Click += new RoutedEventHandler(delegate { Script.Instance.Update(true); }); exitMenuItem.Header = Properties.Resources.Exit; exitMenuItem.Click += new RoutedEventHandler(delegate { if (Script.Instance.Enabled) { Script.Instance.Enabled = false; } }); this.ContextMenu.Items.Add(opacityMenuItem); this.ContextMenu.Items.Add(scalingMenuItem); this.ContextMenu.Items.Add(refreshMenuItem); this.ContextMenu.Items.Add(new Separator()); this.ContextMenu.Items.Add(topmostMenuItem); this.ContextMenu.Items.Add(showInTaskbarMenuItem); this.ContextMenu.Items.Add(new Separator()); this.ContextMenu.Items.Add(muteMenuItem); this.ContextMenu.Items.Add(new Separator()); this.ContextMenu.Items.Add(charactersMenuItem); this.ContextMenu.Items.Add(new Separator()); this.ContextMenu.Items.Add(updateMenuItem); this.ContextMenu.Items.Add(new Separator()); this.ContextMenu.Items.Add(exitMenuItem); this.ContextMenu.Opened += new RoutedEventHandler(delegate { Agent agent = Application.Current.MainWindow as Agent; if (agent != null) { foreach (MenuItem menuItem in opacityMenuItem.Items) { menuItem.IsChecked = Math.Floor((double)menuItem.Tag * 100) == Math.Floor(agent.Opacity * 100); } foreach (MenuItem menuItem in scalingMenuItem.Items) { menuItem.IsChecked = Math.Floor((double)menuItem.Tag * 100) == Math.Floor(agent.ZoomScaleTransform.ScaleX * 100) && Math.Floor((double)menuItem.Tag * 100) == Math.Floor(agent.ZoomScaleTransform.ScaleY * 100); } topmostMenuItem.IsChecked = agent.Topmost; showInTaskbarMenuItem.IsChecked = agent.ShowInTaskbar; muteMenuItem.IsChecked = agent.isMute; List<MenuItem> menuItemList = new List<MenuItem>(charactersMenuItem.Items.Cast<MenuItem>()); HashSet<string> pathHashSet = new HashSet<string>(); LinkedList<KeyValuePair<Character, string>> characterLinkedList = new LinkedList<KeyValuePair<Character, string>>(); foreach (Character character in Script.Instance.Characters) { string path = Path.IsPathRooted(character.Script) ? character.Script : Path.GetFullPath(character.Script); if (!pathHashSet.Contains(path)) { pathHashSet.Add(path); } characterLinkedList.AddLast(new KeyValuePair<Character, string>(character, path)); } List<KeyValuePair<string, string>> keyValuePairList = (from fileName in Directory.EnumerateFiles(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "*", SearchOption.AllDirectories) let extension = Path.GetExtension(fileName) let isZip = extension.Equals(".zip", StringComparison.OrdinalIgnoreCase) where isZip || extension.Equals(".xml", StringComparison.OrdinalIgnoreCase) select new KeyValuePair<bool, string>(isZip, fileName)).Concat(from path in pathHashSet select new KeyValuePair<bool, string>(Path.GetExtension(path).Equals(".zip", StringComparison.OrdinalIgnoreCase), path)).Aggregate<KeyValuePair<bool, string>, List<KeyValuePair<string, string>>>(new List<KeyValuePair<string, string>>(), (list, kvp1) => { if (!list.Exists(delegate (KeyValuePair<string, string> kvp2) { return kvp2.Value.Equals(kvp1.Value); })) { if (kvp1.Key) { FileStream fs = null; try { fs = new FileStream(kvp1.Value, FileMode.Open, FileAccess.Read, FileShare.Read); using (ZipArchive zipArchive = new ZipArchive(fs)) { fs = null; foreach (ZipArchiveEntry zipArchiveEntry in from zipArchiveEntry in zipArchive.Entries where zipArchiveEntry.FullName.EndsWith(".xml", StringComparison.OrdinalIgnoreCase) select zipArchiveEntry) { Stream stream = null; try { stream = zipArchiveEntry.Open(); foreach (string attribute in from attribute in ((System.Collections.IEnumerable)XDocument.Load(stream).XPathEvaluate("/script/character/@name")).Cast<XAttribute>() select attribute.Value) { list.Add(new KeyValuePair<string, string>(attribute, kvp1.Value)); } } catch { return list; } finally { if (stream != null) { stream.Close(); } } } } } finally { if (fs != null) { fs.Close(); } } } else { FileStream fs = null; try { fs = new FileStream(kvp1.Value, FileMode.Open, FileAccess.Read, FileShare.Read); foreach (string attribute in from attribute in ((System.Collections.IEnumerable)XDocument.Load(fs).XPathEvaluate("/script/character/@name")).Cast<XAttribute>() select attribute.Value) { list.Add(new KeyValuePair<string, string>(attribute, kvp1.Value)); } } catch { return list; } finally { if (fs != null) { fs.Close(); } } } } return list; }); charactersMenuItem.Items.Clear(); keyValuePairList.Sort(delegate (KeyValuePair<string, string> kvp1, KeyValuePair<string, string> kvp2) { return String.Compare(kvp1.Key, kvp2.Key, StringComparison.CurrentCulture); }); keyValuePairList.ForEach(delegate (KeyValuePair<string, string> kvp) { for (LinkedListNode<KeyValuePair<Character, string>> nextLinkedListNode = characterLinkedList.First; nextLinkedListNode != null; nextLinkedListNode = nextLinkedListNode.Next) { if (nextLinkedListNode.Value.Key.Name.Equals(kvp.Key) && nextLinkedListNode.Value.Value.Equals(kvp.Value)) { MenuItem selectedMenuItem = menuItemList.Find(delegate (MenuItem menuItem) { return kvp.Key.Equals(menuItem.Header as string) && kvp.Value.Equals(menuItem.Tag as string) && (menuItem.IsChecked || menuItem.HasItems); }); if (selectedMenuItem == null) { selectedMenuItem = new MenuItem(); selectedMenuItem.Header = kvp.Key; selectedMenuItem.Tag = kvp.Value; } else { selectedMenuItem.Items.Clear(); menuItemList.Remove(selectedMenuItem); } charactersMenuItem.Items.Add(selectedMenuItem); List<MenuItem> childMenuItemList = new List<MenuItem>(); Dictionary<string, SortedSet<int>> dictionary = new Dictionary<string, SortedSet<int>>(); List<string> motionTypeList = new List<string>(); this.cachedMotionList.ForEach(delegate (Motion motion) { if (motion.Type != null) { SortedSet<int> sortedSet; if (dictionary.TryGetValue(motion.Type, out sortedSet)) { if (!sortedSet.Contains(motion.ZIndex)) { sortedSet.Add(motion.ZIndex); } } else { sortedSet = new SortedSet<int>(); sortedSet.Add(motion.ZIndex); dictionary.Add(motion.Type, sortedSet); motionTypeList.Add(motion.Type); } } }); motionTypeList.Sort(delegate (string s1, string s2) { return String.Compare(s1, s2, StringComparison.CurrentCulture); }); motionTypeList.ForEach(delegate (string type) { foreach (MenuItem menuItem in selectedMenuItem.Items) { if (type.Equals(menuItem.Header as string)) { if (nextLinkedListNode.Value.Key.HasTypes) { menuItem.IsChecked = nextLinkedListNode.Value.Key.Types.Contains(menuItem.Header as string); } else { menuItem.IsChecked = false; } childMenuItemList.Add(menuItem); return; } } MenuItem childMenuItem = new MenuItem(); childMenuItem.Header = type; childMenuItem.Tag = nextLinkedListNode.Value.Key.Name; childMenuItem.Click += new RoutedEventHandler(delegate { string tag = childMenuItem.Tag as string; if (tag != null) { foreach (Character c in from c in Script.Instance.Characters where c.Name.Equals(tag) select c) { foreach (Window window in Application.Current.Windows) { Agent a = window as Agent; if (a != null && c.Name.Equals(a.characterName)) { string header = childMenuItem.Header as string; a.Render(); if (c.Types.Contains(header)) { c.Types.Remove(header); } else if (header != null) { SortedSet<int> sortedSet1; if (dictionary.TryGetValue(header, out sortedSet1)) { foreach (string s in c.Types.ToArray()) { SortedSet<int> sortedSet2; if (dictionary.TryGetValue(s, out sortedSet2) && sortedSet1.SequenceEqual(sortedSet2)) { c.Types.Remove(s); } } } c.Types.Add(header); } foreach (Image image in a.Canvas.Children.Cast<Image>()) { Image i = image; Motion motion = i.Tag as Motion; if (motion != null) { List<string> typeList = null; bool isVisible; if (motion.Type == null) { typeList = new List<string>(); a.cachedMotionList.ForEach(delegate (Motion m) { if (m.ZIndex == motion.ZIndex) { typeList.Add(m.Type); } }); } if (typeList == null) { if (c.HasTypes) { typeList = new List<string>(); a.cachedMotionList.ForEach(delegate (Motion m) { if (m.ZIndex == motion.ZIndex && c.Types.Contains(m.Type)) { typeList.Add(m.Type); } }); isVisible = typeList.Count > 0 && typeList.LastIndexOf(motion.Type) == typeList.Count - 1; } else { isVisible = false; } } else if (c.HasTypes) { isVisible = !typeList.Exists(delegate (string t) { return c.Types.Contains(t); }); } else { isVisible = true; } if (isVisible && (i.Visibility != Visibility.Visible || i.OpacityMask != null)) { LinearGradientBrush linearGradientBrush = i.OpacityMask as LinearGradientBrush; if (linearGradientBrush == null) { GradientStopCollection gradientStopCollection = new GradientStopCollection(); gradientStopCollection.Add(new GradientStop(Color.FromArgb(0, 0, 0, 0), 0)); gradientStopCollection.Add(new GradientStop(Color.FromArgb(0, 0, 0, 0), 1)); i.OpacityMask = linearGradientBrush = new LinearGradientBrush(gradientStopCollection, new Point(0.5, 0), new Point(0.5, 1)); } Storyboard storyboard; ColorAnimation colorAnimation1 = new ColorAnimation(linearGradientBrush.GradientStops[0].Color, Color.FromArgb(Byte.MaxValue, 0, 0, 0), TimeSpan.FromMilliseconds(250)); ColorAnimation colorAnimation2 = new ColorAnimation(linearGradientBrush.GradientStops[1].Color, Color.FromArgb(Byte.MaxValue, 0, 0, 0), TimeSpan.FromMilliseconds(250)); SineEase sineEase1 = new SineEase(); SineEase sineEase2 = new SineEase(); if (a.imageStoryboardDictionary.TryGetValue(i, out storyboard)) { storyboard.Stop(i); a.imageStoryboardDictionary[i] = storyboard = new Storyboard(); } else { storyboard = new Storyboard(); a.imageStoryboardDictionary.Add(i, storyboard); } sineEase1.EasingMode = sineEase2.EasingMode = EasingMode.EaseInOut; colorAnimation1.EasingFunction = sineEase1; colorAnimation2.BeginTime = TimeSpan.FromMilliseconds(250); colorAnimation2.EasingFunction = sineEase2; storyboard.CurrentStateInvalidated += new EventHandler(delegate (object s, EventArgs e) { if (((Clock)s).CurrentState == ClockState.Filling) { i.OpacityMask = null; a.Render(); storyboard.Remove(i); a.imageStoryboardDictionary.Remove(i); } }); storyboard.Children.Add(colorAnimation1); storyboard.Children.Add(colorAnimation2); Storyboard.SetTargetProperty(colorAnimation1, new PropertyPath("(0).(1)[0].(2)", Image.OpacityMaskProperty, LinearGradientBrush.GradientStopsProperty, GradientStop.ColorProperty)); Storyboard.SetTargetProperty(colorAnimation2, new PropertyPath("(0).(1)[1].(2)", Image.OpacityMaskProperty, LinearGradientBrush.GradientStopsProperty, GradientStop.ColorProperty)); i.Visibility = Visibility.Visible; i.BeginStoryboard(storyboard, HandoffBehavior.SnapshotAndReplace, true); } else if (!isVisible && (i.Visibility == Visibility.Visible || i.OpacityMask != null)) { LinearGradientBrush linearGradientBrush = i.OpacityMask as LinearGradientBrush; if (linearGradientBrush == null) { GradientStopCollection gradientStopCollection = new GradientStopCollection(); gradientStopCollection.Add(new GradientStop(Color.FromArgb(Byte.MaxValue, 0, 0, 0), 0)); gradientStopCollection.Add(new GradientStop(Color.FromArgb(Byte.MaxValue, 0, 0, 0), 1)); i.OpacityMask = linearGradientBrush = new LinearGradientBrush(gradientStopCollection, new Point(0.5, 0), new Point(0.5, 1)); } Storyboard storyboard; ColorAnimation colorAnimation1 = new ColorAnimation(linearGradientBrush.GradientStops[0].Color, Color.FromArgb(0, 0, 0, 0), TimeSpan.FromMilliseconds(250)); ColorAnimation colorAnimation2 = new ColorAnimation(linearGradientBrush.GradientStops[1].Color, Color.FromArgb(0, 0, 0, 0), TimeSpan.FromMilliseconds(250)); SineEase sineEase1 = new SineEase(); SineEase sineEase2 = new SineEase(); if (a.imageStoryboardDictionary.TryGetValue(i, out storyboard)) { storyboard.Stop(i); a.imageStoryboardDictionary[i] = storyboard = new Storyboard(); } else { storyboard = new Storyboard(); a.imageStoryboardDictionary.Add(i, storyboard); } sineEase1.EasingMode = sineEase2.EasingMode = EasingMode.EaseInOut; colorAnimation1.EasingFunction = sineEase1; colorAnimation2.BeginTime = TimeSpan.FromMilliseconds(250); colorAnimation2.EasingFunction = sineEase2; storyboard.CurrentStateInvalidated += new EventHandler(delegate (object s, EventArgs e) { if (((Clock)s).CurrentState == ClockState.Filling) { i.OpacityMask = null; a.Render(); storyboard.Remove(i); a.imageStoryboardDictionary.Remove(i); } }); storyboard.Children.Add(colorAnimation1); storyboard.Children.Add(colorAnimation2); Storyboard.SetTargetProperty(colorAnimation1, new PropertyPath("(0).(1)[0].(2)", Image.OpacityMaskProperty, LinearGradientBrush.GradientStopsProperty, GradientStop.ColorProperty)); Storyboard.SetTargetProperty(colorAnimation2, new PropertyPath("(0).(1)[1].(2)", Image.OpacityMaskProperty, LinearGradientBrush.GradientStopsProperty, GradientStop.ColorProperty)); i.BeginStoryboard(storyboard, HandoffBehavior.SnapshotAndReplace, true); } } } } } } } }); if (nextLinkedListNode.Value.Key.HasTypes) { childMenuItem.IsChecked = nextLinkedListNode.Value.Key.Types.Contains(childMenuItem.Header as string); } else { childMenuItem.IsChecked = false; } childMenuItemList.Add(childMenuItem); }); selectedMenuItem.Items.Clear(); if (childMenuItemList.Count > 0) { selectedMenuItem.IsChecked = false; childMenuItemList.ForEach(delegate (MenuItem mi) { selectedMenuItem.Items.Add(mi); }); } else { selectedMenuItem.IsChecked = true; } characterLinkedList.Remove(nextLinkedListNode); return; } } MenuItem unselectedMenuItem = menuItemList.Find(delegate (MenuItem menuItem) { return kvp.Key.Equals(menuItem.Header as string) && kvp.Value.Equals(menuItem.Tag as string) && !menuItem.IsChecked && !menuItem.HasItems; }); if (unselectedMenuItem == null) { unselectedMenuItem = new MenuItem(); unselectedMenuItem.Header = kvp.Key; unselectedMenuItem.Tag = kvp.Value; unselectedMenuItem.Click += new RoutedEventHandler(delegate { string tag = unselectedMenuItem.Tag as string; if (tag != null) { List<Character> characterList = new List<Character>(); if (Path.GetExtension(tag).Equals(".zip", StringComparison.OrdinalIgnoreCase)) { FileStream fs = null; try { fs = new FileStream(tag, FileMode.Open, FileAccess.Read, FileShare.Read); using (ZipArchive zipArchive = new ZipArchive(fs)) { fs = null; StringBuilder stringBuilder = new StringBuilder(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)); if (Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location).LastIndexOf(Path.DirectorySeparatorChar) != Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location).Length - 1) { stringBuilder.Append(Path.DirectorySeparatorChar); } string path = tag.StartsWith(stringBuilder.ToString(), StringComparison.Ordinal) ? tag.Remove(0, stringBuilder.Length) : tag; foreach (ZipArchiveEntry zipArchiveEntry in from zipArchiveEntry in zipArchive.Entries where zipArchiveEntry.FullName.EndsWith(".xml", StringComparison.OrdinalIgnoreCase) select zipArchiveEntry) { Stream stream = null; try { stream = zipArchiveEntry.Open(); foreach (string a in from a in ((System.Collections.IEnumerable)XDocument.Load(stream).XPathEvaluate("/script/character/@name")).Cast<XAttribute>() select a.Value) { Character character = new Character(); character.Name = a; character.Script = path; characterList.Add(character); } } catch { return; } finally { if (stream != null) { stream.Close(); } } } } } finally { if (fs != null) { fs.Close(); } } } else { FileStream fs = null; try { fs = new FileStream(tag, FileMode.Open, FileAccess.Read, FileShare.Read); StringBuilder stringBuilder = new StringBuilder(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)); if (Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location).LastIndexOf(Path.DirectorySeparatorChar) != Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location).Length - 1) { stringBuilder.Append(Path.DirectorySeparatorChar); } string path = tag.StartsWith(stringBuilder.ToString(), StringComparison.Ordinal) ? tag.Remove(0, stringBuilder.Length) : tag; foreach (string a in from a in ((System.Collections.IEnumerable)XDocument.Load(fs).XPathEvaluate("/script/character/@name")).Cast<XAttribute>() select a.Value) { Character character = new Character(); character.Name = a; character.Script = path; characterList.Add(character); } } catch { return; } finally { if (fs != null) { fs.Close(); } } } if (characterList.Count > 0) { Switch(characterList); } } }); } else { menuItemList.Remove(unselectedMenuItem); } charactersMenuItem.Items.Add(unselectedMenuItem); }); } }); if (this == Application.Current.MainWindow) { System.Configuration.Configuration config = null; string directory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), System.Reflection.Assembly.GetExecutingAssembly().GetName().Name); if (Directory.Exists(directory)) { string fileName = Path.GetFileName(System.Reflection.Assembly.GetExecutingAssembly().Location); foreach (string s in from s in Directory.EnumerateFiles(directory, "*.config") where fileName.Equals(Path.GetFileNameWithoutExtension(s)) select s) { System.Configuration.ExeConfigurationFileMap exeConfigurationFileMap = new System.Configuration.ExeConfigurationFileMap(); exeConfigurationFileMap.ExeConfigFilename = s; config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(exeConfigurationFileMap, System.Configuration.ConfigurationUserLevel.None); } } if (config == null) { config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None); } if (config.AppSettings.Settings["Left"] != null && config.AppSettings.Settings["Top"] != null) { if (config.AppSettings.Settings["Left"].Value.Length > 0 && config.AppSettings.Settings["Top"].Value.Length > 0) { this.Left = Double.Parse(config.AppSettings.Settings["Left"].Value, System.Globalization.CultureInfo.InvariantCulture); this.Top = Double.Parse(config.AppSettings.Settings["Top"].Value, System.Globalization.CultureInfo.InvariantCulture); } } if (config.AppSettings.Settings["Opacity"] != null) { if (config.AppSettings.Settings["Opacity"].Value.Length > 0) { this.opacity = Double.Parse(config.AppSettings.Settings["Opacity"].Value, System.Globalization.CultureInfo.InvariantCulture); } } if (config.AppSettings.Settings["Scale"] != null) { if (config.AppSettings.Settings["Scale"].Value.Length > 0) { this.scale = this.ZoomScaleTransform.ScaleX = this.ZoomScaleTransform.ScaleY = Double.Parse(config.AppSettings.Settings["Scale"].Value, System.Globalization.CultureInfo.InvariantCulture); } } if (config.AppSettings.Settings["Topmost"] != null) { if (config.AppSettings.Settings["Topmost"].Value.Length > 0) { this.Topmost = Boolean.Parse(config.AppSettings.Settings["Topmost"].Value); } } if (config.AppSettings.Settings["ShowInTaskbar"] != null) { if (config.AppSettings.Settings["ShowInTaskbar"].Value.Length > 0) { this.ShowInTaskbar = Boolean.Parse(config.AppSettings.Settings["ShowInTaskbar"].Value); } } if (config.AppSettings.Settings["DropShadow"] != null) { if (config.AppSettings.Settings["DropShadow"].Value.Length > 0) { if (Boolean.Parse(config.AppSettings.Settings["DropShadow"].Value)) { DropShadowEffect dropShadowEffect = new DropShadowEffect(); dropShadowEffect.Color = Colors.Black; dropShadowEffect.BlurRadius = 10; dropShadowEffect.Direction = 270; dropShadowEffect.ShadowDepth = 0; dropShadowEffect.Opacity = 0.5; if (dropShadowEffect.CanFreeze) { dropShadowEffect.Freeze(); } this.Canvas.Effect = dropShadowEffect; } } } if (config.AppSettings.Settings["Mute"] != null) { if (config.AppSettings.Settings["Mute"].Value.Length > 0) { this.isMute = Boolean.Parse(config.AppSettings.Settings["Mute"].Value); } } if (config.AppSettings.Settings["FrameRate"] != null) { if (config.AppSettings.Settings["FrameRate"].Value.Length > 0) { this.frameRate = Double.Parse(config.AppSettings.Settings["FrameRate"].Value, System.Globalization.CultureInfo.InvariantCulture); } } } else { Agent agent = Application.Current.MainWindow as Agent; if (agent != null) { this.opacity = agent.opacity; this.scale = this.ZoomScaleTransform.ScaleX = this.ZoomScaleTransform.ScaleY = agent.scale; this.Topmost = agent.Topmost; this.ShowInTaskbar = agent.ShowInTaskbar; if (agent.Canvas.Effect != null) { DropShadowEffect dropShadowEffect = new DropShadowEffect(); dropShadowEffect.Color = Colors.Black; dropShadowEffect.BlurRadius = 10; dropShadowEffect.Direction = 270; dropShadowEffect.ShadowDepth = 0; dropShadowEffect.Opacity = 0.5; if (dropShadowEffect.CanFreeze) { dropShadowEffect.Freeze(); } this.Canvas.Effect = dropShadowEffect; } this.isMute = agent.isMute; this.frameRate = agent.frameRate; } } this.balloon = new Balloon(); this.balloon.Title = this.Title; this.balloon.SizeChanged += new SizeChangedEventHandler(delegate (object s, SizeChangedEventArgs e) { foreach (Character character in from character in Script.Instance.Characters where character.Name.Equals(this.characterName) select character) { this.balloon.Left = this.Left + (this.Width - e.NewSize.Width) / 2; this.balloon.Top = this.Top - e.NewSize.Height + character.Origin.Y * this.ZoomScaleTransform.ScaleY; } }); this.Dispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(delegate { Run(); return null; }), null); Microsoft.Win32.SystemEvents.PowerModeChanged += new Microsoft.Win32.PowerModeChangedEventHandler(this.OnPowerModeChanged); }
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); } }
static void Main(string[] args) { Pubsub p = new Pubsub(); /* List<object> obj = new List<object>(); for (int i = 0; i < 4000000; i++) obj.Add(new object()); for(int i = 0; i < 4; i++) { var n = i * 100000; var t = new Thread(() => { for(int j= n;j<n+100000;j++) { p.Subscribe("a.b.c", obj[j]); } }); t.Start(); } for (int i = 0; i < 4; i++) { var n = i * 100000; var t = new Thread(() => { for (int j = n; j < n + 100000; j++) { p.Unsubscribe("a.b.c", obj[j]); } }); t.Start(); } */ var obj2 = new object(); //p.Subscribe("a.b.c", new object()); p.Subscribe("a.b.c", obj2); p.Subscribe("a.b.d", obj2); p.Subscribe("a.b.e", obj2); p.Subscribe("a.b.e", new object()); ///p.Unsubscribe("a.b.c", obj2); p.Publish("a.b.*", "A"); p.Print(); p.Unsubscribe("a.b.e", obj2); p.Unsubscribe("a.b.c", obj2); p.Print(); System.Collections.Queue q = new System.Collections.Queue(); }
internal ConnectionEventArgs(byte [] byteRawData, OCTLNET.eStates eState, System.Collections.Queue qCommands) { m_eState = eState; m_byteRawData = byteRawData; m_qCommands = System.Collections.Queue.Synchronized(new System.Collections.Queue(qCommands)); }
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; }
// // - Constructors - // /// <summary> /// Constructor. /// </summary> public DicomThreadTriggerLoop() { triggerQueue = System.Collections.Queue.Synchronized(new System.Collections.Queue()); }