working on it ...

Filters

Explore Public Snippets

Sort by

Found 8,413 snippets matching: task

    public by sTiLL-iLL @ SniPitz-KND  550003  5  8  16

    Async Queue in C#

    using System;
    using System.Net;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    
    public class ParalyzKue
    {
    	readonly object _locker = new object();
    	Task _tail = Task.FromResult (true);
    	
    	public Task Enqueue (Action action)
    	{
    		lock (_locker)
    			return _tail = _tail.ContinueWith (ant => action());
    	}
    
    	public Task<TResult> Enqueue<TResult> (Func<TResult> func)
    	{
    		lock (_locker)
    			return (Task<TResult>) (_tail = _tail.ContinueWith (ant => func()));
    	}
    
    	public Task Enqueue (Func<Task> action)
    	{
    		lock (_locker)
    			return _tail = _tail.Catch().Then (action);
    	}	
    
    	public Task<TResult> Enqueue<TResult> (Func<Task<TResult>> func)
    	{
    		lock (_locker)
    			return (Task<TResult>) (_tail = _tail.Catch().Then (func));
    	}
    }
    
    
    public static class Extensions
    {
    	public static Task<T> Catch<T,TError> (this Task<T> task, Func<TError,T> onError) where TError : Exception
    	{
    		var tcs = new TaskCompletionSource<T> ();
    		task.ContinueWith (ant => {
    			if (task.IsFaulted && task.Exception.InnerException is TError)
    			{
    				tcs.SetResult (onError ((TError) task.Exception.InnerException));
    			}
    			else if (ant.IsCanceled)
    			{
    				tcs.SetCanceled ();
    			}
    			else if (task.IsFaulted)
    			{
    				tcs.SetException (ant.Exception.InnerException);
    			}
    			else
    			{
    				tcs.SetResult (ant.Result);
    			}
    		});
    		return tcs.Task;
    	}		
    	public static Task<T> Catch<T,TError> (this Task<T> task, T onError) where TError : Exception
    	{
    		return task.Catch<T,TError> (ex => onError);
    	}
    	
    	public static Task<T> Catch<T,TError> (this Task task, T onError) where TError : Exception
    	{
    		return task.ToTaskOfT<T>().Catch<T,TError> (onError);
    	}
    
    	public static Task Catch (this Task task)
    	{
    		return task.Catch<object,Exception> (null);
    	}
    	
    	public static Task<T> Catch<T> (this Task<T> task, T valueIfError = default(T))
    	{
    		return task.Catch<T,Exception> (valueIfError);
    	}
    
    	public async static Task<T> ToTaskOfT<T> (this Task t)
    	{
    		await t;
    		return default(T);
    	}
    	
    	public static async Task Then(this Task task, Func<Task> continuation)
    	{
    		await task;
    		await continuation();
    	}
    	
    	public static async Task<TNewResult> Then<TNewResult>(this Task task, Func<Task<TNewResult>> continuation)
    	{
    		await task;
    		return await continuation();
    	}
    	
    	public static async Task Then<TResult>(this Task<TResult> task, Func<TResult,Task> continuation)
    	{
    		await continuation(await task);
    	}
    	
    	public static async Task<TNewResult> Then<TResult, TNewResult>(this Task<TResult> task, Func<TResult, Task<TNewResult>> continuation)
    	{
    		return await continuation(await task);
    	}
    }
    
    /*
    public void doKue()
    {
    	var pcQ = new ParaKue();
    	
      pcQ.Enqueue (() => AsyncMethod1 ("http://www.rotten.com/")).Dump ("Task 1");
    	pcQ.Enqueue (() => AsyncMethod1 ("https://youtube.com/")).Dump ("Task 2");
    	pcQ.Enqueue (() => AsyncMethod1 ("https://yahoo.com/search?q=the cube")).Dump ("Task 3");
      pcQ.Enqueue (() => AsyncMethod1 ("http://www.rotten.com/")).Dump ("Task 4");
    	pcQ.Enqueue (() => AsyncMethod1 ("https://youtube.com/")).Dump ("Task 5");
    	pcQ.Enqueue (() => AsyncMethod1 ("https://www.google.com/search?q=web scrapers")).Dump ("Task 6");
      pcQ.Enqueue (() => AsyncMethod1 ("http://www.rotten.com/")).Dump ("Task 7");
    	pcQ.Enqueue (() => AsyncMethod1 ("https://youtube.com/")).Dump ("Task 8");
    	pcQ.Enqueue (() => AsyncMethod1 ("https://youtube.com/search?q=aliens gods")).Dump ("Task 9");
      pcQ.Enqueue (() => AsyncMethod ("http://www.rotten.com/")).Dump ("Task 10");
    	pcQ.Enqueue (() => AsyncMethod ("https://youtube.com/")).Dump ("Task 11");
    	pcQ.Enqueue (() => AsyncMethod ("https://www.google.com/search?q=javascript")).Dump ("Task 12");
      pcQ.Enqueue (() => AsyncMethod ("http://www.rotten.com/")).Dump ("Task 13");
    	pcQ.Enqueue (() => AsyncMethod ("https://youtube.com/search?q=aliens")).Dump ("Task 14");
      pcQ.Enqueue (() => AsyncMethod ("https://www.yahoo.com/")).Dump ("Task 15");
    	pcQ.Enqueue (() => AsyncMethod ("https://youtube.com/")).Dump ("Task 16");
    	pcQ.Enqueue (() => AsyncMethod ("https://www.google.com/search?q=aliens disclosure")).Dump ("Task 17");
    }
    
    string SyncMethod (string uri)
    {
        var x = new System.Net.WebClient();
        var y = x.DownloadString(uri);
        return y;
    }
    
    async Task<string> AsyncMethod (string uri)
    {
       return await Task.Run(() => new System.Net.WebClient().DownloadStringTaskAsync(uri).Dump());
    }
    
    
    async Task<string> AsyncMethod1 (string uri)
    {
       var x = await new System.Net.WebClient().DownloadStringTaskAsync(uri);
       return x;
    }
    
    */

    public by JeffMorrison  316486  1  4  0

    com.javarush.test.level03.lesson08.task02;

    package com.javarush.test.level03.lesson08.task02;
    
    /* Зарплата через 5 лет
    Ввести с клавиатуры отдельно Имя, число1, число2. Вывести надпись:
    «Имя» получает «число1» через «число2» лет.
    Пример: Коля получает 3000 через 5 лет.
    */
    
    import java.io.*;
    
    public class Solution
    {
        public static void main(String[] args) throws Exception
        {
         BufferedReader r = new BufferedReader(new InputStreamReader(System.in ));
    String a = r.readLine();
    String s = r.readLine();;
    String d = r.readLine();
    int n = Integer.parseInt(s);
    int t = Integer.parseInt(d);
    System.out.println(a+" получает "+s+" через "+d+" лет.");   //Напишите тут ваш код
        }
    }

    public by UdeF  125277  0  5  0

    Entfernt das TrayIcon beim Beenden

    entfernt das TrayIcon vor dem beenden aus der Taskleiste.
    OnAutoItExitRegister("__TrayIconHide")
    Func __TrayIconHide()
        TraySetState(2)
    EndFunc
    
    ; MsgBox(0, "hallo", "h")          

    public by sTiLL-iLL  2808  1  8  12

    C# Task extensions for yer pleasure

    helpful for c# TAP stuff.... ENJOI!
    // Task extensions
    
    public static class Extensions
    {
    
    	public static Task<T> Catch<T,TError> (this Task<T> task, Func<TError,T> onError) where TError : Exception
    	{
    		var tcs = new TaskCompletionSource<T> ();
    		task.ContinueWith (ant => {
    			if (task.IsFaulted && task.Exception.InnerException is TError)
                {
    				tcs.SetResult (onError ((TError) task.Exception.InnerException));
                }
    			else if (ant.IsCanceled)
                {
    				tcs.SetCanceled ();
                }
    			else if (task.IsFaulted)
                {
    				tcs.SetException (ant.Exception.InnerException);
                }
    			else
                {
    				tcs.SetResult (ant.Result);
                }
    		});
    		return tcs.Task;
    	}	
    /*	
    	public static Task<T> Catch<T,TError> (this Task<T> task, T onError) where TError : Exception
    	{
    		return task.Catch<T,TError> (ex => onError);
    	}
    	
    	public static Task<T> Catch<T,TError> (this Task task, T onError) where TError : Exception
    	{
    		return task.ToTaskOfT<T>().Catch<T,TError> (onError);
    	}
    
    	public static Task Catch (this Task task)
    	{
    		return task.Catch<object,Exception> (null);
    	}
    	
    	public static Task<T> Catch<T> (this Task<T> task, T valueIfError = default(T))
    	{
    		return task.Catch<T,Exception> (valueIfError);
    	}
    */
    	public async static Task<T> ToTaskOfT<T> (this Task t)
    	{
    		await t;
    		return default(T);
    	}
    	
    	public static async Task Then(this Task task, Func<Task> continuation)
    	{
    		await task;
    		await continuation();
    	}
    	
    	public static async Task<TNewResult> Then<TNewResult>(this Task task, Func<Task<TNewResult>> continuation)
    	{
    		await task;
    		return await continuation();
    	}
    	
    	public static async Task Then<TResult>(this Task<TResult> task, Func<TResult,Task> continuation)
    	{
    		await continuation(await task);
    	}
    	
    	public static async Task<TNewResult> Then<TResult, TNewResult>(this Task<TResult> task, Func<TResult, Task<TNewResult>> continuation)
    	{
    		return await continuation(await task);
    	}
    }            

    public by sTiLL-iLL @ SniPitz-KND  3710  3  7  10

    kKlient.cs

    an experiment in async task-based http methods C#!!!!
    using System;
    using System.Net;
    using System.Web;
    using System.Net.Cache;
    using System.Threading;
    using System.Threading.Tasks;
    
    public class kKlient
    {
        public string Base
        {
            get;
            set;
        }
        public RequestCachePolicy CachPol
        {
            get;
            set;
        }
        public bool UseDef
        {
            get;
            set;
        }
        public ICredentials Credz
        {
            get;
            set;
        }
        public WebHeaderCollection Headz
        {
            get;
            set;
        }
        public IWebProxy Prxy
        {
            get;
            set;
        }
    
        public kKlient (object[] argz)
        {
            new HTTPAction(argz);
        }
    
        public async Task<string> FetchString (string uri, CancellationToken cToken = default (CancellationToken),
            IProgress<DownloadProgressChangedEventArgs> progress = null)
        {
            return await Task.Run(( ) => GetClient(cToken, progress).DownloadStringTaskAsync(uri));
        }
    
        public async Task<byte[]> FetchData (string uri, CancellationToken cToken = default (CancellationToken),
            IProgress<DownloadProgressChangedEventArgs> progress = null)
        {
            return await Task.Run(( ) => GetClient(cToken, progress).DownloadDataTaskAsync(uri));
        }
    
        public async Task FetchFile (string uri, string fileName, CancellationToken cToken = default (CancellationToken),
            IProgress<DownloadProgressChangedEventArgs> progress = null)
        {
            await Task.Run(( ) => GetClient(cToken, progress).DownloadFileTaskAsync(uri, fileName));
        }
    
    
        internal class HTTPAction
             : WebClient
        {
            public HTTPAction ( )
                : base()
            {
            }
    
            public HTTPAction (string url)
                : base()
            {
            }
        }
    
        private HTTPAction GetClient (CancellationToken cancelToken, IProgress<DownloadProgressChangedEventArgs> progress)
        {
            HTTPAction hta = new HTTPAction()
            {
                BaseAddress = Base,
                CachePolicy = CachPol,
                UseDefaultCredentials = UseDef,
                Credentials = Credz,
                Headers = Headz,
                Proxy = Prxy,
            };
    
            if (cancelToken != CancellationToken.None) cancelToken.Register(( ) => hta.CancelAsync());
            if (progress != null)
            {
                hta.DownloadProgressChanged += (sender, args) => progress.Report(args);
            }
    
            return hta;
        }
    }           

    public by cghersi  3409  1  6  0

    How to create an asynchronous task in C#

    This is a simple way to create a task that will run asynchronously with respect to the current thread
    System.Threading.Tasks.Task.Factory.StartNew(() =>
    {
      log.Info("This will run async");
    });
    

    public by cghersi  2792  2  7  1

    Manage a queue in Java

    This simple class has a queue that is filled and depleted with its two methods. The getter blocks until a new item is ready on the queue. It can be used also as a synchronization mechanism between two threads
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Observable;
    import java.util.Observer;
    import java.util.concurrent.ArrayBlockingQueue;
    import java.util.concurrent.ConcurrentHashMap;
    
    public class ClassWithQueue {
    
    	private ArrayBlockingQueue<String> incomingTextMessages;
    	
    	public StubIPCJ(){
    		incomingTextMessages = new ArrayBlockingQueue<String>(1000);
    	}
    	
    	public String getTextMessage(){
    		String msg = null;
    		try {			
    			msg = incomingTextMessages.take();
    		} catch (InterruptedException e) {
    			log.error("ipcGetFrame failure: " + e.getMessage());
    			return null;
    		}
    			
    		return msg; 		
    	}
    
    	public void addToQueue(String obj) {		
    		synchronized(incomingTextMessages){
    			try {
    				incomingTextMessages.add(obj);
    			}catch(IllegalStateException ew){
    				incomingTextMessages.poll();
    				incomingTextMessages.add(obj);
    			}
    		}								
    	}
    }
    

    public by Alessio Felicioni  9027  1  4  1

    scheduled task command, windows host (warning: not just a CTRL+C & CTRL+V crontab replacement). Scheduled for every Monday at 20:15

    scheduled task command, windows host (warning: not just a CTRL+C & CTRL+V crontab replacement). Scheduled for every Monday at 20:15: windows-scheduled-task.cmd
    schtasks /create /tn "Namespace\Scheduled Task" /tr "php -f C:\xampp\htdocs\index.php" /sc weekly /d MON /st 20:15
    
    

    public by sTiLL-iLL  2608  1  8  13

    Managed Interval! Timer Alchemy with concurrent kueue executes tasks on the b bb b bbeat

    check files, ping a server, download a receipt... if you can list it this can execute it, neat and tidy. its like a gold watch of timer structs (use my non-bloking kueue with this)
    using System;
    using System.IO;
    using System.Linq;
    using System.Threading;
    using System.Threading.Tasks;
    
    
    void Main()
    {
    	var dct = new DownCount(5);
    	new Thread (() =>
    	{
    		for (int i = 0; i < 5; i++)
    		{
    			Thread.Sleep(1000);
    			dct.Signal();
    			Console.WriteLine ("Signal " + i);
    		}
    	}).Start();
    	
    	Console.WriteLine ("Wait for it...");
    	dc.Wait();
    	Console.WriteLine ("ahhhhhh......");
    }
    
    public class DownCount
    {
      int val;
    	object loka = new object ();
    	public DownCount() { }
    	
    	public DownCount (int cnt1)
    	{
    	  val = cnt1;
    	}
    	
    	public void Signal()
    	{
    	  DCnt1 (-1);
    	}
    	
    	public void DCnt1 (int totl)
    	{
    		lock (loka) 
    		{ 
    			val += totl;
    			if (val <= 0)
    			{
    			  Monitor.PulseAll (loka);
    			}
    		}
    	}
    	
    	public void Wait()
    	{
    		lock (loka)
    		{
    			while (val > 0)
    			{
    				Monitor.Wait (loka);
    			}
    		}
    	}
    }
    
    //////////////////////////////////////////////////////////
    
    public class betterInterval
    {
      static void Tik(long t)
      {
        this.onTik.Invoke(t);
      }
      
      static IObservable<long> Interval(TimeSpan period)
      {
          return Observable.Create<long> (observer => {
    	    long i = 0;
    	    object sync = new object();
    	        return new Timer (_ => {
                      lock (sync) observer.OnNext (i++);
              }, Tik(i), period, period);
        });
      }
      
      static IObservable<long> kreate(TimeSpan period)
      {
        return Interval (TimeSpan.FromSeconds(period)).Subscribe(onTik);
      }
      
      static async void onTik(t)
      {
        Console.WriteLine(t);
      }
    }
    
    void Main()
    {
        IObservable<long> bi = betterInterval.kreate(TimeSpan.FromSeconds(5));
        bi.Subscribe(Console.WriteLine(t);
    }
    
    
    ///////////////////////////////////////////////////////////////////////
    
    public class KInterval
    {
        public delegate void Signal (object signal);
        public event Signal Received;
    
        static long tcnt = 0;
        long dly = 0;
        long prd = 0;
        KQue kq = new KQue(5);
        Timer tmr;
    
        public KInterval (long delay = 5000, long period = 3000, int workersCount = 3)
        {
            dly = delay;
            prd = period;
            if (workersCount > 0)
            {
                kq = new KQue(workersCount);
            }
        }
    
        public void Begin ( )
        {
            kq.NQItem(( ) => tmr = new Timer(Signaled, tcnt, dly, prd));
        }
    
        public void Kill ( )
        {
            tmr.Dispose();
            kq.ShutdownKQ(true);
        }
    
        private void Signaled (object signal)
        {
            var sig = (long) signal;
            var st = sig;
            this.Received += KInterval_Received;
            this.Received.Invoke(sig);
            this.Received -= KInterval_Received;
        }
    
        void KInterval_Received (object signal)
        {      }
    }                        

    public by aniello  3686  3  4  0

    Query WorkFlow Tasks

    Query WorkFlow Tasks: querytask.java
    public List<Task> queryTasks(IWorkflowContext context,
                                 int noOfRecords,
                                 String orderBy,
                                 String searchString) throws WorkflowException {
    
    
        List<String> queryColumns = new ArrayList<String>();
    
        queryColumns.add(TableConstants.WFTASK_TITLE_COLUMN.getName());
        queryColumns.add(TableConstants.WFTASK_PRIORITY_COLUMN.getName());
        queryColumns.add(TableConstants.WFTASK_STATE_COLUMN.getName());
        queryColumns.add(TableConstants.WFTASK_SUBSTATE_COLUMN.getName());
        queryColumns.add(TableConstants.WFTASK_ACQUIREDBY_COLUMN.getName());
        queryColumns.add(TableConstants.WFTASK_TASKID_COLUMN.getName());
        queryColumns.add(TableConstants.WFTASK_TASKNUMBER_COLUMN.getName());
        queryColumns.add(TableConstants.WFTASK_PROCESSNAME_COLUMN.getName());
        queryColumns.add(TableConstants.WFTASK_PROCESSID_COLUMN.getName());
        queryColumns.add(TableConstants.WFTASK_INSTANCEID_COLUMN.getName());
        queryColumns.add(TableConstants.WFTASK_PROCESSVERSION_COLUMN.getName());
        queryColumns.add(TableConstants.WFTASK_IDENTIFICATIONKEY_COLUMN.getName());
        queryColumns.add(TableConstants.WFTASK_ASSIGNEEGROUPS_COLUMN.getName());
        queryColumns.add(TableConstants.WFTASK_ASSIGNEEUSERS_COLUMN.getName());
        queryColumns.add(TableConstants.WFTASK_EXPIRATIONDATE_COLUMN.getName());
    
        // specific "text string" columns
        queryColumns.add(TableConstants.WFTASK_TEXTATTRIBUTE1_COLUMN.getName());
        queryColumns.add(TableConstants.WFTASK_TEXTATTRIBUTE2_COLUMN.getName());
        queryColumns.add(TableConstants.WFTASK_TEXTATTRIBUTE3_COLUMN.getName());
        queryColumns.add(TableConstants.WFTASK_TEXTATTRIBUTE4_COLUMN.getName());
        queryColumns.add(TableConstants.WFTASK_URLATTRIBUTE1_COLUMN.getName());
        queryColumns.add(TableConstants.WFTASK_URLATTRIBUTE2_COLUMN.getName());
    
    
        // Correct state
        List<String> correctStates = new ArrayList<String>();
    
        correctStates.add(IWorkflowConstants.TASK_STATE_ALERTED);
        correctStates.add(IWorkflowConstants.TASK_STATE_ASSIGNED);
        correctStates.add(IWorkflowConstants.TASK_STATE_INFO_REQUESTED);
        correctStates.add(IWorkflowConstants.TASK_STATE_OUTCOME_UPDATED);
    
            
    
        // only these states 
        Predicate predicateBasic =
           new Predicate(TableConstants.WFTASK_STATE_COLUMN, 
                         Predicate.OP_IN,
                         correctStates);
        // not stale tasks
        predicateBasic.addClause(Predicate.AND,
                            TableConstants.WFTASK_STATE_COLUMN,
                            Predicate.OP_NEQ,
                            IWorkflowConstants.TASK_STATE_STALE);
           
        Predicate predicateSearch = null;
        if ( searchString != null && !"".equals(searchString) ) {
                
                
           predicateSearch = new Predicate(TableConstants.WFTASK_TEXTATTRIBUTE1_COLUMN,
                                           Predicate.OP_CONTAINS,
                                           searchString);
           predicateSearch.addClause(Predicate.OR,
                               TableConstants.WFTASK_TEXTATTRIBUTE2_COLUMN,
                               Predicate.OP_CONTAINS,
                               searchString);
           predicateSearch.addClause(Predicate.OR,
                               TableConstants.WFTASK_TEXTATTRIBUTE3_COLUMN,
                               Predicate.OP_CONTAINS,
                               searchString);
           if ( isParsableToInt(searchString) ){  
              predicateSearch.addClause(Predicate.OR,
                                        TableConstants.WFTASK_TASKNUMBER_COLUMN,
                                        Predicate.OP_EQ,
                                        searchString);
           }
         }
            
        Predicate predicate = null;
        if ( predicateSearch == null ) {
          predicate = predicateBasic; 
        } else {
          predicate = new Predicate (predicateBasic,Predicate.AND,predicateSearch);
        }
              
            
        // Ordering
        Ordering taskOrdering = null;
        logger.info("set the default Priority / EscalationDate Ordering");
        if ( "PRIO".equalsIgnoreCase(orderBy) ) {
           taskOrdering = new Ordering(TableConstants.WFTASK_PRIORITY_COLUMN, true,false); 
           taskOrdering.addClause(TableConstants.WFTASK_TASKNUMBER_COLUMN, true,false);
        } else if  ("ID".equalsIgnoreCase(orderBy) ) { 
           taskOrdering = new Ordering(TableConstants.WFTASK_TASKNUMBER_COLUMN, false,true);
        } else if ("ESC_DESC".equalsIgnoreCase(orderBy)  ) {
            taskOrdering = new Ordering(TableConstants.WFTASK_EXPIRATIONDATE_COLUMN, false, false);
        }  else if ("ESC_ASC".equalsIgnoreCase(orderBy) ) {
            taskOrdering = new Ordering(TableConstants.WFTASK_EXPIRATIONDATE_COLUMN, true, false);
        } else if ("CRE_DESC".equalsIgnoreCase(orderBy)  ) {
              taskOrdering = new Ordering(TableConstants.WFTASK_CREATEDDATE_COLUMN, false, false);
        }  else if ("CRE_ASC".equalsIgnoreCase(orderBy) ) {
              taskOrdering = new Ordering(TableConstants.WFTASK_CREATEDDATE_COLUMN, true, false);
        } 
    
        List<ITaskQueryService.OptionalInfo> optionalInfo = new ArrayList<ITaskQueryService.OptionalInfo>();
        optionalInfo.add(ITaskQueryService.OptionalInfo.CUSTOM_ACTIONS);
        optionalInfo.add(ITaskQueryService.OptionalInfo.COMMENTS);
        optionalInfo.add(ITaskQueryService.OptionalInfo.PAYLOAD);
        optionalInfo.add(ITaskQueryService.OptionalInfo.DISPLAY_INFO);
    
        List<Task> tasks =
            getTaskQueryService().queryTasks(context, 
                                             queryColumns,
                                             optionalInfo,
                                             ITaskQueryService.AssignmentFilter.MY_AND_GROUP,
                                             null, 
                                             predicate, 
                                             taskOrdering,
                                             0,
                                             noOfRecords);
    
        logger.debug("[EINDE] queryTasks()");
    
        getTaskQueryService().destroyWorkflowContext(context);
    
        return tasks;
    }
    
    
    
    
    • Public Snippets
    • Channels Snippets