public ActionResult Recommendation(
            RenderModel model,
            int id,
            string name)
        {
            IPublishedContent recommendationRespository = Helper.TypedContentAtRoot().FirstOrDefault()
                                                          .FirstChild(x => x.DocumentTypeAlias == Constants.NodeAlias.RECOMMENDATIONS_REPOSITORY);

            RecommendationModel recommendationModel = RecommendationFactory.Create(model.Content, recommendationRespository, Services.ContentService, Site.IsEnglish, isDetails: true);

            // make sure the productName for the route matches the encoded product name
            string expectedName = recommendationModel.HeadLine.ToSeoUrl();

            string actualName = (name ?? "").ToLower();

            // permanently redirect to the correct URL
            if (expectedName != actualName)
            {
                return(RedirectToActionPermanent(Constants.Controllers.Recommendation.NAME,
                                                 Constants.Controllers.Recommendation.Actions.RECOMMENDATION,
                                                 new
                {
                    id = recommendationModel.Id,
                    name = expectedName
                }));
            }

            return(CurrentTemplate(recommendationModel));
        }
示例#2
0
        public RecommendationModel GetRecommendations(double userId)
        {
            var model = new RecommendationModel();
            var tasks = new Task[this.WorkerUrls.Count];

            var start = DateTime.Now;

            var userIds = this.DbService.GetRecommendationUsers(userId);
            var part    = userIds.Count / this.WorkerUrls.Count;
            var args    = new string[this.WorkerUrls.Count];

            for (int i = 0; i < this.WorkerUrls.Count; i++)
            {
                if (i == this.WorkerUrls.Count - 1)
                {
                    args[i] = string.Join(",", userIds.Skip(i * part));
                }
                else
                {
                    args[i] = string.Join(",", userIds.Skip(i * part).Take(part));
                }
            }

            var ret   = new IEnumerable <Recommendation> [this.WorkerUrls.Count];
            var index = 0;

            foreach (var worker in this.WorkerUrls)
            {
                var task = Task.Factory.StartNew(() =>
                {
                    var i   = index;
                    var url = worker.ToString() + "/Service/Recommendations?userId=" + userId.ToString();
                    ret[i]  = RequestHelper.Post <Collection <Recommendation> >(url, args[i]);
                });

                Thread.Sleep(100);

                tasks[index++] = task;
            }

            Task.WaitAll(tasks);

            var q = new Collection <Recommendation>();

            foreach (var list in ret)
            {
                foreach (var r in list)
                {
                    if (!q.Any(e => e.MovieId == r.MovieId))
                    {
                        q.Add(r);
                    }
                }
            }

            model.Recommendations = new Collection <Recommendation>(q.Take(25).ToList());
            model.ElapsedTime     = DateTime.Now.Subtract(start).TotalMilliseconds;

            return(model);
        }
        public ActionResult Index()
        {
            var config = WingtipTicketApp.Config.RecommendationSiteUrl;
            var uri    = String.Empty;

            if (!String.IsNullOrEmpty(config))
            {
                var uriBuilder = new UriBuilder(config);

                var user = Session["SessionUser"] as Customer;
                var queryStringBuilder = HttpUtility.ParseQueryString(uriBuilder.Query);

                if (user != null)
                {
                    queryStringBuilder["UserName"] = String.Format("{0} {1}", user.FirstName, user.LastName);
                }

                uriBuilder.Query = queryStringBuilder.ToString();
                uri = uriBuilder.ToString();
            }

            var model = new RecommendationModel(uri);

            return(View(model));
        }
示例#4
0
 public RecommendationBuilder(AppSettings appSettings, IAudioFeatureRepository audioFeatureRepo, QuestionRepository questionRepository)
 {
     _model              = new RecommendationModel();
     _model.Limit        = 20;
     _questionRepository = questionRepository;
     _audioFeatureRepo   = audioFeatureRepo;
     _model.Market       = appSettings.Region;
 }
示例#5
0
        public RecommendationsPageModel(RecommendationModel model)
        {
            if (model == null)
            {
                return;
            }

            Id     = model.Id;
            Text   = model.Text;
            IsTest = model.IsTest;
        }
示例#6
0
        public async Task <ActionResult> Create(RecommendationModel model)
        {
            if (ModelState.IsValid)
            {
                var recommendationModelBuilder = new TrackListModelBuilder(model);
                var recommendedTracks          = await recommendationModelBuilder.BuildAsync();

                return(View("Details", recommendedTracks));
            }
            return(View());
        }
