Esempio n. 1
0
        private double CalcFunct1(TaskParameters taskP)
        {
            double f   = 0;
            var    val = new List <double>();
            var    v   = new List <Vector>();
            double h   = res.GetH();
            var    rk  = new Vector[res.Count - 1];

            rk[0]   = new Vector(1, startP[0]);
            itab[0] = 1;
            double t = res[0].X;

            for (int i = 1; i < res.Count - 1; i++)
            {
                val.Clear();
                v.Clear();
                for (int j = 0; j < tw.SetCount; j++)
                {
                    double x1 = rk[i - 1][0] + tw.FunctionSet(t, rk[i - 1], j, taskP) * h;
                    v.Add(new Vector(1, x1));
                    val.Add(Math.Abs(x1 - res[i].Y[0]));
                }
                double min   = val.Min();
                int    index = val.IndexOf(min);
                rk[i]   = v[index];
                itab[i] = index + 1;
                f      += min * min * h;
                t       = t + h;
            }

            return(f);
        }
Esempio n. 2
0
 /// <summary>
 /// This method is only for paramteter customizing (merge with Schedule(string name, ?)
 /// TaskName should be preinitialized and point to existing named tp in container.
 /// </summary>
 /// <param name="tp"></param>
 /// <param name="parallelism"></param>
 /// <param name="dueInSeconds"></param>
 protected void Schedule(TaskParameters tp,
                         ScheduleTaskParallelism parallelism = ScheduleTaskParallelism.AllowOthers,
                         int dueInSeconds = 0)
 {
     lock (runningTasks)
     {
         if (!IsStarted)
         {
             throw new InvalidOperationException("Task scheduler is not running");
         }
         log.Info("Scheduling " + tp);
         var entity = new ScheduleEntity()
         {
             NextExecution = DateTime.MaxValue,
             Parallelism   = parallelism,
             TaskName      = tp.TaskName,
         };
         lock (repoLocker)
         {
             repo.Save(entity);
             repo.LoadSettingsIfNull(entity);
             foreach (KeyValuePair <string, object> setting in tp.Settings)
             {
                 entity.Settings.AddEntry(setting.Key, setting.Value);
             }
             entity.NextExecution = DateTime.Now.AddSeconds(Math.Max(0, dueInSeconds));
             repo.Update(entity);
         }
     }
 }
        private LeveledTask addTask(ref ConcurrentDictionary <string, ConcurrentDictionary <string, long> > allresult,
                                    TaskParameters taskP,
                                    string q,
                                    int maxSleep,
                                    bool IsHighPrority = false)
        {
            var result = allresult;

            LeveledTask lt = new LeveledTask((param) =>
            {
                var p = param as TaskParameters;

                var resultQ = result.GetOrAdd(p.Q, new ConcurrentDictionary <string, long>());
                resultQ.AddOrUpdate(string.Concat("S", p.Seq), DateTime.UtcNow.Ticks, (key, current) => { throw new InvalidOperationException("Found existing key"); });
                //Trace.WriteLine(string.Format("Task {0} on Queue {1} - Start", p.Seq, p.Q), "info");
                Thread.Sleep(maxSleep);
                //Trace.WriteLine(string.Format("Task {0} on Queue {1} - End", p.Seq, p.Q), "info");
                resultQ.AddOrUpdate(string.Concat("E", p.Seq), DateTime.UtcNow.Ticks, (key, current) => { throw new InvalidOperationException("Found existing key"); });
            },
                                             taskP);


            lt.QueueId        = q;
            lt.IsHighPriority = IsHighPrority;
            lt.Start(scheduler);

            return(lt);
        }
Esempio n. 4
0
        public void RunCode(string[] firstPlayerCode, string[] secondPlayerCode, string pathToField, GameFinishType finishType, IEnumerable <BLL.Models.Bot> bots1, IEnumerable <BLL.Models.Bot> bots2, int finalX = 0, int finalY = 0)
        {
            CompilationResult compResult1 = compiler.CompileCode(TaskParameters.Build(firstPlayerCode.Length), firstPlayerCode);
            CompilationResult compResult2 = compiler.CompileCode(TaskParameters.Build(secondPlayerCode.Length), secondPlayerCode);

            if (!compResult1.IsCodeCorrect || !compResult2.IsCodeCorrect)
            {
                throw new ArgumentException("Unable to compile code");
            }

            FieldBuilder fieldBuilder = new FieldBuilder(pathToField);

            Runner.CodeRunners.Models.Field field = fieldBuilder.GetFieldForRunner();
            field = fieldBuilder.PlaceBots(field, bots1.Select(b => new Models.Bot(b.X, b.Y, b.Name)), 1);
            field = fieldBuilder.PlaceBots(field, bots2.Select(b => new Models.Bot(b.X, b.Y, b.Name)), 2);

            FinishGameCondition finishCondition = null;

            if (finishType == GameFinishType.CommandsNumber)
            {
                finishCondition = new CommandNumberCondition();
            }
            else
            {
                finishCondition = new BotOnPointCondition(finalX, finalY);
            }

            IEnumerable <Runner.CodeRunners.Models.Bot> runnerBots1 = bots1.Select(mapper.Map <Runner.CodeRunners.Models.Bot>);
            IEnumerable <Runner.CodeRunners.Models.Bot> runnerBots2 = bots2.Select(mapper.Map <Runner.CodeRunners.Models.Bot>);

            runner.RunCodeGame(compResult1.InformationForCodeRunner, compResult2.InformationForCodeRunner, field, runnerBots1, runnerBots2, finishCondition);

            runner.GameFinished += Runner_GameFinished;
        }
Esempio n. 5
0
        protected async override Task OnConsume(string example, TaskParameters taskParameters, ClientActiveTasks cleanup)
        {
            registerTask(cleanup, "ExampleTask"); // may throw AlreadyInProgress exception
            _logger.LogInformation("Example Task Starting");
            int captionCount       = 0;
            int transcriptionCount = 0;

            using (var _context = CTDbContext.CreateDbContext())
            {
                CaptionQueries captionQueries = new CaptionQueries(_context);

                var transcriptions = await _context.Transcriptions.Take(30).ToListAsync();

                foreach (var transcription in transcriptions)
                {
                    var transcriptionId = transcription.Id;
                    var videoID         = transcription.VideoId;
                    var captions        = await captionQueries.GetCaptionsAsync(transcriptionId);

                    _logger.LogInformation($"{transcription.Id}: Caption count= {captions.Count}");
                    transcriptionCount++;
                }
            }

            _logger.LogInformation($"Example Task Done.  transcriptionCount={transcriptionCount} captionCount={captionCount}");
        }
Esempio n. 6
0
#pragma warning disable 1998
        protected async override Task OnConsume(string emptyString, TaskParameters taskParameters, ClientActiveTasks cleanup)
        {
            // Maybe in the future if we use this task again: registerTask(cleanup, "RefreshAccessTokenAsync"); // may throw AlreadyInProgress exception
            // no. xx nope await _box.RefreshAccessTokenAsync();
            // refreshing the Box access token caused the token to go stale
            // We've had a better experience not refreshing it
        }
Esempio n. 7
0
    protected void lnkBreakWithCopy_Click(Object sender, EventArgs e)
    {
        // Check permission
        CheckModifyPermission(true);

        // Break permission inheritance and copy parent permissions
        AclInfoProvider.BreakInheritance(Node, true);

        // Log staging task
        TaskParameters taskParam = new TaskParameters();

        taskParam.SetParameter("copyPermissions", true);
        DocumentSynchronizationHelper.LogDocumentChange(Node, TaskTypeEnum.BreakACLInheritance, Node.TreeProvider, SynchronizationInfoProvider.ENABLED_SERVERS, taskParam, Node.TreeProvider.AllowAsyncActions);

        // Insert information about this event to event log.
        if (DocumentManager.Tree.LogEvents)
        {
            EventLogProvider.LogEvent(EventType.INFORMATION, "Content", "DOCPERMISSIONSMODIFIED", ResHelper.GetAPIString("security.documentpermissionsbreakcopy", "Inheritance of the parent page permissions have been broken. Parent page permissions have been copied."), eventUrl, DocumentManager.Tree.UserInfo.UserID, DocumentManager.Tree.UserInfo.UserName, Node.NodeID, DocumentName, ipAddress, Node.NodeSiteID);
        }

        lblInheritanceInfo.Text = GetString("Security.InheritsInfo.DoesNotInherit");
        SwitchBackToPermissionsMode();

        // Clear and reload
        securityElem.InvalidateAcls();
        securityElem.LoadOperators(true);
    }
Esempio n. 8
0
        /// <summary>Extracts scene information for a video.
        /// Beware: It is possible to start another scene task while the first one is still running</summary>
        protected async override Task OnConsume(string videoId, TaskParameters taskParameters, ClientActiveTasks cleanup)
        {
            registerTask(cleanup, videoId); // may throw AlreadyInProgress exception
            using (var _context = CTDbContext.CreateDbContext())
            {
                Video video = await _context.Videos.FindAsync(videoId);

                if (video.SceneData == null || taskParameters.Force)
                {
                    var jsonString = await _rpcClient.PythonServerClient.GetScenesRPCAsync(new CTGrpc.File
                    {
                        FilePath = video.Video1.VMPath
                    });

                    JArray scenes = JArray.Parse(jsonString.Json);

                    video.SceneData = new JObject
                    {
                        { "Scenes", scenes }
                    };

                    await _context.SaveChangesAsync();
                }
            }
        }
