protected override void OnContentChanged() {
      base.OnContentChanged();
      if (Content != null) {
        var data = Content.Data;
        var filterLogic = new FilterLogic(data);
        var searchLogic = new SearchLogic(data, filterLogic);
        var statisticsLogic = new StatisticsLogic(data, searchLogic);
        var manipulationLogic = new ManipulationLogic(data, searchLogic, statisticsLogic);

        var viewShortcuts = new ItemList<IViewShortcut> {
          new DataGridContent(data, manipulationLogic, filterLogic),
          new StatisticsContent(statisticsLogic),

          new LineChartContent(data),
          new HistogramContent(data),
          new ScatterPlotContent(data),
          new CorrelationMatrixContent(Content),
          new DataCompletenessChartContent(searchLogic),
          
          new FilterContent(filterLogic),
          new ManipulationContent(manipulationLogic, searchLogic, filterLogic),
          new TransformationContent(data, filterLogic)
        };

        viewShortcutListView.Content = viewShortcuts.AsReadOnly();

        viewShortcutListView.ItemsListView.Items[0].Selected = true;
        viewShortcutListView.Select();

      } else {
        viewShortcutListView.Content = null;
      }
    }
        private static Expression <Func <T, bool> > CombineExpressions <T>(IEnumerable <Expression <Func <T, bool> > > expressions, FilterLogic filterLogic)
        {
            if (!(expressions is object) || !expressions.Any())
            {
                return(DefaultExpression <T>());
            }

            Expression <Func <T, bool> > result = null;

            foreach (var expression in expressions)
            {
                if (!(result is object))
                {
                    result = expression;
                    continue;
                }

                switch (filterLogic)
                {
                case FilterLogic.And:
                    result = AndAlso(result, expression);
                    break;

                case FilterLogic.Or:
                    result = OrElse(result, expression);
                    break;

                default:
                    throw new ArgumentException($"Invalid filter logic: {filterLogic}.", nameof(filterLogic));
                }
            }

            return(result ?? DefaultExpression <T>());
        }
        /// <summary>
        /// 指定 IFilter 集合获取 Lambda 表达式
        /// </summary>
        /// <typeparam name="TItem"></typeparam>
        /// <param name="filters"></param>
        /// <param name="logic"></param>
        /// <returns></returns>
        public static Expression <Func <TItem, bool> > GetFilterLambda <TItem>(this IEnumerable <IFilterAction> filters, FilterLogic logic = FilterLogic.And)
        {
            var exps = filters.Select(f => f.GetFilterConditions().GetFilterLambda <TItem>());

            return(exps.ExpressionAndLambda(logic));
        }
        /// <summary>
        /// 表达式取 and 逻辑操作方法
        /// </summary>
        /// <typeparam name="TItem"></typeparam>
        /// <param name="expressions"></param>
        /// <param name="logic"></param>
        /// <returns></returns>
        private static Expression <Func <TItem, bool> > ExpressionAndLambda <TItem>(this IEnumerable <Expression <Func <TItem, bool> > > expressions, FilterLogic logic = FilterLogic.And)
        {
            Expression <Func <TItem, bool> >?ret = null;
            var exp_p   = Expression.Parameter(typeof(TItem));
            var visitor = new ComboExpressionVisitor(exp_p);

            foreach (var exp in expressions)
            {
                if (ret == null)
                {
                    ret = exp;
                    continue;
                }

                var left  = visitor.Visit(ret.Body);
                var right = visitor.Visit(exp.Body);
                ret = logic == FilterLogic.And
                    ? Expression.Lambda <Func <TItem, bool> >(Expression.AndAlso(left, right), exp_p)
                    : Expression.Lambda <Func <TItem, bool> >(Expression.OrElse(left, right), exp_p);
            }
            return(ret ?? (r => true));
        }