示例#7
0
        public IResponse <RecommendationResponse> GetRecommendation()
        {
            RecommendationModel rq = new RecommendationModel
            {
                ClientType    = "web_site",
                Count         = 4,
                SessionId     = "c9f7f47db1c2d6faf423bd3e9fc4e956",
                SitePageType  = "product_detail",
                siteProductId = "34"
            };

            return(_getRecommendation.GetRecommendations(rq).Result);
        }
        public IActionResult Index()
        {
            var recommendations    = new List <RecommendationModel>();
            var model              = new UserModel(HttpContext.Session.GetInt32("UserId") ?? 0);
            var recommendedCourses = new CourseModel().RecommendedCourses(model);

            if (recommendedCourses == null)
            {
                return(RedirectToAction("SetPreferences", model));
            }
            var uniIds           = new List <int>();
            var usedUniversities = new List <UniversityModel>();

            foreach (var course in recommendedCourses)
            {
                int universityId = Convert.ToInt32(course["universityId"].ToString());
                if (!uniIds.Contains(universityId))
                {
                    uniIds.Add(universityId);
                    usedUniversities.Add(new UniversityModel(universityId));
                }
            }

            foreach (var university in usedUniversities)
            {
                var newUniversityRecommendations = new RecommendationModel();
                newUniversityRecommendations.University = university;
                newUniversityRecommendations.Courses    = new List <CourseModel>();

                foreach (var course in recommendedCourses)
                {
                    var universityId = Convert.ToInt32(course["universityId"].ToString());
                    if (newUniversityRecommendations.University.UniversityId == universityId)
                    {
                        var courseId  = Convert.ToInt32(course["studyProgramId"].ToString());
                        var uniCourse = new CourseModel(courseId);
                        newUniversityRecommendations.Courses.Add(uniCourse);
                    }
                }
                recommendations.Add(newUniversityRecommendations);
            }
            model.Recommendations = recommendations;

            return(View(model));
        }
示例#9
0
        public async Task <IResponse <RecommendationResponse> > GetRecommendations(RecommendationModel query)
        {
            Urls.BaseUrl = "https://feelaplace.infiniteanalytics.com/SocialGenomix";

            IRequestCreateOptions <GetRequestCreateOption> requestCreateOptions = new RequestCreateOptions <GetRequestCreateOption>();
            IHttpResponse httpResponse = await HttpWebRequestProviders <GetRequestCreateOption> .GetWebRequestProviderAsync(string.Format(Urls.InfiniteAnalytics.Recommendation, query.SessionId, query.ClientType, query.SitePageType, query.siteProductId, query.Count), requestCreateOptions).ConfigureAwait(false);

            if (!string.IsNullOrWhiteSpace(httpResponse.Response))
            {
                RecommendationResponse recommendations = Mapper <RecommendationResponse> .MapJsonStringToObject(httpResponse.Response);

                return(GetResponse(true, recommendations));
            }
            else
            {
                _logger.Log(LogCategory.Error, new Exception("Failed to fetch recommendations", httpResponse.WebException));
                return(GetResponse(false, null));
            }
        }
        public string GetRecommendations(RecommendationModel rec)
        {
            var builder = new StringBuilder($"{ApiUrl}/recommendations");

            builder.Append("?limit=" + rec.Limit);

            if (rec.ArtistSeed?.Count > 0)
            {
                builder.Append("&seed_artists=" + string.Join(",", rec.ArtistSeed));
            }

            if (rec.GenreSeed?.Count > 0)
            {
                builder.Append("&seed_genres=" + string.Join(",", rec.GenreSeed));
            }

            if (rec.TrackSeed?.Count > 0)
            {
                builder.Append("&seed_tracks=" + string.Join(",", rec.TrackSeed));
            }

            if (rec.Target != null)
            {
                builder.Append(rec.Target.BuildUrlParams("target"));
            }

            if (rec.Min != null)
            {
                builder.Append(rec.Min.BuildUrlParams("min"));
            }

            if (rec.Max != null)
            {
                builder.Append(rec.Max.BuildUrlParams("max"));
            }

            if (!string.IsNullOrEmpty(rec.Market))
            {
                builder.Append("&market=" + rec.Market);
            }

            return(builder.ToString());
        }