Esempio n. 9
0
        protected async override Task OnConsume(string example, TaskParameters taskParameters, ClientActiveTasks cleanup)
        {
            registerTask(cleanup, "BuildElasticIndexTask"); // may throw AlreadyInProgress exception
            GetLogger().LogInformation("BuildElasticIndexTask Starting");

            using (var _context = CTDbContext.CreateDbContext())
            {
                CaptionQueries captionQueries = new CaptionQueries(_context);

                var all_transcriptions = await _context.Transcriptions.Where(t => t.Language == Languages.ENGLISH_AMERICAN).ToListAsync();

                foreach (var transcription in all_transcriptions)
                {
                    var all_captions = transcription.Captions;

                    // each index has the unique name "index_string_unique", the current in use one has the alias "index_string_alias"
                    var index_string_base   = transcription.Id + "_" + Languages.ENGLISH_AMERICAN.ToLower(System.Globalization.CultureInfo.CurrentCulture);
                    var index_string_unique = index_string_base + "_" + $"{DateTime.Now:yyyyMMddHHmmss}";
                    var index_string_alias  = index_string_base + "_" + "primary";

                    var asyncBulkIndexResponse = await _client.BulkAsync(b => b
                                                                         .Index(index_string_unique)
                                                                         .IndexMany(all_captions)
                                                                         );

                    var alias_exist = await _client.Indices.ExistsAsync(index_string_alias);

                    if (alias_exist.Exists)
                    {
                        var oldIndices = await _client.GetIndicesPointingToAliasAsync(index_string_alias);

                        var oldIndexName = oldIndices.First().ToString();

                        var indexResponse = await _client.Indices.BulkAliasAsync(new BulkAliasRequest
                        {
                            Actions = new List <IAliasAction>
                            {
                                new AliasRemoveAction {
                                    Remove = new AliasRemoveOperation {
                                        Index = oldIndexName, Alias = index_string_alias
                                    }
                                },
                                new AliasAddAction {
                                    Add = new AliasAddOperation {
                                        Index = index_string_unique, Alias = index_string_alias
                                    }
                                }
                            }
                        });
                    }
                    else
                    {
                        var putAliasResponse = await _client.Indices.PutAliasAsync(new PutAliasRequest(index_string_unique, index_string_alias));
                    }
                }
            }

            GetLogger().LogInformation("BuildElasticIndexTask Done");
        }
Esempio n. 10
0
 public TaskWorker(TaskParameters p, Type t, string mf, string sf, object target)
 {
     TaskParams = p;
     MainFunctionName = mf;
     SecondFunctionName = sf;
     classType = t;
     this.target = target;
 }
Esempio n. 11
0
        public CompilationResultDTO CompileBotsCode(string[] code, int botsCount)
        {
            this.ConfigureMapper();

            CompilationResult res = compiler.CompileCode(TaskParameters.Build(botsCount), code);

            return(_mapper.Map <CompilationResultDTO>(res));
        }
Esempio n. 12
0
        public void CanParseEnumeration()
        {
            var p = new TaskParameters(new Dictionary <string, string> {
                { "lake", "constance" }
            });

            Assert.That(p.Parameter <Lakes>("lake"), Is.EqualTo(Lakes.Constance));
        }
Esempio n. 13
0
        public void CanParseDefaultStringParameter()
        {
            var p = new TaskParameters(new Dictionary <string, string> {
                { "file", "thefile.txt" }
            });

            Assert.That(p.Parameter("file", "afile.txt"), Is.EqualTo("thefile.txt"));
        }
Esempio n. 14
0
        public void CanParseStringParameterWithType()
        {
            var p = new TaskParameters(new Dictionary <string, string> {
                { "file", "thefile.txt" }
            });

            Assert.That(p.Parameter(typeof(string), "file", "afile.txt"), Is.EqualTo("thefile.txt"));
        }
        public void AsyncAsync()
        {
            var maxQueue      = 10;
            var maxTasks      = 5000;
            var maxSleep      = 10;
            var IsHighPrority = false;
            var result        = new ConcurrentDictionary <string, ConcurrentDictionary <string, long> >();
            var sw            = new Stopwatch();

            sw.Start();


            var Tasks = new List <Task>();


            for (var qNum = 1; qNum <= maxQueue; qNum++)
            {
                var qName = string.Concat("Q", qNum);
                for (var Seq = 1; Seq < maxTasks / maxQueue; Seq++)
                {
                    var taskP = new TaskParameters()
                    {
                        Q = qName, Seq = Seq
                    };

                    LeveledTask lt = new LeveledTask(async(param) =>
                    {
                        // this force the new task not to be inlined.

                        await Task.Factory.StartNew(async() => { await Task.Delay(100); }, TaskCreationOptions.LongRunning);
                        var p = param as TaskParameters;

                        var resultQ = result.GetOrAdd(p.Q, new ConcurrentDictionary <string, long>());
                        resultQ.AddOrUpdate(string.Concat("S", p.Seq), DateTime.UtcNow.Ticks, (key, current) => { throw new InvalidOperationException("Found existing key"); });
                        //Trace.WriteLine(string.Format("Task {0} on Queue {1} - Start", p.Seq, p.Q), "info");
                        Thread.Sleep(maxSleep);
                        //Trace.WriteLine(string.Format("Task {0} on Queue {1} - End", p.Seq, p.Q), "info");
                        resultQ.AddOrUpdate(string.Concat("E", p.Seq), DateTime.UtcNow.Ticks, (key, current) => { throw new InvalidOperationException("Found existing key"); });
                    },
                                                     taskP);

                    lt.QueueId        = qName;
                    lt.IsHighPriority = IsHighPrority;
                    lt.Start(scheduler);
                    Tasks.Add(lt);
                }
            }


            Task.WhenAll(Tasks).Wait();
            sw.Stop();
            Trace.WriteLine(string.Format("{0} Tasks on {1} Queues - Executed in {2} sec", maxTasks, maxQueue, sw.Elapsed.Seconds), "info");
            //verify(ref result);

            // tasks that uses normal start.run will lose order in the queue.
            // the only way that tasks maintain order is to by using
            // leveled tasks to create sub tasks.
        }
Esempio n. 16
0
 public void TestMagicHeaderMissing()
 {
     const string text = "Test test test, ho ho ho. ";
     const string compressedTxt = "compressed.txt";
     File.WriteAllText("in.txt", text);
     var parameters = new TaskParameters(ProcessorMode.Decompress, "in.txt", compressedTxt);
     var processor = new TaskProcessor(new LoggerMock());
     Assert.Throws<Exception>(() => processor.Start(parameters).Wait());
 }
Esempio n. 17
0
 public Vector AbstractFunction(double t, Vector y, TaskParameters tps)
 {
     object res = classType.InvokeMember(MainFunctionName, BindingFlags.Public
                                                           | BindingFlags.InvokeMethod
                                                           | BindingFlags.Instance | BindingFlags.Static, null,
                                         target,
                                         new object[] {t, y, tps});
     return res as Vector;
 }
Esempio n. 18
0
 public double FunctionSet(double t, Vector y, int index, TaskParameters tp)
 {
     object res = classType.InvokeMember(SecondFunctionName, BindingFlags.Public
                                                             | BindingFlags.InvokeMethod
                                                             | BindingFlags.Instance | BindingFlags.Static, null,
                                         target,
                                         new object[] {t, y, tp[index]});
     return (double) res;
 }
Esempio n. 19
0
        protected async override Task OnConsume(string transcriptionId, TaskParameters taskParameters, ClientActiveTasks cleanup)
        {
            registerTask(cleanup, transcriptionId); // may throw AlreadyInProgress exception

            GetLogger().LogInformation($"Creating VTT & SRT files for ({transcriptionId})");

            using (var _context = CTDbContext.CreateDbContext())
            {
                var transcription = await _context.Transcriptions.FindAsync(transcriptionId);

                CaptionQueries captionQueries = new CaptionQueries(_context);
                var            captions       = await captionQueries.GetCaptionsAsync(transcription.Id);

                var vttfile = await FileRecord.GetNewFileRecordAsync(Caption.GenerateWebVTTFile(captions, transcription.Language), ".vtt");

                FileRecord?existingVtt = await _context.FileRecords.FindAsync(transcription.FileId);

                if (existingVtt is null)
                {
                    GetLogger().LogInformation($"{transcriptionId}: Creating new vtt file {vttfile.FileName}");
                    await _context.FileRecords.AddAsync(vttfile);

                    transcription.File = vttfile;
                    _context.Entry(transcription).State = EntityState.Modified;
                }
                else
                {
                    GetLogger().LogInformation($"{transcriptionId}: replacing existing vtt file contents {existingVtt.FileName}");
                    existingVtt.ReplaceWith(vttfile);
                    _context.Entry(existingVtt).State = EntityState.Modified;
                }

                var srtfile = await FileRecord.GetNewFileRecordAsync(Caption.GenerateSrtFile(captions), ".srt");

                FileRecord?existingSrt = await _context.FileRecords.FindAsync(transcription.SrtFileId);

                if (existingSrt is null)
                {
                    GetLogger().LogInformation($"{transcriptionId}: Creating new srt file {srtfile.FileName}");

                    await _context.FileRecords.AddAsync(srtfile);

                    transcription.SrtFile = srtfile;
                    _context.Entry(transcription).State = EntityState.Modified;
                }
                else
                {
                    GetLogger().LogInformation($"{transcriptionId}: replacing existing srt file contents {existingSrt.FileName}");
                    existingSrt.ReplaceWith(srtfile);
                    _context.Entry(existingSrt).State = EntityState.Modified;
                }

                await _context.SaveChangesAsync();

                GetLogger().LogInformation($"{transcriptionId}: Database updated");
            }
        }