Пример #5
0
        private async Task ShowRecommendations(IDialogContext context, IAwaitable <object> result)
        {
            await Interactions.SendMessage(context, "Tenho tantos produtos que sei que poderiam ser do seu interesse. Espere só um momento, vou analisar o nosso catálogo.", 0, 4000);

            List <Product> products = new List <Product>();
            List <Filter>  popular  = RecommendationsLogic.GetPopularFilters(StateHelper.GetFiltersCount(context));

            while (true)
            {
                FilterDefinition <Product> joinedFilters = FilterLogic.GetJoinedFilter(popular);

                //fetch +1 product to see if pagination is needed
                products = ProductController.getProductsFilter(
                    joinedFilters,
                    Constants.N_ITEMS_CARROUSSEL + 1,
                    this.lastFetchId);

                //filters didn't retrieved any products at the first try
                if (products.Count == 0 && lastFetchId == null)
                {
                    popular.RemoveAt(popular.Count - 1);
                }
                else
                {
                    break;
                }
            }

            List <string> currentWishlist = StateHelper.GetWishlistItems(context);

            foreach (string str in currentWishlist)
            {
                ObjectId       obj = new ObjectId(str);
                List <Product> l   = Logic.RecommendationsLogic.GetSimilarProducts(obj);
                products.InsertRange(0, l);
            }

            if (products.Count > Constants.N_ITEMS_CARROUSSEL)
            {
                lastFetchId = products[products.Count - 2].Id;
            }

            var reply = context.MakeMessage();

            reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
            List <Attachment> cards = new List <Attachment>();

            for (int i = 0; i < products.Count && i < Constants.N_ITEMS_CARROUSSEL; i++)
            {
                cards.Add(ProductCard.GetProductCard(products[i], ProductCard.CardType.RECOMMENDATION).ToAttachment());
            }

            await Interactions.SendMessage(context, "Estas são as minhas recomendações:", 0, 2000);

            reply.Attachments = cards;
            await context.PostAsync(reply);

            //Check if pagination is needed
            if (products.Count <= Constants.N_ITEMS_CARROUSSEL)
            {
                context.Done(new CODE(DIALOG_CODE.DONE));
            }
            else
            {
                await Interactions.SendMessage(context, "Ainda tenho mais recomendações para si. Se for do seu interesse não hesite, carregue no botão abaixo.", 2000, 2000);

                reply = context.MakeMessage();

                reply.Attachments.Add(
                    getCardButtonsAttachment(new List <ButtonType> {
                    ButtonType.PAGINATION
                }, DialogType.RECOMMENDATION));
                await context.PostAsync(reply);


                context.Wait(this.InputHandler);
            }
        }
 /// <summary>
 /// 指定 IFilter 集合获取委托
 /// </summary>
 /// <typeparam name="TItem"></typeparam>
 /// <param name="filters"></param>
 /// <param name="logic"></param>
 /// <returns></returns>
 public static Func <TItem, bool> GetFilterFunc <TItem>(this IEnumerable <IFilterAction> filters, FilterLogic logic = FilterLogic.And)
 {
     return(filters.GetFilterLambda <TItem>(logic).Compile());
 }
Пример #7
0
 public Filter(List <IFilter> filters, FilterLogic logic)
 {
     Filters = filters;
     Logic   = logic;
 }
Пример #8
0
 private static DynamicFilterLogic ToDynamicFilterLogic(this FilterLogic logic) => logic switch
 {
Пример #9
0
 public static IFilterRequest ToFilterRequest <T>(this IEnumerable <T> values, string fieldName, FilterOperator filterOperator, FilterLogic filterLogic)
 {
     return(new FilterRequest
     {
         Filters = values.ToFilters(fieldName, filterOperator),
         Logic = filterLogic
     });
 }
Пример #10
0
 public static IQueryable <T1> Filter <T1, T2>(this IQueryable <T1> source, IEnumerable <T2> values, string fieldName, FilterOperator filterOperator, FilterLogic filterLogic)
 {
     return(source.Filter(values.ToFilterRequest(fieldName, filterOperator, filterLogic)));
 }
Пример #11
0
        public void TestTakeTen()
        {
            // Arrange

            // First we have to create an IEnumerable of showings to use in the method that will be tested
            List <Showing> showingslist = new List <Showing> {
                // Put showings in the list with ID's 1 to 11, and check if only 1 to 10 stayed(first 10)
                new Showing {
                    ShowingID = 1
                },
                new Showing {
                    ShowingID = 2
                },
                new Showing {
                    ShowingID = 3
                },
                new Showing {
                    ShowingID = 4
                },
                new Showing {
                    ShowingID = 5
                },
                new Showing {
                    ShowingID = 6
                },
                new Showing {
                    ShowingID = 7
                },
                new Showing {
                    ShowingID = 8
                },
                new Showing {
                    ShowingID = 9
                },
                new Showing {
                    ShowingID = 10
                },
                new Showing {
                    ShowingID = 11
                }
            };

            IEnumerable <Showing> showings = showingslist.ToEnumerable();

            // Act
            List <Showing> resultList     = FilterLogic.TakeTen(showings);
            List <int>     expectedResult = new List <int> {
                1,
                2,
                3,
                4,
                5,
                6,
                7,
                8,
                9,
                10
            };
            List <int> results = new List <int> {
                resultList[0].ShowingID,
                resultList[1].ShowingID,
                resultList[2].ShowingID,
                resultList[3].ShowingID,
                resultList[4].ShowingID,
                resultList[5].ShowingID,
                resultList[6].ShowingID,
                resultList[7].ShowingID,
                resultList[8].ShowingID,
                resultList[9].ShowingID
            };

            // Assert
            Assert.AreEqual(expectedResult[0], results[0]);
            Assert.AreEqual(expectedResult[9], results[9]);
        }
Пример #12
0
        ///<inheritdoc/>
        public override MultiFilter Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            if (reader.TokenType != JsonTokenType.StartObject)
            {
                throw new JsonException("Multifilter json must start with '{'.");
            }

            reader.Read();

            if (reader.TokenType != JsonTokenType.PropertyName || MultiFilter.LogicJsonPropertyName != reader.GetString())
            {
                throw new JsonException($@"Expected ""{MultiFilter.LogicJsonPropertyName}"" property.");
            }

            reader.Read();
            FilterLogic logic = reader.GetString()?.ToLowerInvariant() switch
            {
                "and" => FilterLogic.And,
                "or" => FilterLogic.Or,
                object value => throw new JsonException(@$ "Unexpected " "{value}" " value for " "{MultiFilter.LogicJsonPropertyName}" " property."),
                      null => throw new JsonException(@$ "Unexpected " "null" " value for " "{MultiFilter.LogicJsonPropertyName}" " property.")
            };

            IList <IFilter> filters = new List <IFilter>();

            if (reader.Read() && (reader.TokenType != JsonTokenType.PropertyName || MultiFilter.FiltersJsonPropertyName != reader.GetString()))
            {
                throw new JsonException($@"Expected ""{MultiFilter.FiltersJsonPropertyName}"" property.");
            }

            reader.Read();
            if (reader.TokenType != JsonTokenType.StartArray)
            {
                throw new JsonException(@"Expected ""["".");
            }

            reader.Read();

            // We are about to try parsing the JSON to get either a Filter or a MultiFilter.
            // We store a copy of the original reader in case the parsing process fails.
            Utf8JsonReader readerCopy = reader;

            while (reader.TokenType != JsonTokenType.EndArray)
            {
                long position = reader.TokenStartIndex;
                try
                {
                    filters.Add(_filterConverter.Read(ref reader, typeof(Filter), options));
                }
                catch
                {
                    // The json is not a Filter so we need to go back to where the parsing was performed
                    // and try to get a MultFilter instead

                    // 1. The copyReader position is moved to where the original parser were before failing
                    while (readerCopy.TokenStartIndex < position)
                    {
                        readerCopy.Read();
                    }

                    // 2. Try to parse the Json and get a MultiFilter.
                    filters.Add(Read(ref readerCopy, typeof(MultiFilter), options));
                    // The parsing was a success -> we move the reader to the continue the parsing process

                    while (reader.TokenStartIndex < readerCopy.TokenStartIndex)
                    {
                        reader.Read();
                    }
                    reader.Read(); // Advances the reader until the next token
                }
            }

            reader.Read();
            if (reader.TokenType != JsonTokenType.EndObject)
            {
                throw new JsonException(@"Expected ""}"".");
            }

            return(new MultiFilter
            {
                Logic = logic,
                Filters = filters
            });
        }