示例#11
0
        /// <summary>
        /// Gets the recommendations.
        /// </summary>
        /// <param name="userId">The user id.</param>
        /// <returns>A recommendations collection model.</returns>
        public RecommendationModel GetRecommendations(double userId)
        {
            var model = new RecommendationModel();

            model.Recommendations = new Collection <Recommendation>();

            var query =
                @"select top 25 movie_id, m.title, AVG(rating) as avgrating, COUNT(rating) as [count]
  from ratings
  inner join movies as m
  on movie_id = m.id
where  [user_id] in (select [user_id] from ratings where [user_id] != @userId and movie_id in (select movie_id from ratings where [user_id] = @userId and rating >= 3) and rating >= 3)
 and movie_id not in (select movie_id from ratings where [user_id] = @userId and rating >= 3)
group by movie_id, title
order by avgrating desc";

            var command = new SqlCommand(query, this.Connection);

            command.Parameters.Add(new SqlParameter("@userId", userId));
            command.CommandTimeout = 600;

            var start = DateTime.Now;

            this.Connection.Open();

            using (var reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    var r = new Recommendation();
                    r.MovieTitle = (string)reader["title"];
                    r.MovieId    = (Int64)reader["movie_id"];
                    r.Stars      = (decimal)reader["avgrating"];
                    r.Count      = (int)reader["count"];
                    model.Recommendations.Add(r);
                }
            }

            model.ElapsedTime = DateTime.Now.Subtract(start).TotalMilliseconds;

            return(model);
        }
        public IActionResult Index()
        {
            if (ModelState.IsValid)
            {
                Display.mine.Recommendations = dataModel.GetRecommendations(Display.mine.MyRecipe);

                // Remove ingredients already in recipe
                foreach (IngredientModel Ingredient in Display.mine.MyRecipe.Ingredients)
                {
                    RecommendationModel toRemove = Display.mine.Recommendations.Where(t => t.Ingredient.Name == Ingredient.Name).FirstOrDefault();
                    Ingredient.Score = toRemove.Score;
                    Display.mine.Recommendations.Remove(toRemove);
                }
                // Sort by Score
                Display.mine.MyRecipe.Ingredients = Display.mine.MyRecipe.Ingredients.OrderByDescending(t => t.Score).ToList();

                return(View(Display));
            }
            else
            {
                return(RedirectToAction("Error"));
            }
        }
示例#13
0
        public async Task <JsonResponse> GetRecommendation([FromBody] RecommendationRequesrModel request)
        {
            try
            {
                List <string>       recommendedCrops = new List <string>();
                RecommendationModel model            = new RecommendationModel();
                string[]            textSplit        = request.district.Split(",");

                model.n        = Convert.ToDecimal(request.n);
                model.p        = Convert.ToDecimal(request.p);
                model.k        = Convert.ToDecimal(request.k);
                model.ph       = Convert.ToDecimal(request.ph);
                model.district = textSplit.FirstOrDefault();
                model.location = textSplit.LastOrDefault();

                var recommendationModel = System.Text.Json.JsonSerializer.Serialize(model);
                var requestContent      = new StringContent(recommendationModel, Encoding.UTF8, "application/json");

                using (var httpClient = new HttpClient())
                {
                    var url = "http://127.0.0.1:5000/api/prediction";
                    using (var response = await httpClient.PostAsync(url, requestContent))
                    {
                        string apiResponse = await response.Content.ReadAsStringAsync();

                        recommendedCrops = JsonConvert.DeserializeObject <List <string> >(apiResponse);
                    }
                }

                return(await _response.JsonResult(true, ResponseType.Success, "Successfully Retrieved district item.", recommendedCrops));
            }
            catch (Exception ex)
            {
                return(await _response.JsonResult(true, ResponseType.Exception, ex.Message, null));
            }
        }
示例#14
0
 public RecommendationModel AddGenres(RecommendationModel model, List <string> genres)
 {
     _model           = model;
     _model.GenreSeed = genres;
     return(_model);
 }
示例#15
0
 public RecommendationModel AddArtists(RecommendationModel model, List <string> artists)
 {
     _model            = model;
     _model.ArtistSeed = artists;
     return(_model);
 }