Esempio n. 20
0
        public void InvokesTaskByWholeName()
        {
            var task = new MockTask {FullName = "asdf"};
            var runner = new TaskRunner();
            var taskParameters = new TaskParameters(new Dictionary<string, string>());
            runner.RunTask("asdf", taskParameters, new [] {task});

            Assert.That(task.WasInvoked, Is.True);
            Assert.That(task.WasInvokedWithTaskParameters, Is.SameAs(taskParameters));
        }
Esempio n. 21
0
        public void RunTask(string taskName, TaskParameters taskParameters, IEnumerable<ITask> tasks) {
            var matchingTasks = tasks.Where(t => AllTaskNames(t).Contains(taskName.ToLower())).ToArray();

            if (matchingTasks.Count() > 1) {
                throw new AmbiguousTaskNameException(taskName, matchingTasks);
            } else if (!matchingTasks.Any()) {
                throw new NoMatchingTaskException(taskName, tasks);
            } else {
                matchingTasks.Single().Invoke(taskParameters);
            }
        }
        public void AsyncAsync()
        {
            var maxQueue = 10;
            var maxTasks = 5000;
            var maxSleep = 10;
            var IsHighPrority = false;
            var result = new ConcurrentDictionary<string, ConcurrentDictionary<string, long>>();
            var sw = new Stopwatch();
            sw.Start();

            var Tasks = new List<Task>();

            for (var qNum = 1; qNum <=  maxQueue; qNum++)
            {
                var qName = string.Concat("Q", qNum);
                for (var Seq = 1; Seq < maxTasks / maxQueue; Seq++)
                {
                    var taskP = new TaskParameters() { Q = qName, Seq = Seq };

                    LeveledTask lt = new LeveledTask(async (param) =>
                    {
                        // this force the new task not to be inlined.

                        await Task.Factory.StartNew(async () => { await Task.Delay(100); }, TaskCreationOptions.LongRunning );
                        var p = param as TaskParameters;

                        var resultQ = result.GetOrAdd(p.Q, new ConcurrentDictionary<string, long>());
                        resultQ.AddOrUpdate(string.Concat("S", p.Seq), DateTime.UtcNow.Ticks, (key, current) => { throw new InvalidOperationException("Found existing key"); });
                        //Trace.WriteLine(string.Format("Task {0} on Queue {1} - Start", p.Seq, p.Q), "info");
                        Thread.Sleep(maxSleep);
                        //Trace.WriteLine(string.Format("Task {0} on Queue {1} - End", p.Seq, p.Q), "info");
                        resultQ.AddOrUpdate(string.Concat("E", p.Seq), DateTime.UtcNow.Ticks, (key, current) => { throw new InvalidOperationException("Found existing key"); });

                    },
                    taskP);

                    lt.QueueId = qName;
                    lt.IsHighPriority = IsHighPrority;
                    lt.Start(scheduler);
                    Tasks.Add(lt);
                }
            }

            Task.WhenAll(Tasks).Wait();
            sw.Stop();
            Trace.WriteLine(string.Format("{0} Tasks on {1} Queues - Executed in {2} sec", maxTasks, maxQueue, sw.Elapsed.Seconds), "info");
            //verify(ref result);

            // tasks that uses normal start.run will lose order in the queue.
            // the only way that tasks maintain order is to by using
            // leveled tasks to create sub tasks.
        }
Esempio n. 23
0
        public void InvokesTaskByWholeName()
        {
            var task = new MockTask {
                FullName = "asdf"
            };
            var runner         = new TaskRunner();
            var taskParameters = new TaskParameters(new Dictionary <string, string>());

            runner.RunTask("asdf", taskParameters, new [] { task });

            Assert.That(task.WasInvoked, Is.True);
            Assert.That(task.WasInvokedWithTaskParameters, Is.SameAs(taskParameters));
        }
Esempio n. 24
0
        public void TestTaskAbortion()
        {
            var text = string.Concat(Enumerable.Repeat("Test test test, ho ho ho. ", 200500));
            const string compressedTxt = "compressed.txt";
            File.WriteAllText("in.txt", text);
            var parameters = new TaskParameters(ProcessorMode.Compress, "in.txt", compressedTxt);
            var processor = new TaskProcessor(new LoggerMock());
            var task = processor.Start(parameters);

            task.Abort();
            task.Wait();
            Assert.True(task.IsErrorOccured);
        }
Esempio n. 25
0
        private Vector RK4_1(double x, Vector y, double h, int j, TaskParameters taskP)
        {
            var    res = new Vector(2);
            Vector f0, f1, f2, f3;

            f0  = h * ff(x, y, j, taskP);
            f1  = h * ff(x + h / 2, y + f0 / 2, j, taskP);
            f2  = h * ff(x + h / 2, y + f1 / 2, j, taskP);
            f3  = h * ff(x + h, y + f2, j, taskP);
            res = y + (f0 + 2 * f1 + 2 * f2 + f3) / 6;

            return(res);
        }
Esempio n. 26
0
        public bool Schedule(string name,
                             ScheduleTaskParallelism parallelism = ScheduleTaskParallelism.AllowOthers)
        {
            TaskParameters tp = GetNamedTaskParameter(name);

            if (tp == null)
            {
                return(false);
            }
            tp.TaskName = name;
            Schedule(tp, parallelism);
            return(true);
        }
Esempio n. 27
0
        /// <summary>
        /// Create an instance of the specified TaskAdapter class from class name, DLL and path
        /// </summary>
        /// <param name="task">Configuration object for requested TaskAdapter</param>
        private TaskAdapter LoadAdapter(TaskParameters task)
        {
            // Ensure caller has provided name of class to load:
            if (string.IsNullOrEmpty(task.AdapterClassName))
            {
                throw new LoadAdapterException(10, "TaskAdapter class name not provided");
            }

            // Build path of adapter DLL, if specified (looking in current folder, if no path provided):
            string adapterDLLPath = string.IsNullOrEmpty(task.AdapterDLLName) ? null
                                : TaskUtilities.General.PathCombine(string.IsNullOrEmpty(task.AdapterDLLPath) ? AppDomain.CurrentDomain.BaseDirectory : task.AdapterDLLPath, task.AdapterDLLName);

            try
            {
                // Load Assembly from DLL name (if provided - otherwise look in "this" Assembly):
                var assembly = string.IsNullOrEmpty(adapterDLLPath) ? Assembly.GetExecutingAssembly() : Assembly.LoadFrom(adapterDLLPath);
                if (assembly == null)
                {
                    throw BuildLoadAdapterException(11, new ArgumentException("Invalid DLL path/name, or assembly not loaded"), task.AdapterClassName, adapterDLLPath);
                }

                // Retrieve collection of types from assembly with a base type of TaskAdapter:
                var assemblyTypes = assembly.GetTypes()?.Where(t => t.IsSubclassOf(typeof(TaskAdapter)));
                if (assemblyTypes?.Any() ?? throw BuildLoadAdapterException(12, new ArgumentException("Assembly contains no TaskAdapters"), task.AdapterClassName, adapterDLLPath))
                {
                    // Locate assembly with matching name (short or fully-qualified):
                    foreach (var type in assemblyTypes)
                    {
                        if (type.FullName.Equals(task.AdapterClassName, StringComparison.OrdinalIgnoreCase) ||
                            type.Name.Equals(task.AdapterClassName, StringComparison.OrdinalIgnoreCase))
                        {
                            // Create TaskAdapter instance (ActivatorUtilities will handle dependency injection, so long as TaskName
                            // (TaskAdapter constructor argument) is not null (which would confuse activator):
                            return((TaskAdapter)ActivatorUtilities.CreateInstance(isp, type, task.TaskName ?? string.Empty));
                        }
                    }
                }

                // If this point is reached, class was not found:
                throw BuildLoadAdapterException(13, new ArgumentException("Specified class not found in assembly"), task.AdapterClassName, adapterDLLPath);
            }
            catch (LoadAdapterException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw BuildLoadAdapterException(14, ex, task.AdapterClassName, adapterDLLPath);
            }
        }
