public List <AnalysisModel> startDepartmentAnalysis(string userId) { Departments department = findDepartmentByEmployee(userId); var past4Month = DateTime.Now.AddMonths(-1).Month; var Year = DateTime.Now.Year; var po = from req in dbcontext.requisitions join req_d in dbcontext.requisitionDetails on req.Id equals req_d.RequisitionId group req_d by new { req.Department.DeptName, req_d.Inventory.ItemCategory.name, req.DateSubmitted.Month, req.DateSubmitted.Year } into h where (h.Key.Month >= past4Month && h.Key.Year == Year && h.Key.DeptName == department.DeptName) select new { Month = h.Key.Month, Qty = h.Sum(x => x.RequestedQty), Category = h.Key.name }; List <AnalysisModel> aQ = new List <AnalysisModel>(); foreach (var c in po) { AnalysisModel a = new AnalysisModel(); a.quantity = c.Qty; a.Category = c.Category; aQ.Add(a); } return(aQ); }
public ActionResult Index(AnalysisModel model) { if (!ModelState.IsValid) { return(View()); } var content = string.Empty; if (!Utility.IsValidUrl(model.Text)) { return(View("Result", new ResultModel { WordOccurenceOnText = TextAnalyser.Analyse(model.Text) })); } if (!Utility.TryGetContent(model.Text, out string htmlContent)) { ModelState.AddModelError("", "The Url is invalid."); return(View()); } return(View("Result", new ResultModel { WordOccurenceOnPage = model.WordOccurenceOnPage ? BodyAnalyser.Analyse(htmlContent) : new Dictionary <string, int>(), WordOccurenceOnMeta = model.WordOccurenceOnMeta ? MetaAnalyser.Analyse(htmlContent) : new Dictionary <string, int>(), ExternalLinkOccurence = model.ExternalLinkOccurence ? LinkAnalyser.Analyse(htmlContent) : new Dictionary <string, int>() })); }
public async Task <IActionResult> Edit(int id, [Bind("AnalysisId,StartTime,EndTime,AnalysisName,UserGivenNetworkType,UserGivenNodes,UserGivenTarget,UserGivenDrugTarget,NetworkNodeCount,NetworkNodes,NetworkEdgeCount,NetworkEdges,NetworkTargetCount,NetworkTargets,NetworkDrugTargetCount,NetworkDrugTargets,NetworkBestResultCount,NetworkBestResultNodes,DoContact,Status,ScheduledToStop,AlgorithmType,GeneticRandomSeed,GeneticMaxIteration,GeneticIterationNoImprovement,GeneticMaxPathLength,GeneticPopulationSize,GeneticElementsRandom,GeneticPercentageRandom,GeneticPercentageElite,GeneticProbabilityMutation,GreedyRandomSeed,GreedyMaxIteration,GreedyMaxIterationNoImprovement,GreedyMaxPathLength,GreedyHeuristics")] AnalysisModel analysisModel) { if (id != analysisModel.AnalysisId) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(analysisModel); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!AnalysisModelExists(analysisModel.AnalysisId)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(analysisModel)); }
public void ExternalLinkAnalysis_Success() { // Arrange var htmlContent = "<html><body><a href=\"https://valid.url\">This is a test.</a></body></html>"; var model = new AnalysisModel { ExternalLinkOccurence = true, Text = "http://www.valid.url" }; var mock = new Mock <IUrlUtility>(); mock.Setup(m => m.IsValidUrl(model.Text)).Returns(true); mock.Setup(m => m.GetContent(model.Text)).Returns(htmlContent); mock.Setup(m => m.TryGetContent(model.Text, out htmlContent)).Returns(true); var controller = GetHomeController(mock.Object); // Act var result = controller.Index(model) as ActionResult; // Assert Assert.IsInstanceOfType(result, typeof(ViewResult)); var viewResult = result as ViewResult; Assert.AreEqual("Result", viewResult.ViewName); Assert.IsInstanceOfType(viewResult.Model, typeof(ResultModel)); var resultModel = viewResult.Model as ResultModel; Assert.AreNotEqual(0, resultModel.ExternalLinkOccurence.Count); }
public Analysis Create(AnalysisModel model, Infrastructure.Database.AppContext context) { //TODO return(new Analysis() { }); }
public async Task <IActionResult> Create([Bind("AnalysisName,UserIsNetworkSeed,UserGivenNetworkGeneration,UserGivenNodes,UserGivenTarget,UserGivenDrugTarget,AlgorithmType,GeneticRandomSeed,GeneticMaxIteration,GeneticMaxIterationNoImprovement,GeneticMaxPathLength,GeneticPopulationSize,GeneticElementsRandom,GeneticPercentageRandom,GeneticPercentageElite,GeneticProbabilityMutation,GreedyRandomSeed,GreedyMaxIteration,GreedyMaxIterationNoImprovement,GreedyMaxPathLength,GreedyRepeats,GreedyHeuristics")] AnalysisModel analysisModel) { ApplicationUser user = await _userManager.GetUserAsync(HttpContext.User); analysisModel.User = user; // If the model is valid and the user is logged in. if (ModelState.IsValid && user != null) { // If the network is generated successfully. if (AlgorithmFunctions.GenerateNetwork(analysisModel)) { // Save the new analysis to the database. _context.Add(analysisModel); await _context.SaveChangesAsync(); // Calling on a Hangfire background task the analysis run. var analysisRun = new AnalysisRun(_context); BackgroundJob.Enqueue(() => analysisRun.RunAnalysis(analysisModel.AnalysisId)); // This also seems to be working. The only problem is that it's not implmeneted on a background task. // await AlgorithmFunctions.RunAnalysis(_context, analysisModel); // Return to Dashboard. return(RedirectToAction(nameof(Index))); } else { return(View(analysisModel)); } } return(View(analysisModel)); }
public Signal Apply(AnalysisModel model) { Signal signal = new Signal(); if (model.Candles.Count < 2) { return(signal); } var currentCandle = model.HeikinAshi.Last(); var previousCandle = model.HeikinAshi.ElementAt(model.Candles.Count - 2); if (currentCandle.Close > previousCandle.High) { signal.TradeType = TradeType.Long; signal.SignalType = SignalType.Entry; signal.Price = currentCandle.Close; } else if (currentCandle.Close < previousCandle.Low) { signal.TradeType = TradeType.Short; signal.SignalType = SignalType.Entry; signal.Price = currentCandle.Close; } signal.Strength = 100; signal.TimeStamp = model.Candles.Last().TimeStamp; return(signal); }
public void CreateAnalysis(AnalysisModel model) { using (IDbConnection connection = new SqlConnection(GlobalConfig.CnnString(db))) { var p = new DynamicParameters(); p.Add("@ProductId", model.ProductId); p.Add("@id", model.Id, dbType: DbType.Int32, direction: ParameterDirection.InputOutput); try { connection.Execute("dbo.spAnalyses_Insert", p, commandType: CommandType.StoredProcedure); } catch (SqlException ex) { throw new Exception(ex.HelpLink, new Exception(ex.Message)); } model.Id = p.Get <int>("@id"); foreach (AnalysisNutrientModel an in model.Nutrients) { if (an.Amount != decimal.Zero) { p = new DynamicParameters(); p.Add("@AnalysisId", model.Id); p.Add("@NutrientId", an.NutrientId); p.Add("@Amount", an.Amount); connection.Execute("dbo.spAnalysisNutrients_Insert", p, commandType: CommandType.StoredProcedure); } } } }
public CacheDumpAnalyzer(AnalysisInput input, string outputDir, HashSet <long> targetSemistableHashSet) : base(input) { m_model = new AnalysisModel(CachedGraph); m_outputDir = outputDir; m_targetSemistableHashSet = targetSemistableHashSet; }
public void Run(AnalysisModel model) { foreach (IRule rule in Rules) { rule.Check(model); } }
/// <summary> /// Constructor. /// </summary> public FingerprintStoreAnalyzer(AnalysisInput analysisInputOld, AnalysisInput analysisInputNew) : base(analysisInputNew) { if (analysisInputOld.ExecutionLogPath.Equals(analysisInputNew.ExecutionLogPath, StringComparison.OrdinalIgnoreCase)) { var fingerprintStoreDirectories = Directory.GetDirectories(Path.GetDirectoryName(analysisInputNew.ExecutionLogPath), Scheduler.Scheduler.FingerprintStoreDirectory + "*", SearchOption.AllDirectories); if (fingerprintStoreDirectories.Length != 2) { throw new BuildXLException($"Expecting two '{Scheduler.Scheduler.FingerprintStoreDirectory}' directories under log path '{Path.GetDirectoryName(analysisInputNew.ExecutionLogPath)}'"); } else { m_oldStoreLocation = fingerprintStoreDirectories.First(x => !x.EndsWith(Scheduler.Scheduler.FingerprintStoreDirectory)); m_newStoreLocation = fingerprintStoreDirectories.First(x => x.EndsWith(Scheduler.Scheduler.FingerprintStoreDirectory)); Console.WriteLine($"Comparing old fingerprint store {m_oldStoreLocation} with new one {m_newStoreLocation}"); m_model = new AnalysisModel(CachedGraph); } } else { m_oldStoreLocation = GetStoreLocation(analysisInputOld); m_newStoreLocation = GetStoreLocation(analysisInputNew); m_model = new AnalysisModel(CachedGraph); } }
public IHttpActionResult CreateAnalysis([FromUri] List <string> algorithms, [FromUri] string dataSet, [FromUri] string name) { if (_analysisManager.ReadAnalysis(name) != null) { return(BadRequest("Name already in use!")); } List <Model> models = GetFullModels(algorithms, dataSet); Analysis analysis = new Analysis() { Name = name, DateCreated = DateTime.Now, AnalysisModels = new List <AnalysisModel>(), NumberOfSolvents = models[0].NumberOfSolvents }; foreach (Model m in models) { AnalysisModel analysisModel = new AnalysisModel() { Model = m }; analysis.AnalysisModels.Add(analysisModel); } analysis = _analysisManager.CreateAnalysis(analysis, User.Identity.Name); return(Ok(analysis)); }
public IHttpActionResult Put(AnalysisModel model, int id) { if (model == null) { return(BadRequest("Model is null")); } if (id <= 0) { return(BadRequest("ID not valid")); } try { var application = Repository.Get(id); if (application == null) { return(NotFound()); } Repository.Update(Parser.Create(model, Repository.HomeContext()), id); return(Ok()); } catch (Exception ex) { return(BadRequest(ex.Message)); } }
public override void ProcessRow(IList <object> row) { bool idExists = int.TryParse((string)row[IdIndex], out int id); if (idExists == false) { id = 0; } AnalysisModel newAnalysisModel = new AnalysisModel { Id = id, ProductId = Convert.ToInt32(row[ProductIdIndex]), Nutrients = new List <AnalysisNutrientModel>() }; foreach (var key in NutrientMappings.Keys) { AnalysisNutrientModel newNutrientRecord = CreateAnalysisNutrientRecord(row, newAnalysisModel, key); newAnalysisModel.Nutrients.Add(newNutrientRecord); } GlobalConfig.Connection.CreateAnalysis(newAnalysisModel); IList <object> updateRow = new object[] { newAnalysisModel.Id, }; UpdateValues.Add(updateRow); }
private bool ConfirmPastTrend(AnalysisModel model) { bool isTrending = false; var lastNCandles = model.HeikinAshi.Skip(model.HeikinAshi.Count - SAMPLE_SIZE).Take(SAMPLE_SIZE).ToList(); int upCandlesCount = lastNCandles.Count(c => c.IsGreen); int downCandlesCount = lastNCandles.Count(c => c.IsRed); // 1. If all candles are in same trend. if (upCandlesCount == 0 || downCandlesCount == 0) { return(true); } // 2. decimal max = Math.Max(lastNCandles.Max(c => c.Close), lastNCandles.Max(c => c.Open)); decimal min = Math.Min(lastNCandles.Min(c => c.Close), lastNCandles.Min(c => c.Open)); // 3. Find longest streak int upStreak = GetLongestStreak(lastNCandles, true); int downStreak = GetLongestStreak(lastNCandles, false); if (upStreak.Percentage(lastNCandles.Count) > 70 || downStreak.Percentage(lastNCandles.Count) > 70) { return(true); } return(isTrending); }
public CacheMissAnalyzer(AnalysisInput input) : base(input) { Console.WriteLine("Loaded old graph"); m_model = new AnalysisModel(CachedGraph); m_logPath = input.ExecutionLogPath; }
public ActionResult Analysis() { var model = new AnalysisModel(); model.OriginalIDs = GetValidOriginalIDs(); model.StudySeries = GetStudySeries(model); return(View(model)); }
static void RunMetrics(SyntaxParser parser, AnalysisModel analysisModel, ResultModel result) { MetricInfo metricInfo = MetricInfo.FromParsers(true, parser); if (analysisModel.RunIndicatorMetrics) { foreach (ConstructIndicator indicator in Enum.GetValues(typeof(ConstructIndicator))) { try { MetricResult <bool> metricResult = new MetricResult <bool>(); metricResult.Occurences = metricInfo.GetOccurrences(indicator); metricResult.Result = metricResult.Occurences.Count() > 0; result.IndicatorMetricsResult.Add(indicator, metricResult); } catch (Exception ex) { logger.ErrorException(string.Format("Metrics \"{0}\" failed", indicator), ex); } } } if (analysisModel.RunQuantityMetrics) { foreach (Quantity quantity in Enum.GetValues(typeof(Quantity))) { try { MetricResult <int> metricResult = new MetricResult <int>(); metricResult.Result = metricInfo.GetQuantity(quantity); metricResult.Occurences = metricInfo.GetOccurrences(quantity); result.QuantityMetricsResult.Add(quantity, metricResult); } catch (Exception ex) { logger.ErrorException(string.Format("Metrics \"{0}\" failed", quantity), ex); } } } if (analysisModel.RunRatingMetrics) { foreach (Rating rating in Enum.GetValues(typeof(Rating))) { try { MetricResult <double> metricResult = new MetricResult <double>(); metricResult.Result = metricInfo.GetRating(rating); metricResult.Occurences = metricInfo.GetOccurrences(rating); result.RatingMetricsResult.Add(rating, metricResult); } catch (Exception ex) { logger.ErrorException(string.Format("Metrics \"{0}\" failed", rating), ex); } } } }
private static void UpdateLeadingHeikinAshi(AnalysisModel model) { var currentHeikinAshi = model.HeikinAshi.Last(); var lastIndex = model.HeikinAshi.Select(c => c.Index).OrderBy(item => Math.Abs(currentHeikinAshi.Index - item)).Skip(1).First(); var previousHeikinAshi = model.HeikinAshi.FirstOrDefault(c => c.Index == lastIndex); if (currentHeikinAshi.IsCrossingLeadingCandle(model.LeadingHeikinAshi) && currentHeikinAshi.Body.Percentage(model.AverageHeikinAshiBody) < 400) { model.LeadingHeikinAshi = currentHeikinAshi; } }
/// <summary> /// Initializes a new instance. /// </summary> /// <param name="index">The zero-based index of the worker.</param> /// <param name="context">The context the model is traversed in.</param> /// <param name="stateStack">The state stack that should be used by the worker.</param> /// <param name="model">The model that the worker should analyze.</param> public Worker(int index, TraversalContext context, StateStack stateStack, AnalysisModel model) { Requires.NotNull(context, nameof(context)); Requires.NotNull(stateStack, nameof(stateStack)); Requires.NotNull(model, nameof(model)); _index = index; _context = context; _stateStack = stateStack; Model = model; }
public ActionResult Analysis(AnalysisModel model) { model.OriginalIDs = GetValidOriginalIDs(); if (model.StudySeries == null || model.StudySeries.Count() < 1) { model.StudySeries = GetStudySeries(model); } if (ModelState.IsValid) { } return(View(model)); }
/// <summary> /// Initializes a new instance. /// </summary> /// <param name="index">The zero-based index of the worker.</param> /// <param name="context">The context the model is traversed in.</param> /// <param name="stateStack">The state stack that should be used by the worker.</param> /// <param name="model">The model that the worker should analyze.</param> public Worker(int index, TraversalContext <TExecutableModel> context, StateStack stateStack, AnalysisModel <TExecutableModel> model) { Requires.NotNull(context, nameof(context)); Requires.NotNull(stateStack, nameof(stateStack)); Requires.NotNull(model, nameof(model)); _index = index; _context = context; _stateStack = stateStack; Model = model; }
private static void UpdateLeadingCandle(AnalysisModel model) { var currentCandle = model.Candles.Last(); uint lastIndex = model.Candles.Select(c => c.Index).OrderBy(item => Math.Abs(currentCandle.Index - item)).Skip(1).First(); var previousCandle = model.Candles.FirstOrDefault(c => c.Index == lastIndex); if (currentCandle.IsCrossingLeadingCandle(model.LeadingCandle) && currentCandle.Body.Percentage(model.AverageCandleBody) < 400) { model.LeadingCandle = currentCandle; } }
public void RequiredField_ExpectMissingRequiredField() { // Arrange var controller = GetHomeController(new UrlUtility()); var model = new AnalysisModel { Text = string.Empty }; // Act var result = controller.Index(model) as ActionResult; var results = ValidationHelper.Validate(model); // Assert Assert.IsInstanceOfType(result, typeof(ViewResult)); Assert.AreNotEqual(0, results.Count); }
/// <summary> /// Checks whether the <paramref name="invariant" /> holds in all states of the <paramref name="stateGraph" />. /// </summary> /// <param name="stateGraph">The state graph that should be checked.</param> /// <param name="invariant">The invariant that should be checked.</param> internal InvariantAnalysisResult CheckInvariant(StateGraph <TExecutableModel> stateGraph, Formula invariant) { Requires.NotNull(stateGraph, nameof(stateGraph)); Requires.NotNull(invariant, nameof(invariant)); // We have to track the state vector layout here; this will nondeterministically store some model instance of // one of the workers; but since all state vectors are the same, we don't care AnalysisModel model = null; Func <AnalysisModel> createAnalysisModelFunc = () => model = new StateGraphModel <TExecutableModel>(stateGraph, Configuration.SuccessorCapacity); var createAnalysisModel = new AnalysisModelCreator(createAnalysisModelFunc); using (var checker = new InvariantChecker(createAnalysisModel, Configuration, invariant)) { var result = checker.Check(); return(result); } }
/// <summary> /// /// </summary> /// <param name="model"></param> /// <returns></returns> private async Task ExecuteAnalysis(AnalysisModel model) { var tokenResult = await CotohaApiManager.GetAccessTokenAsync(); if (tokenResult.StatusCode == HttpStatusCode.Created) { model.KeywordResult = await CotohaApiManager.ExtractionKeywordsAsync(new CotohaAPI.Models.KeyWordRequest() { Document = model.Presenter.SpeachText, Type = "kuzure", DoSegment = true, MaxKeywordNum = 10 }); model.KeyPhraseExtractResult = await TextAnalyticsManager.ExecuteJapaneseKeyPhraseExtractAsync(string.Join("。", model.Presenter.SpeachText)); } }
public void TextAnalysis_Success() { // Arrange var controller = GetHomeController(new UrlUtility()); var model = new AnalysisModel { Text = "This is a test." }; // Act var result = controller.Index(model) as ActionResult; var results = ValidationHelper.Validate(model); // Assert Assert.IsInstanceOfType(result, typeof(ViewResult)); var viewResult = result as ViewResult; Assert.AreEqual("Result", viewResult.ViewName); Assert.AreEqual(0, results.Count); }
public async Task <ActionResult> ResultData(TargetEventInfo info) { var rawDataList = DatabaseManager.Executor.GetEventData(info.GroupId, info.EventDate); if (rawDataList.Count() == 0) { return(View("Index")); } AnalysisModel model = new AnalysisModel(); model.Presenter.SpeachText = rawDataList.Where(data => data.info_type == "presentor") .OrderBy(data => data.serial_no) .Select((data) => data.data) .ToList(); await ExecuteAnalysis(model); return(View("Result", model)); }
public void InvalidUrl_ExpectError() { // Arrange var htmlContent = string.Empty; var model = new AnalysisModel { Text = "http://www.invalid.url" }; var mock = new Mock <IUrlUtility>(); mock.Setup(m => m.IsValidUrl(model.Text)).Returns(true); mock.Setup(m => m.TryGetContent(model.Text, out htmlContent)).Returns(false); var controller = GetHomeController(mock.Object); // Act var result = controller.Index(model) as ActionResult; // Assert Assert.IsInstanceOfType(result, typeof(ViewResult)); Assert.IsFalse(controller.ModelState.IsValid); Assert.AreEqual("The Url is invalid.", controller.ModelState[""].Errors[0].ErrorMessage); }
private IEnumerable <SelectListItem> GetStudySeries(AnalysisModel m) { if (m.originalID > 0) { string query_string = "SELECT Series.seriesDescription, Study.studyDate FROM Patient INNER JOIN Study ON Patient.patientID = Study.patientID INNER JOIN Series ON Study.studyID = Series.studyID WHERE Patient.originalID = @p1"; SqlConnection db = new SqlConnection(@"Data Source="",1044;Initial Catalog="";User ID="";Password="""); SqlCommand Command = new SqlCommand(query_string); Command.Connection = db; Command.Parameters.AddWithValue("@p1", m.originalID.ToString()); db.Open(); SqlDataReader reader = Command.ExecuteReader(); AuditController.CreateAuditEntry(Session["userID"].ToString(), Session["username"].ToString(), "Patient", "originalID", "Select"); AuditController.CreateAuditEntry(Session["userID"].ToString(), Session["username"].ToString(), "Study", null, "Select"); AuditController.CreateAuditEntry(Session["userID"].ToString(), Session["username"].ToString(), "Series", null, "Select"); var ss = new List <SelectListItem>(); while (reader.Read()) { ss.Add(new SelectListItem { Value = reader["studyDate"] + " - " + reader["seriesDescription"], Text = reader["studyDate"] + " - " + reader["seriesDescription"] }); } db.Close(); if (ss.Count < 1) { ss.Add(new SelectListItem { Value = "No data", Text = "No data" } ); } return(ss); } return(new List <SelectListItem>()); }
private Signal ShortExit(AnalysisModel model) { Signal signal = new Signal(); var currentHeikinAshi = model.CurrentHeikinAshi; var currentCandle = model.CurrentCandle; var previousHeikinAshi = model.PreviousHeikinAshi; var previousCandle = model.PreviousCandle; if (currentHeikinAshi.IsRed && previousHeikinAshi.IsRed) { if (currentHeikinAshi.Body < previousHeikinAshi.Body && currentHeikinAshi.Close > previousHeikinAshi.Close && currentHeikinAshi.Body < (currentHeikinAshi.UpperWick + currentHeikinAshi.LowerWick) && currentCandle.IsGreen && currentCandle.Close > (previousCandle.IsGreen ? previousCandle.Close : previousCandle.Open)) { signal.SignalType = SignalType.Exit; signal.TradeType = TradeType.Short; signal.Strength = 50; signal.Price = currentHeikinAshi.Close; } } if (currentHeikinAshi.IsGreen && previousHeikinAshi.IsRed) { if (currentHeikinAshi.Close > previousHeikinAshi.Open || currentHeikinAshi.Body < previousHeikinAshi.Body || currentHeikinAshi.IsCrossingLeadingCandle(model.LeadingHeikinAshi)) { signal.SignalType = SignalType.Exit; signal.TradeType = TradeType.Short; signal.Strength = 50; signal.Price = currentHeikinAshi.Close; } } return(signal); }