Пример #13
0
        public ActionResult GetFilteredFilms()
        {
            CinemaViewModel model = (CinemaViewModel)TempData["model"];

            if (model == null)
            {
                model = new CinemaViewModel();
            }

            // Retrieve the user input
            string dayInput  = Request["searchDay"];  // format: 03-04-2017      (string)
            string timeInput = Request["searchTime"]; // format: 13 14 15 .... (int)

            // Initialize time variable that will be used to work with the user input
            DateTime time;

            // If a day has been entered, put this in time. Else, take the current day.
            if (dayInput != "")
            {
                time = DateTime.ParseExact(dayInput, "dd-MM-yyyy", CultureInfo.InvariantCulture);
            }
            else
            {
                time = DateTime.Now;
            }

            // If a time has been entered, put this in time.
            if (timeInput != "")
            {
                time = time.AddHours(Int32.Parse(timeInput));
            }

            var dayofweek = time.DayOfWeek;

            //First get all showings
            IEnumerable <Showing> allShowings = showingRepo.GetShowings();

            //Filter the list to only contain showings coming after the given time
            IEnumerable <Showing> showingsAfterDate = FilterLogic.GetShowingsAfterDate(allShowings, time);

            //Order the results by date so that the most near one will be shown first
            IEnumerable <Showing> showingsOrdered = FilterLogic.OrderByDate(showingsAfterDate);

            //Filter out showings that are not on the chosen day
            IEnumerable <Showing> todaysShowings = FilterLogic.TodaysShowings(showingsOrdered, time);

            //If the list contains more than 10, take the first 10 showings to show on the page
            List <Showing> allTenShowings = new List <Showing>();

            if (todaysShowings.Count() > 10)
            {
                allTenShowings = FilterLogic.TakeTen(todaysShowings);
            }
            else
            {
                allTenShowings = todaysShowings.ToList();
            }

            //Add the corresponding film to the list of showings,
            //so that the information of the film can be used
            List <Film> allFilms = new List <Film>();

            //Add every film that has been found in the result list of showings
            FilterLogic.AddFilms(allTenShowings, allFilms);

            List <Review> allReviews = reviewRepo.GetReviews().ToList();

            if (time.Day == DateTime.Now.Day)
            {
                ViewBag.selectedDate = Resources.Global.FilterControllerToday;
            }
            else
            {
                ViewBag.selectedDate = FilterLogic.GetDay(time.DayOfWeek) + " " + time.Day + "-" + time.Month;
            }

            ViewBag.reviews         = allReviews;
            ViewBag.selectedTime    = time.ToString("HH:mm");
            ViewBag.numberOfResults = allTenShowings.Count;
            ViewBag.resultShowings  = allTenShowings;
            ViewBag.resultFilms     = allFilms;

            TempData["Model"] = model;
            return(View("FilteredFilms", model));
        }