Esempio n. 28
0
        private double CalcFunct2(TaskParameters taskP)
        {
            double f        = 0;
            var    val      = new List <double>();
            var    min1List = new List <double>();
            var    min2List = new List <double>();
            var    v        = new List <Vector>();
            double h        = res.GetH();
            var    rk       = new Vector[res.Count - 1];

            rk[0]   = new Vector(2, startP[0], startP[1]);
            itab[0] = 1;
            double t = res[0].X;

            for (int i = 1; i < res.Count - 2; i++)
            {
                val.Clear();
                min1List.Clear();
                v.Clear();
                for (int j = 0; j < tw.SetCount; j++)
                {
                    //double x2 = rk[i - 1][1] + this.tw.FunctionSet(t, rk[i - 1], j, taskP) * h;
                    //double x1 = rk[i - 1][0] + x2 * h;
                    //Vector vv = new Vector(2, x1, x2);

                    Vector vv = RK4_1(t, rk[i - 1], h, j, taskP);
                    v.Add(vv);
                    double min1 = Math.Abs(vv[0] - res[i].Y[0]);
                    double min2 = Math.Abs(vv[1] - dz[i]);
                    val.Add(min1 + min2);
                    min1List.Add(min1);
                    min2List.Add(min2);

                    //if (i < this.dz.Length)
                    //{
                    //    val2.Add(Math.Abs(vv[1] - this.dz[i]));
                    //}
                }
                double min   = val.Min();
                int    index = val.IndexOf(min);
                rk[i]   = v[index];
                itab[i] = index + 1;
                //f += min * min * h;
                f += Math.Pow(min1List[index], 2) + Math.Pow(min2List[index], 2) * h;
                t  = t + h;
            }

            return(f);
        }
Esempio n. 29
0
 public void Publish(T data, TaskParameters taskParameters = null)
 {
     try
     {
         if (taskParameters == null)
         {
             taskParameters = new TaskParameters();
         }
         _rabbitMQ.PublishTask(_queueName, data, taskParameters);
     }
     catch (Exception e)
     {
         _logger.LogError(e, "Error Publishing Task!");
     }
 }
Esempio n. 30
0
        public Vector MF2(double t, Vector v, TaskParameters p)
        {
            var res = new Vector(2);

            res[0] = v[1];
            if (p.Gamma is List <double> )
            {
                var pp = new List <double>();
                (p.Gamma as List <double>).ForEach(x => pp.Add(x));

                pp.Insert(0, double.MinValue);
                pp.Add(double.MaxValue);

                //double a = double.MinValue;
                double b = pp[0];

                for (int i = 0; i < pp.Count - 1; i++)
                {
                    if (v[0] > pp[i] && v[0] <= pp[i + 1])
                    {
                        res[1] = CallSecFunc(SecFuncName, t, v, p[i]);
                    }
                    else
                    {
                        continue;
                    }
                }
            }
            else if (p.Gamma is Dictionary <double, int> )
            {
                try
                {
                    var tt = p.Gamma as Dictionary <double, int>;
                    //int i = -1;
                    double index = tt.Keys.ToList().Find(x => Math.Abs(x - t) < 0.01);
                    res[1] = CallSecFunc(SecFuncName, t, v, p[tt[index]]);
                }
                catch
                {
                    res[1] = 1;
                }
            }
            else
            {
                throw new NotImplementedException("not impl yet");
            }
            return(res);
        }
Esempio n. 31
0
        protected async override Task OnConsume(string transcriptionId, TaskParameters taskParameters, ClientActiveTasks cleanup)
        {
            registerTask(cleanup, transcriptionId); // may throw AlreadyInProgress exception
            using (var _context = CTDbContext.CreateDbContext())
            {
                var transcription = await _context.Transcriptions.FindAsync(transcriptionId);

                FileRecord existingVtt = await _context.FileRecords.FindAsync(transcription.FileId);

                FileRecord existingSrt = await _context.FileRecords.FindAsync(transcription.SrtFileId);


                CaptionQueries captionQueries = new CaptionQueries(_context);
                var            captions       = await captionQueries.GetCaptionsAsync(transcription.Id);

                var vttfile = await FileRecord.GetNewFileRecordAsync(Caption.GenerateWebVTTFile(captions, transcription.Language), ".vtt");

                if (string.IsNullOrEmpty(transcription.FileId))
                {
                    await _context.FileRecords.AddAsync(vttfile);

                    transcription.File = vttfile;
                    _context.Entry(transcription).State = EntityState.Modified;
                }
                else
                {
                    existingVtt.ReplaceWith(vttfile);
                    _context.Entry(existingVtt).State = EntityState.Modified;
                }

                var srtfile = await FileRecord.GetNewFileRecordAsync(Caption.GenerateSrtFile(captions), ".srt");

                if (string.IsNullOrEmpty(transcription.SrtFileId))
                {
                    await _context.FileRecords.AddAsync(srtfile);

                    transcription.SrtFile = srtfile;
                    _context.Entry(transcription).State = EntityState.Modified;
                }
                else
                {
                    existingSrt.ReplaceWith(srtfile);
                    _context.Entry(existingSrt).State = EntityState.Modified;
                }

                await _context.SaveChangesAsync();
            }
        }
        /// <summary>
        /// Original implementation of OnConsume. This code may be deleted if it is no longer useful. It is left as available for now as a template
        /// </summary>
        /// <param name="videoId"></param>
        /// <param name="taskParameters"></param>
        /// <returns></returns>
        private async Task OldOnConsumeNotUsed(string videoId, TaskParameters taskParameters)
        {
            using (var _context = CTDbContext.CreateDbContext())
            {
                // Get the video object
                var video = await _context.Videos.FindAsync(videoId);

                _logger.LogInformation("Consuming" + video);
                // Make RPC call to produce audio file.
                var file = await _rpcClient.PythonServerClient.ConvertVideoToWavRPCWithOffsetAsync(new CTGrpc.FileForConversion
                {
                    File = new CTGrpc.File {
                        FilePath = video.Video1.VMPath
                    }
                });


                // Check if a valid file was returned.
                if (FileRecord.IsValidFile(file.FilePath))
                {
                    var fileRecord = await FileRecord.GetNewFileRecordAsync(file.FilePath, file.Ext);

                    // Get the latest video object, in case it has changed
                    var videoLatest = await _context.Videos.FindAsync(video.Id);

                    // If there is no Audio file present, then update.
                    if (videoLatest.Audio == null)
                    {
                        await _context.FileRecords.AddAsync(fileRecord);

                        videoLatest.Audio = fileRecord;
                        await _context.SaveChangesAsync();


                        // If no transcriptions present, produce transcriptions.
                        if (!videoLatest.Transcriptions.Any())
                        {
                            _transcriptionTask.Publish(videoLatest.Id);
                        }
                    }
                }
                else
                {
                    throw new Exception("ConvertVideoToWavTask Failed + " + video.Id);
                }
            }
        }
        private List <LeveledTask> createTasks(ref ConcurrentDictionary <string, ConcurrentDictionary <string, long> > allresult,
                                               int maxTasks,
                                               int MaxQueue,
                                               int MaxSleep,
                                               bool isHighPirotiy,
                                               bool randomPrority = false,
                                               int seedID         = 0)
        {
            var sw = new Stopwatch();

            sw.Start();

            var highProrityTasks   = 0;
            var normalProrityTasks = 0;
            var Tasks = new List <LeveledTask>();

            for (var i = seedID + 1; i <= maxTasks + seedID; i++)
            {
                var q     = string.Concat("Q", rnd.Next(1, MaxQueue));
                var taskP = new TaskParameters()
                {
                    Q = q, Seq = i
                };

                var bIsHighPrority = (isHighPirotiy || (randomPrority && rnd.Next(1, int.MaxValue) % 2 == 0));

                if (bIsHighPrority)
                {
                    highProrityTasks++;
                }
                else
                {
                    normalProrityTasks++;
                }

                // Trace.WriteLine(string.Format("task {0} created on queue {1}", i, q), "info-test");

                var lt = addTask(ref allresult, taskP, q, rnd.Next(1, MaxSleep), bIsHighPrority);

                Tasks.Add(lt);
            }

            sw.Stop();
            Trace.WriteLine(string.Format("Created N:{0}/H:{1} tasks in {2} ms", normalProrityTasks, highProrityTasks, sw.ElapsedMilliseconds), "info");
            return(Tasks);
        }
Esempio n. 34
0
        /// <inheritdoc />
        public async Task Run(TaskParameters arguments, IProgress <float> progress, CancellationToken cancellationToken)
        {
            string path = arguments["path"].As <string>();

            try
            {
                progress.Report(0);
                Track track = await _identifier.IdentifyTrack(path);

                progress.Report(25);

                if (track.Episode == null)
                {
                    throw new TaskFailedException($"No episode identified for the track at {path}");
                }
                if (track.Episode.ID == 0)
                {
                    if (track.Episode.Slug != null)
                    {
                        track.Episode = await _libraryManager.Get <Episode>(track.Episode.Slug);
                    }
                    else if (track.Episode.Path != null)
                    {
                        track.Episode = await _libraryManager.GetOrDefault <Episode>(x => x.Path.StartsWith(track.Episode.Path));

                        if (track.Episode == null)
                        {
                            throw new TaskFailedException($"No episode found for the track at: {path}.");
                        }
                    }
                    else
                    {
                        throw new TaskFailedException($"No episode identified for the track at {path}");
                    }
                }

                progress.Report(50);
                await _libraryManager.Create(track);

                progress.Report(100);
            }
            catch (IdentificationFailedException ex)
            {
                throw new TaskFailedException(ex);
            }
        }