示例#16
0
        public RecommendationQueryResult Handle(RecommendationQuery query)
        {
            var sessionResponseIA     = _initSession.GetSession().Result;
            RecommendationModel model = new RecommendationModel
            {
                ClientType    = "web_site",
                Count         = 4,
                SessionId     = sessionResponseIA.Result.SessionId,
                SitePageType  = "product_detail",
                siteProductId = query.Id,
            };
            var recommendations     = _getRecommendation.GetRecommendations(model).Result;
            var recomendationResult = AutoMapper.Mapper.Map <List <RecommendationItem> >(recommendations.Result.Data[0].Items);
            var recommendationIds   = recomendationResult.Select(e => e.SiteProductId);

            var siteEvents            = _eventSiteIdMappingRepository.GetBySiteId(query.SiteId).OrderBy(o => o.SortOrder);
            var categoryEvents        = _eventRepository.GetByCategoryId(query.EventCategoryId).Where(e => e.IsEnabled == true);
            var categoryEventsForSite = categoryEvents.Where(ce => recommendationIds.Any(se => se == (ce.Id)));
            var eventIds        = categoryEventsForSite.Select(ce => ce.Id);
            var eventMapping    = _eventRepository.GetByEventIds(eventIds).Where(e => e.IsEnabled == true).ToDictionary(e => e.Id);
            var allEventDetails = _eventDetailRepository.GetByEventIds(eventIds).Where(ed => ed.IsEnabled == true);
            var venueMapping    = _venueRepository.GetByVenueIds(allEventDetails.Select(ed => ed.VenueId).Distinct())
                                  .ToDictionary(v => v.Id);
            var eventDetailsMapping = allEventDetails.GroupBy(ed => ed.EventId)
                                      .ToDictionary(g => g.Key, g => g.ToList());
            var cityIds     = venueMapping.Values.Select(s => s.CityId).Distinct();
            var cityMapping = _cityRepository.GetByCityIds(cityIds)
                              .ToDictionary(c => c.Id);
            var stateId      = cityMapping.Values.Select(c => c.StateId).Distinct();
            var stateMapping = _stateRepository.GetByStateIds(stateId)
                               .ToDictionary(s => s.Id);
            var countryIdList  = stateMapping.Values.Select(s => s.CountryId).Distinct();
            var countryMapping = _countryRepository.GetByCountryIds(countryIdList)
                                 .ToDictionary(c => c.Id);
            var CategoryEventData = categoryEventsForSite.Select(ce =>
            {
                var eventObj                    = eventMapping[ce.Id];
                var eventDetails                = eventDetailsMapping[ce.Id];
                var eventDetailIdList           = eventDetails.Select(s => s.Id).Distinct();
                var venues                      = eventDetails.Select(s => s.VenueId).Distinct().Select(v => venueMapping[v]);
                var cities                      = venues.Select(s => s.CityId).Distinct().Select(c => cityMapping[c]);
                var states                      = cities.Select(s => s.StateId).Distinct().Select(s => stateMapping[s]);
                var countries                   = states.Select(s => s.CountryId).Distinct().Select(c => countryMapping[c]);
                var eventTicketAttributeMapping = new List <Contracts.DataModels.EventTicketAttribute>
                {
                    _eventTicketAttributeRepository.GetMaxPriceByEventDetailId(eventDetailIdList),
                    _eventTicketAttributeRepository.GetMinPriceByEventDetailId(eventDetailIdList)
                };
                var currencyMapping = _currencyTypeRepository.GetByCurrencyId(eventTicketAttributeMapping.First().CurrencyId);
                return(new CategoryEventContainer
                {
                    CategoryEvent = Mapper.Map <Contracts.Models.CategoryEvent>(ce),
                    EventType = eventObj.EventTypeId.ToString(),
                    City = Mapper.Map <IEnumerable <City> >(cities),
                    State = Mapper.Map <IEnumerable <State> >(states),
                    Country = Mapper.Map <IEnumerable <Country> >(countries),
                    Event = Mapper.Map <Event>(eventObj),
                    EventDetail = Mapper.Map <IEnumerable <EventDetail> >(eventDetails),
                    CurrencyType = Mapper.Map <CurrencyType>(currencyMapping),
                    Venue = Mapper.Map <IEnumerable <Venue> >(venues),
                    EventTicketAttribute = Mapper.Map <IEnumerable <EventTicketAttribute> >(eventTicketAttributeMapping),
                });
            });

            return(new RecommendationQueryResult
            {
                CategoryEvents = CategoryEventData.ToList()
            });
        }
示例#17
0
 public TrackListModelBuilder(RecommendationModel recommendationModel)
 {
     _recommendationModel = recommendationModel;
     _client = new SpotifyApiClient();
 }