Esempio n. 35
0
        /// <summary>
        /// Apply all values received in parameters collection to ReturnValue collection
        /// </summary>
        public override async Task <TaskResult> ExecuteTask(TaskParameters parameters)
        {
            var result      = new TaskResult();
            var dateTimeNow = DateTime.Now;             // Use single value throughout for consistency in macro replacements

            try
            {
                // Iterate through all keys in incoming parameter collection:
                foreach (var key in parameters.GetKeys())
                {
                    // Retrieve specified key value, processing date macros:
                    var value = parameters.GetString(key, null, dateTimeNow);

                    // Now process any nested macros in resulting value string - regex will capture argument-named macros,
                    // to allow keys passed as parameters to this adapter (including the keys of return values output by
                    // previous adapters in batch) to have their values updated with the value of other keys in collection
                    // (again including return values output by previous steps). For example, if a previous adapter in this
                    // batch output a return value of "@FileID"/57, placing the parameter "Command"/"echo <@@FileID>" in
                    // the collection for THIS adapter will result in value "Command"/"echo 57" being placed in the return
                    // value collection (and then placed into input parameter collections of subsequent steps):
                    var valuemacromatches = TaskUtilities.General.REGEX_NESTEDPARM_MACRO
                                            .Matches(value)
                                            .Cast <Match>()
                                            // Flatten match collection into name/value pair and select unique values only:
                                            .Select(match => new { Name = match.Groups["name"].Value, Value = match.Value })
                                            .Distinct();
                    foreach (var match in valuemacromatches)
                    {
                        // Retrieve parameter matching the "name" portion of the macro - processing date/time macros
                        // again - and replace all instances of the specified macro with the string retrieved:
                        value = value.Replace(match.Value, parameters.GetString(match.Name, null, dateTimeNow));
                    }

                    // Add final value to return value collection:
                    result.AddReturnValue(key, value);
                }

                result.Success = true;
            }
            catch (Exception ex)
            {
                result.AddException(ex);
            }
            return(result);
        }
Esempio n. 36
0
        /// <inheritdoc />
        public Task Run(TaskParameters arguments, IProgress <float> progress, CancellationToken cancellationToken)
        {
            ICollection <IPlugin> plugins = _pluginManager.GetAllPlugins();
            int count = 0;

            progress.Report(0);

            foreach (IPlugin plugin in plugins)
            {
                plugin.Initialize(_provider);

                progress.Report(count / plugins.Count * 100);
                count++;
            }

            progress.Report(100);
            return(Task.CompletedTask);
        }
Esempio n. 37
0
        private RKResults DrawRes(RKResults r, RAlgSolver ra, string cn, string cnsuff, Color c, OutputHelper output,
                                  int eb, out double functional)
        {
            if (!isReal)
            {
                for (int i = 0; i < r.Count - setCount; i++)
                {
                    if (eb == 1)
                    {
                        if (setCount == 1)
                        {
                            (tblResList as List<ResPointViewType1>)[i + i*step].M1 = ra.itab[i];
                        }
                        else
                        {
                            (tblResList as List<ResPointViewType2>)[i + i*step].M1 = ra.itab[i];
                        }
                    }
                    else
                    {
                        if (setCount == 1)
                        {
                            (tblResList as List<ResPointViewType1>)[i + i*step].M2 = ra.itab[i];
                        }
                        else
                        {
                            (tblResList as List<ResPointViewType2>)[i + i*step].M2 = ra.itab[i];
                        }
                    }
                }
                grcTabRes.RefreshDataSource();
            }

            var sb = new StringBuilder();

            Dictionary<double, int> tt = GetTT(r, ra.itab);

            //-- draw res ---
            if (!curves.ContainsKey(cn))
            {
                curves.Add(cn, new PointPairList());
                var curve = new LineItem(cn, curves[cn], c, SymbolType.None);
                curve.Line.Style = DashStyle.Dash;
                curve.Line.Width = 2;
                //this.zgcMainChart2.MasterPane[1].CurveList.Add(curve);

                if (setCount == 2)
                {
                    curves.Add(cn + cnsuff, new PointPairList());
                    var curve1 = new LineItem(cn + cnsuff, curves[cn + cnsuff], c, SymbolType.None);
                    curve.Line.Style = DashStyle.Dash;
                    curve.Line.Width = 2;
                    zgcMainChart2.MasterPane[0].CurveList.Add(curve1);

                    zgcMainChart2.MasterPane[1].CurveList.Add(curve);
                }
                else
                {
                    zgcMainChart2.MasterPane[0].CurveList.Add(curve);
                }
            }
            else
            {
                curves[cn].Clear();
                if (setCount == 2)
                {
                    curves[cn + cnsuff].Clear();
                }
            }

            int k = 0;
            var listDraw = new List<TaskParameter>();
            for (int i = 0; i < tps.Count; i++)
            {
                var tpDraw = new TaskParameter(tps[i].Param.Length);
                string line = string.Format("{0}) ", i);
                for (int j = 0; j < tps[0].Param.Length; j++)
                {
                    tpDraw.Param[j] = ra.x[k];
                    line += string.Format("a{0}={1:f6} ", j, ra.x[k]);
                    k++;
                }
                sb.AppendLine(line);
                listDraw.Add(tpDraw);
            }
            sb.AppendLine("-----");

            var tps1 = new TaskParameters(listDraw, tt);
            var tw1 = new TaskWorker(tps1, funcDescr.GetType(), funcDescr.MainFuncName, funcDescr.SecFuncName, funcDescr);

            double t0, t1;
            if (!isReal)
            {
                t0 = double.Parse(txtT0.Text);
                t1 = double.Parse(txtT1.Text);
            }
            else
            {
                t0 = 0;
                t1 = ASignal.Count*0.01;
            }
            var rk1 = new RKVectorForm(tw1, cn, t0, t1, startVector);
            RKResults res1 = rk1.SolveWithConstH(res.Count - 1, RKMetodType.RK2_1);

            functional = GetDiff(res, res1);
            sb.Append(string.Format("f={0:f6}", functional));
            //rtb.Text = sb.ToString();
            //this.SetControlFeathe(rtb, "text=", sb.ToString());
            output.WriteLine(sb.ToString());

            int nn = setCount == 1 ? 1 : 2;
            for (int i = 0; i < res1.Count - nn; i++)
            {
                if (nn == 1)
                {
                    curves[cn].Add(res1[i].X, res1[i].Y[0]);
                }
                else
                {
                    curves[cn].Add(res1[i].Y[0], res1[i].Y[1]);
                    curves[cn + cnsuff].Add(res1[i].X, res1[i].Y[0]);
                }
            }
            SetControlProperty(zgcMainChart2, "chart", null);
            //this.zgcMainChart2.AxisChange();
            //this.zgcMainChart2.Refresh();
            return res1;
        }
Esempio n. 38
0
        private Vector RK4_1(double x, Vector y, double h, int j, TaskParameters taskP)
        {
            var res = new Vector(2);
            Vector f0, f1, f2, f3;

            f0 = h * ff(x, y, j, taskP);
            f1 = h * ff(x + h / 2, y + f0 / 2, j, taskP);
            f2 = h * ff(x + h / 2, y + f1 / 2, j, taskP);
            f3 = h * ff(x + h, y + f2, j, taskP);
            res = y + (f0 + 2 * f1 + 2 * f2 + f3) / 6;

            return res;
        }
Esempio n. 39
0
        private RAlgSolver(TaskWorker tw, RKResults res, List<List<double>> startParameters)
        {
            this.tw = tw;
            this.res = res;

            itab = new int[res.Count - 1];

            if (res[0].Y.Count == 2)
            {
                var dz1 = new double[res.Count - 1];
                for (int i = 1; i < res.Count; i++)
                {
                    dz1[i - 1] = (res[i].Y[0] - res[i - 1].Y[0]) / (res[i].X - res[i - 1].X);
                }
                var dz2 = new double[res.Count - 2];
                for (int i = 1; i < dz1.Length; i++)
                {
                    dz2[i - 1] = (dz1[i] - dz1[i - 1]) / (res[i].X - res[i - 1].X);
                }
                dz = dz2;
            }

            var list = new List<TaskParameter>();

            int k = 0;
            for (int i = 0; i < startParameters.Count; i++)
            {
                var tp1 = new TaskParameter(startParameters[i].Count);
                for (int j = 0; j < startParameters[i].Count; j++)
                {
                    x[k] = startParameters[i][j];
                    tp1.Param[j] = x[k];
                    k++;
                }
                list.Add(tp1);
            }
            c = k;
            tp = new TaskParameters(list, double.MinValue);
        }
Esempio n. 40
0
        public Vector MF1(double t, Vector v, TaskParameters p)
        {
            var res = new Vector(1);
            if (p.Gamma is List<double>)
            {
                var pp = new List<double>();
                (p.Gamma as List<double>).ForEach(x => pp.Add(x));

                pp.Insert(0, double.MinValue);
                pp.Add(double.MaxValue);

                //double a = double.MinValue;
                double b = pp[0];

                for (int i = 0; i < pp.Count - 1; i++)
                {
                    if (v[0] > pp[i] && v[0] <= pp[i + 1])
                    {
                        res[0] = CallSecFunc(SecFuncName, t, v, p[i]);
                    }
                    else
                        continue;
                }
            }
            else if (p.Gamma is Dictionary<double, int>)
            {
                try
                {
                    var tt = p.Gamma as Dictionary<double, int>;
                    //int i = -1;
                    double index = tt.Keys.ToList().Find(x => Math.Abs(x - t) < 0.01);
                    res[0] = CallSecFunc(SecFuncName, t, v, p[tt[index]]);
                }
                catch (Exception)
                {
                    res[0] = 1;
                }
            }
            else
                throw new NotImplementedException("not impl yet");
            return res;
        }
 /// <summary>
 /// This method is only for paramteter customizing (merge with Schedule(string name, ?)
 /// TaskName should be preinitialized and point to existing named tp in container.
 /// </summary>
 /// <param name="tp"></param>
 /// <param name="parallelism"></param>
 /// <param name="dueInSeconds"></param>
 protected void Schedule(TaskParameters tp, 
     ScheduleTaskParallelism parallelism = ScheduleTaskParallelism.AllowOthers, 
     int dueInSeconds = 0)
 {
     lock (runningTasks)
     {
         if (!IsStarted) throw new InvalidOperationException("Task scheduler is not running");
         log.Info("Scheduling "+tp);
         var entity = new ScheduleEntity()
                          {
                              NextExecution = DateTime.MaxValue,
                              Parallelism = parallelism,
                              TaskName = tp.TaskName,
                          };
         lock (repoLocker)
         {
             repo.Save(entity);
             repo.LoadSettingsIfNull(entity);
             foreach (KeyValuePair<string, object> setting in tp.Settings)
             {
                 entity.Settings.AddEntry(setting.Key, setting.Value);
             }
             entity.NextExecution = DateTime.Now.AddSeconds(Math.Max(0, dueInSeconds));
             repo.Update(entity);
         }
     }
 }
Esempio n. 42
0
 public void ThrowsExceptionWhenStringParameterIsNotPresentWithType()
 {
     var p = new TaskParameters(new Dictionary<string, string>());
     Assert.That(() => p.Parameter(typeof(string), "file"), Throws.InstanceOf<RequiredParameterNotGivenException>());
 }
Esempio n. 43
0
        private void btnSolveRK_Click(object sender, EventArgs e)
        {
            try
            {
                btnSolveRK.Enabled = false;
                isReal = false;
                view.Output.ClearScreen();
                grcTabRes.DataSource = null;
                n = int.Parse(txtN.Text, enUsCulture);
                setCount = rbN1.Checked ? 1 : 2;
                //this.gamma = double.Parse(txtGamma.Text);

                if (setCount == 1)
                {
                    view.ConfigGraphPane(zgcMainChart2, this, PaneLayout.SingleColumn, new List<ChartInfo>
                                                                                           {
                                                                                               new ChartInfo
                                                                                                   {
                                                                                                       Title = "(t,z1)",
                                                                                                       XAxisTitle = "t",
                                                                                                       YAxisTitle = "z1"
                                                                                                   },
                                                                                           });
                }
                else
                {
                    view.ConfigGraphPane(zgcMainChart2, this, PaneLayout.SingleColumn, new List<ChartInfo>
                                                                                           {
                                                                                               new ChartInfo
                                                                                                   {
                                                                                                       Title = "(t,z1)",
                                                                                                       XAxisTitle = "t",
                                                                                                       YAxisTitle = "z1"
                                                                                                   },
                                                                                               new ChartInfo
                                                                                                   {
                                                                                                       Title = "(z1,z2)",
                                                                                                       XAxisTitle = "z1",
                                                                                                       YAxisTitle = "z2"
                                                                                                   }
                                                                                           });
                }
                //ZedGraph.GraphPane gp = this.zgcMainChart2.GraphPane;
                //gp.CurveList.Clear();
                curves.Clear();

                if (setCount == 1)
                {
                    curves.Add(curveName, new PointPairList());
                    zgcMainChart2.MasterPane[0].AddCurve(curveName, curves[curveName], Color.Black, SymbolType.None);
                }
                else
                {
                    curves.Add(curveName, new PointPairList());
                    curves.Add(curveName + curveNameSuff, new PointPairList());
                    zgcMainChart2.MasterPane[0].AddCurve(curveName + curveNameSuff, curves[curveName + curveNameSuff],
                                                         Color.Black, SymbolType.None);
                    zgcMainChart2.MasterPane[1].AddCurve(curveName, curves[curveName], Color.Black, SymbolType.None);
                }

                var p = new List<double>();

                var gammaList = new List<double>();
                for (int i = 0; i < dgvGama.ColumnCount; i++)
                {
                    double d = double.Parse(dgvGama.Rows[0].Cells[i].Value.ToString().Replace(',', '.'), enUsCulture);
                    gammaList.Add(d);
                }

                var list = new List<TaskParameter>();
                for (int i = 0; i < dgvParameters.RowCount; i++)
                {
                    var tp = new TaskParameter(dgvParameters.ColumnCount);
                    for (int j = 0; j < dgvParameters.ColumnCount; j++)
                    {
                        double val = double.Parse(dgvParameters.Rows[i].Cells[j].Value.ToString().Replace(',', '.'),
                                                  enUsCulture);
                        tp.Param[j] = val;
                    }
                    list.Add(tp);
                }

                tps = new TaskParameters(list, gammaList);
                string mfName = setCount == 1 ? "MF1" : "MF2";
                funcDescr = new Functions_2_2(mfName, fnames[(sfList.SelectedItem as string).ToUpper()]);

                tw = new TaskWorker(tps, funcDescr.GetType(), funcDescr.MainFuncName, funcDescr.SecFuncName, funcDescr);

                startVector = setCount == 1
                                  ? new Vector(1, double.Parse(txtY0.Text.Replace(',', '.'), enUsCulture))
                                  : new Vector(2, double.Parse(txtY00.Text.Replace(',', '.'), enUsCulture),
                                               double.Parse(txtY01.Text.Replace(',', '.'), enUsCulture));

                var rk = new RKVectorForm(tw, curveName, double.Parse(txtT0.Text.Replace(',', '.'), enUsCulture),
                                          double.Parse(txtT1.Text.Replace(',', '.'), enUsCulture), startVector);
                res = rk.SolveWithConstH(n, RKMetodType.RK4_1);

                if (rbN1.Checked)
                {
                    for (int i = 0; i < res.Count - 1; i++)
                    {
                        curves[curveName].Add(res[i].X, res[i].Y[0]);
                    }
                    //res.ForEach(r => this.curves[curveName].Add(r.X, r.Y[0]));
                }
                else
                {
                    for (int i = 0; i < res.Count - 2; i++)
                    {
                        curves[curveName + curveNameSuff].Add(res[i].X, res[i].Y[0]);
                        curves[curveName].Add(res[i].Y[0], res[i].Y[1]);
                    }
                    //res.ForEach(r => this.curves[curveName].Add(r.Y[0], r.Y[1]));
                }
                zgcMainChart2.AxisChange();
                zgcMainChart2.Refresh();

                if (setCount == 1)
                {
                    tblResList = new List<ResPointViewType1>();
                    for (int i = 0; i < res.Count - 1; i++)
                        (tblResList as List<ResPointViewType1>).Add(new ResPointViewType1(res[i].X, res[i].Y[0], -1, -1));
                    grcTabRes.DataSource = null;
                    grcTabRes.DataSource = tblResList;
                }
                else
                {
                    tblResList = new List<ResPointViewType2>();
                    for (int i = 0; i < res.Count - 2; i++)
                        (tblResList as List<ResPointViewType2>).Add(new ResPointViewType2(res[i].X, res[i].Y[0],
                                                                                          res[i].Y[1], -1, -1));
                    grcTabRes.DataSource = null;
                    grcTabRes.DataSource = tblResList;
                }
                grcTabRes.RefreshDataSource();
            }
            finally
            {
                btnSolveRK.Enabled = true;
            }
        }
Esempio n. 44
0
        private void btnSolveRK_Click(object sender, EventArgs e)
        {
            this.rtbResult1.Text = this.rtbResult2.Text = string.Empty;
            this.dgvTabRes.DataSource = null;
            this.n = int.Parse(this.txtN.Text);
            this.setCount = this.rbN1.Checked ? 1 : 2;
            //this.gamma = double.Parse(txtGamma.Text);

            ZedGraph.GraphPane gp = this.zgcMainChart2.GraphPane;
            gp.CurveList.Clear();
            this.curves.Clear();

            this.curves.Add(this.curveName, new PointPairList());
            gp.AddCurve(this.curveName, this.curves[curveName], Color.Black, SymbolType.None);

            List<double> gammaList = new List<double>();
            List<double> p = new List<double>();

            for (int i = 0; i < dgvGama.ColumnCount; i++)
            {
                gammaList.Add(Convert.ToDouble(dgvGama.Rows[0].Cells[i].Value));
            }

            List<TaskParameter> list = new List<TaskParameter>();
            for (int i = 0; i < dgvParameters.RowCount; i++)
            {
                TaskParameter tp = new TaskParameter(dgvParameters.ColumnCount);
                for (int j = 0; j < dgvParameters.ColumnCount; j++)
                {
                    double val = Convert.ToDouble(dgvParameters.Rows[i].Cells[j].Value);
                    tp.Param[j] = val;
                }
                list.Add(tp);
            }

            this.tps = new TaskParameters(list, gammaList);
            string mfName = this.setCount == 1 ? "MF1" : "MF2";
            this.funcDescr = new Functions_2_2(mfName, this.fnames[(sfList.SelectedItem as string).ToUpper()]);

            this.tw = new TaskWorker(tps, funcDescr.GetType(), funcDescr.MainFuncName, funcDescr.SecFuncName, funcDescr);

            this.startVector = this.setCount == 1 ? new Vector(1, double.Parse(this.txtY0.Text)) :
                new Vector(2, double.Parse(this.txtY00.Text), double.Parse(this.txtY01.Text));

            RKVectorForm rk = new RKVectorForm(tw, curveName, double.Parse(this.txtT0.Text), double.Parse(this.txtT1.Text), startVector);
            this.res = rk.SolveWithConstH(n, RKMetodType.RK4_1);

            if (this.rbN1.Checked)
            {
                res.ForEach(r => this.curves[curveName].Add(r.X, r.Y[0]));
            }
            else
            {
                res.ForEach(r => this.curves[curveName].Add(r.Y[0], r.Y[1]));
            }
            this.zgcMainChart2.AxisChange();
            this.zgcMainChart2.Refresh();

            if (this.setCount == 1)
            {
                this.tblResList = new List<ResPointViewType1>();
                for (int i = 0; i < res.Count - 1; i++)
                    (this.tblResList as List<ResPointViewType1>).Add(new ResPointViewType1(res[i].X, res[i].Y[0], -1, -1));
                this.dgvTabRes.DataSource = null;
                this.dgvTabRes.DataSource = tblResList;
            }
            else
            {
                this.tblResList = new List<ResPointViewType2>();
                for (int i = 0; i < res.Count - 2; i++)
                    (this.tblResList as List<ResPointViewType2>).Add(new ResPointViewType2(res[i].X, res[i].Y[0], res[i].Y[1], -1, -1));
                this.dgvTabRes.DataSource = null;
                this.dgvTabRes.DataSource = tblResList;
            }
            this.dgvTabRes.RefreshDataSource();

            this.randomStartParameters = this.GetRandomStartParam();
        }
Esempio n. 45
0
 private Vector ff(double t, Vector y, int j, TaskParameters taskP)
 {
     return new Vector(2, y[1], tw.FunctionSet(t, y, j, taskP));
 }
Esempio n. 46
0
 public void CanParseDefaultStringParameter()
 {
     var p = new TaskParameters(new Dictionary<string, string> {{"file", "thefile.txt"}});
     Assert.That(p.Parameter("file", "afile.txt"), Is.EqualTo("thefile.txt"));
 }
    protected void lnkBreakWithCopy_Click(Object sender, EventArgs e)
    {
        // Check permission
        CanModifyPermission(true);

        // Break permission inheritance and copy parent permissions
        AclProvider.BreakInherintance(Node, true);

        // Log staging task
        TaskParameters taskParam = new TaskParameters();
        taskParam.SetParameter("copyPermissions", true);
        DocumentSynchronizationHelper.LogDocumentChange(Node, TaskTypeEnum.BreakACLInheritance, Node.TreeProvider, SynchronizationInfoProvider.ENABLED_SERVERS, taskParam, Node.TreeProvider.AllowAsyncActions);

        // Insert information about this event to eventlog.
        if (Tree.LogEvents)
        {
            EventLog.LogEvent(EventLogProvider.EVENT_TYPE_INFORMATION, DateTime.Now, "Content", "DOCPERMISSIONSMODIFIED", Tree.UserInfo.UserID, Tree.UserInfo.UserName, Node.NodeID, DocumentName, ipAddress, ResHelper.GetAPIString("security.documentpermissionsbreakcopy", "Inheritance of the parent document permissions have been broken. Parent document permissions have been copied."), Node.NodeSiteID, eventUrl);
        }

        lblInheritanceInfo.Text = GetString("Security.InheritsInfo.DoesNotInherit");
        SwitchBackToPermissionsMode();

        // Clear and reload
        securityElem.InvalidateAcls();
        securityElem.LoadOperators(true);
    }
Esempio n. 48
0
        private double CalcFunct1(TaskParameters taskP)
        {
            double f = 0;
            var val = new List<double>();
            var v = new List<Vector>();
            double h = res.GetH();
            var rk = new Vector[res.Count - 1];
            rk[0] = new Vector(1, startP[0]);
            itab[0] = 1;
            double t = res[0].X;
            for (int i = 1; i < res.Count - 1; i++)
            {
                val.Clear();
                v.Clear();
                for (int j = 0; j < tw.SetCount; j++)
                {
                    double x1 = rk[i - 1][0] + tw.FunctionSet(t, rk[i - 1], j, taskP) * h;
                    v.Add(new Vector(1, x1));
                    val.Add(Math.Abs(x1 - res[i].Y[0]));
                }
                double min = val.Min();
                int index = val.IndexOf(min);
                rk[i] = v[index];
                itab[i] = index + 1;
                f += min * min * h;
                t = t + h;
            }

            return f;
        }
        public void Task_T()
        {
            var maxQueue = 10;
            var maxTasks = 5000;
            var maxSleep = 10;
            var IsHighPrority = false;
            var result = new ConcurrentDictionary<string, ConcurrentDictionary<string, long>>();
            var sw = new Stopwatch();
            sw.Start();

            var Tasks = new List<Task<long>>();

            for (var qNum = 1; qNum <= maxQueue; qNum++)
            {
                var qName = string.Concat("Q", qNum);
                for (var Seq = 1; Seq < maxTasks / maxQueue; Seq++)
                {
                    var taskP = new TaskParameters() { Q = qName, Seq = Seq };

                    LeveledTask<long> lt = new LeveledTask<long>( (param) =>
                    {
                        // this force the new task not to be inlined.

                        var p = param as TaskParameters;

                        var resultQ = result.GetOrAdd(p.Q, new ConcurrentDictionary<string, long>());
                        resultQ.AddOrUpdate(string.Concat("S", p.Seq), DateTime.UtcNow.Ticks, (key, current) => { throw new InvalidOperationException("Found existing key"); });
                        //Trace.WriteLine(string.Format("Task {0} on Queue {1} - Start", p.Seq, p.Q), "info");
                        Thread.Sleep(maxSleep);
                        //Trace.WriteLine(string.Format("Task {0} on Queue {1} - End", p.Seq, p.Q), "info");
                        resultQ.AddOrUpdate(string.Concat("E", p.Seq), DateTime.UtcNow.Ticks, (key, current) => { throw new InvalidOperationException("Found existing key"); });

                        return DateTime.Now.Ticks;
                    },
                    taskP);

                    lt.QueueId = qName;
                    lt.IsHighPriority = IsHighPrority;
                    lt.Start(scheduler);
                    Tasks.Add(lt);
                }
            }

            Task.WhenAll(Tasks).Wait();

            foreach (var task in Tasks)
                Trace.WriteLine(String.Format("Task result was:{0} ", task.Result));

            sw.Stop();
            Trace.WriteLine(string.Format("{0} Tasks on {1} Queues - Executed in {2} sec", maxTasks, maxQueue, sw.Elapsed.Seconds), "info");
            verify(ref result);
        }
Esempio n. 50
0
        private void btnTransfer_Click(object sender, EventArgs e)
        {
            isReal = true;
            view.Output.ClearScreen();
            grcTabRes.DataSource = null;
            n = int.Parse(txtN.Text);
            setCount = rbN1.Checked ? 1 : 2;

            double t = 0;
            var r = new RKResults();
            foreach (double y in ASignal)
            {
                r.Add(new RKResult(t, new Vector(1, y)));
                t += 0.01;
            }
            res = r;
            randomStartParameters = GetRandomStartParam();

            var gammaList = new List<double>();
            for (int i = 0; i < dgvGama.ColumnCount; i++)
            {
                gammaList.Add(Convert.ToDouble(dgvGama.Rows[0].Cells[i].Value));
            }

            var list = new List<TaskParameter>();
            for (int i = 0; i < dgvParameters.RowCount; i++)
            {
                var tp = new TaskParameter(dgvParameters.ColumnCount);
                for (int j = 0; j < dgvParameters.ColumnCount; j++)
                {
                    double val = Convert.ToDouble(dgvParameters.Rows[i].Cells[j].Value);
                    tp.Param[j] = val;
                }
                list.Add(tp);
            }

            tps = new TaskParameters(list, gammaList);
            string mfName = setCount == 1 ? "MF1" : "MF2";
            funcDescr = new Functions_2_2(mfName, fnames[(sfList.SelectedItem as string).ToUpper()]);
            startVector = new Vector(1, 0);
            tw = new TaskWorker(tps, funcDescr.GetType(), funcDescr.MainFuncName, funcDescr.SecFuncName, funcDescr);

            xtcMain.SelectedTabPageIndex = 2;
        }
Esempio n. 51
0
        public double Integral(TaskParameters taskP)
        {
            lambda = new int[taskP.Count, dz.Length];
            itab = new int[dz.Length];

            var diffValues = new List<double>();
            int k;
            for (int i = 0; i < dz.Length; i++)
            {
                diffValues.Clear();
                for (int j = 0; j < tw.SetCount; j++)
                {
                    double d = Math.Abs(dz[i] - tw.FunctionSet(res[i].X, res[i].Y, j, taskP));
                    diffValues.Add(d);
                }
                k = diffValues.IndexOf(diffValues.Min());
                for (int j = 0; j < tw.SetCount; j++)
                {
                    lambda[j, i] = j == k ? 1 : 0;
                }
                itab[i] = k + 1;
            }

            double val = 0;
            for (int i = 0; i < dz.Length - 1; i++)
            {
                for (int j = 0; j < tw.SetCount; j++)
                {
                    val += lambda[j, i] * Math.Pow(dz[i] - tw.FunctionSet(res[i].X, res[i].Y, j, taskP), 2);
                }
            }
            val *= res.GetH();
            return val;
        }
Esempio n. 52
0
 public void CanParseDefaultStringParameterIfNotPresentWithType()
 {
     var p = new TaskParameters(new Dictionary<string, string>());
     Assert.That(p.Parameter(typeof(string), "file", "afile.txt"), Is.EqualTo("afile.txt"));
 }
Esempio n. 53
0
 public void Invoke(TaskParameters taskParameters) {
     WasInvoked = true;
     WasInvokedWithTaskParameters = taskParameters;
 }
Esempio n. 54
0
        private void btnSolveRAlg2_Click(object sender, EventArgs e)
        {
            try
            {
                this.btnSolveRAlg2.Enabled = false;
                int tick = Environment.TickCount;
                this.inf2 = null;
                //List<List<double>> sp = this.GetRandomStartParam();
                List<List<double>> sp = this.randomStartParameters;

                RAlgSolver ra = new RAlgSolver(this.tw, this.res, sp, this.startVector);
                ra.FUNCT = new RAlgSolver.FUNCTDelegate(ra.FUNCT4);
                ra.R_Algorithm();

                for (int i = 0; i < res.Count - this.setCount; i++)
                {
                    if (this.setCount == 1)
                    {
                        (this.tblResList as List<ResPointViewType1>)[i].M2 = ra.itab[i];
                    }
                    else
                    {
                        (this.tblResList as List<ResPointViewType2>)[i].M2 = ra.itab[i];
                    }
                }
                this.dgvTabRes.RefreshDataSource();

                Dictionary<double, int> tt = this.GetTT(this.res, ra.itab);

                StringBuilder sb = new StringBuilder();

                //-- draw res ---
                if (!this.curves.ContainsKey(this.curveName2))
                {
                    this.curves.Add(this.curveName2, new PointPairList());
                    LineItem curve = new LineItem(this.curveName2, this.curves[curveName2], Color.Blue, SymbolType.None);
                    curve.Line.Style = System.Drawing.Drawing2D.DashStyle.DashDot;
                    curve.Line.Width = 2;
                    this.zgcMainChart2.GraphPane.CurveList.Add(curve);
                }
                else
                {
                    this.curves[this.curveName2].Clear();
                }

                int k = 0;
                List<TaskParameter> listDraw = new List<TaskParameter>();
                for (int i = 0; i < tps.Count; i++)
                {
                    TaskParameter tpDraw = new TaskParameter(tps[i].Param.Length);
                    string line = string.Format("{0}) ", i);
                    for (int j = 0; j < tps[0].Param.Length; j++)
                    {
                        tpDraw.Param[j] = ra.x[k];
                        line += string.Format("a{0}={1:f6} ", j, ra.x[k]);
                        k++;
                    }
                    sb.AppendLine(line);
                    listDraw.Add(tpDraw);
                }
                sb.AppendLine("-----");
                sb.Append(string.Format("f={0}", ra.f));
                rtbResult2.Text = sb.ToString();

                TaskParameters tps1 = new TaskParameters(listDraw, tt);
                TaskWorker tw1 = new TaskWorker(tps1, this.funcDescr.GetType(), this.funcDescr.MainFuncName, this.funcDescr.SecFuncName, this.funcDescr);
                RKVectorForm rk1 = new RKVectorForm(tw1, curveName2, double.Parse(this.txtT0.Text), double.Parse(this.txtT1.Text), this.startVector);
                RKResults res1 = rk1.SolveWithConstH(n, RKMetodType.RK2_1);

                //if (this.setCount == 1)
                //{
                //    res1.ForEach(r => this.curves[this.curveName2].Add(r.X, r.Y[0]));
                //}
                //else
                //{
                //    res1.ForEach(r => this.curves[this.curveName2].Add(r.Y[0], r.Y[1]));
                //}
                int nn = this.setCount == 1 ? 1 : 2;
                for (int i = 0; i < res1.Count - nn; i++)
                {
                    if (nn == 1)
                    {
                        this.curves[curveName2].Add(res1[i].X, res1[i].Y[0]);
                    }
                    else
                    {
                        this.curves[curveName2].Add(res1[i].Y[0], res1[i].Y[1]);
                    }
                }
                this.zgcMainChart2.AxisChange();
                this.zgcMainChart2.Refresh();

                this.ra2 = ra;
                double t = ((Environment.TickCount - tick) / (double)1000);

                this.rtbResult2.Text += string.Format("\r\n-----\r\ntime = {0} sec", t);
                this.inf2 = string.Format("Result: f = {0:f6} time = {1} sec", ra.f, t);
            }
            finally
            {
                this.btnSolveRAlg2.Enabled = true;
            }
        }
Esempio n. 55
0
 public void CanParseEnumeration()
 {
     var p = new TaskParameters(new Dictionary<string, string> { { "lake", "constance" } });
     Assert.That(p.Parameter<Lakes>("lake"), Is.EqualTo(Lakes.Constance));
 }
        private LeveledTask addTask(ref ConcurrentDictionary<string, ConcurrentDictionary<string, long>>  allresult , 
                            TaskParameters taskP, 
                            string q,
                            int maxSleep, 
                            bool IsHighPrority = false)
        {
            var result = allresult;

            LeveledTask lt = new LeveledTask((param) =>
            {
                var p = param as TaskParameters;

                var resultQ = result.GetOrAdd(p.Q, new ConcurrentDictionary<string, long>());
                resultQ.AddOrUpdate(string.Concat("S", p.Seq), DateTime.UtcNow.Ticks, (key, current) => { throw new InvalidOperationException("Found existing key"); });
                //Trace.WriteLine(string.Format("Task {0} on Queue {1} - Start", p.Seq, p.Q), "info");
                Thread.Sleep(maxSleep);
                //Trace.WriteLine(string.Format("Task {0} on Queue {1} - End", p.Seq, p.Q), "info");
                resultQ.AddOrUpdate(string.Concat("E", p.Seq), DateTime.UtcNow.Ticks, (key, current) => { throw new InvalidOperationException("Found existing key"); });
            },
                       taskP);

            lt.QueueId = q;
            lt.IsHighPriority = IsHighPrority;
            lt.Start(scheduler);

            return lt;
        }
Esempio n. 57
0
 public void CanParseStringParameterWithType()
 {
     var p = new TaskParameters(new Dictionary<string, string> { { "file", "thefile.txt" } });
     Assert.That(p.Parameter(typeof(string), "file", "afile.txt"), Is.EqualTo("thefile.txt"));
 }
        private List<LeveledTask> createTasks(ref ConcurrentDictionary<string, ConcurrentDictionary<string, long>> allresult,
                                            int maxTasks,
                                            int MaxQueue,
                                            int MaxSleep, 
                                            bool isHighPirotiy,
                                            bool randomPrority = false,
                                            int seedID = 0)
        {
            var sw = new Stopwatch();
            sw.Start();

            var highProrityTasks = 0;
            var normalProrityTasks = 0;
            var Tasks = new List<LeveledTask>();

            for (var i = seedID + 1; i <= maxTasks + seedID; i++)
            {
                var q = string.Concat("Q", rnd.Next(1, MaxQueue));
                var taskP = new TaskParameters() { Q = q, Seq = i };

                var bIsHighPrority = (isHighPirotiy || (randomPrority && rnd.Next(1, int.MaxValue) % 2 == 0));

                if (bIsHighPrority)
                    highProrityTasks++;
                else
                    normalProrityTasks++;

               // Trace.WriteLine(string.Format("task {0} created on queue {1}", i, q), "info-test");

                    var lt = addTask(ref allresult, taskP, q, rnd.Next(1, MaxSleep), bIsHighPrority);

                Tasks.Add(lt);
            }

            sw.Stop();
            Trace.WriteLine(string.Format("Created N:{0}/H:{1} tasks in {2} ms", normalProrityTasks, highProrityTasks, sw.ElapsedMilliseconds), "info");
            return Tasks;
        }
Esempio n. 59
0
        private double CalcFunct2_1(TaskParameters taskP)
        {
            double f = 0;
            var val = new List<double>();
            var min1List = new List<double>();
            //List<double> min2List = new List<double>();
            var v = new List<Vector>();
            double h = res.GetH();
            var rk = new Vector[res.Count - 1];
            rk[0] = new Vector(2, startP[0], startP[1]);
            itab[0] = 1;
            double t = res[0].X;
            for (int i = 1; i < res.Count - 2; i++)
            {
                val.Clear();
                min1List.Clear();
                v.Clear();
                for (int j = 0; j < tw.SetCount; j++)
                {
                    Vector vv = RK4_1(t, rk[i - 1], h, j, taskP);
                    v.Add(vv);
                    double min1 = Math.Abs(vv[0] - res[i].Y[0]);
                    //double min2 = Math.Abs(vv[1] - this.dz[i]);
                    val.Add(min1);
                    min1List.Add(min1);
                    //min2List.Add(min2);

                    //if (i < this.dz.Length)
                    //{
                    //    val2.Add(Math.Abs(vv[1] - this.dz[i]));
                    //}
                }
                double min = val.Min();
                int index = val.IndexOf(min);
                rk[i] = v[index];
                itab[i] = index + 1;
                //f += min * min * h;
                f += (Math.Pow(min1List[index], 2) + alpha * (v[index][0] * v[index][0] + v[index][1] * v[index][1])) * h;
                t = t + h;
            }

            return f;
        }