/// <summary>Read in static rating data from a TextReader</summary>
        /// <param name="reader">the <see cref="TextReader"/> to read from</param>
        /// <param name="size">the number of ratings in the file</param>
        /// <param name="user_mapping">mapping object for user IDs</param>
        /// <param name="item_mapping">mapping object for item IDs</param>
        /// <param name="rating_type">the data type to be used for storing the ratings</param>
        /// <returns>the rating data</returns>
        public static IRatings Read(TextReader reader, int size,
            IEntityMapping user_mapping, IEntityMapping item_mapping,
            RatingType rating_type)
        {
            IRatings ratings;
            if (rating_type == RatingType.BYTE)
                ratings = new StaticByteRatings(size);
            else if (rating_type == RatingType.FLOAT)
                ratings = new StaticFloatRatings(size);
            else
                ratings = new StaticRatings(size);

            var split_chars = new char[]{ '\t', ' ', ',' };
            string line;

            while ( (line = reader.ReadLine()) != null )
            {
                if (line.Length == 0)
                    continue;

                string[] tokens = line.Split(split_chars);

                if (tokens.Length < 3)
                    throw new IOException("Expected at least three columns: " + line);

                int user_id = user_mapping.ToInternalID(int.Parse(tokens[0]));
                int item_id = item_mapping.ToInternalID(int.Parse(tokens[1]));
                double rating = double.Parse(tokens[2], CultureInfo.InvariantCulture);

                ratings.Add(user_id, item_id, rating);
            }
            return ratings;
        }
Beispiel #2
0
        public void WhenValidCodeParam_ThenSetProperties(RatingType type, string code)
        {
            var sut = new Rating(code);

            Assert.That(sut.Type, Is.EqualTo(type));
            Assert.That(sut.Code, Is.EqualTo(code));
        }
Beispiel #3
0
        private List <Series> GetListOf(RatingType ratingType)
        {
            tlPanel.Controls.Clear();
            Dictionary <int, Rating> ratings = dataAccess.GetAllRatings(currentUser.Id);

            currentUser.Ratings = ratings;

            if (ratings != null)
            {
                var filteredList = new List <int>();
                switch (ratingType)
                {
                case RatingType.FAVORITES:
                    filteredList = ratings.Where(x => x.Value.Favorite).Select(x => x.Value.Id_series).ToList();
                    break;

                case RatingType.MARKED:
                    filteredList = ratings.Where(x => x.Value.Marked).Select(x => x.Value.Id_series).ToList();
                    break;

                case RatingType.SEEN:
                    filteredList = ratings.Where(x => x.Value.Seen).Select(x => x.Value.Id_series).ToList();
                    break;

                case RatingType.ALL:
                    filteredList = series.Select(x => x.Id_series).ToList();
                    break;
                }
                return(series.Where(x => filteredList.Contains(x.Id_series)).ToList());
            }

            return(null);
        }
Beispiel #4
0
 protected CASRLicenseBase(string szBaseFAR, string szTitle, RatingType rt, string szCategoryName)
 {
     Title               = szTitle;
     BaseFAR             = szBaseFAR;
     RatingSought        = rt;
     CategoryRestriction = szCategoryName;
 }
        public void AddRating(string userId, RatingType ratingType, Post post)
        {
            var like = _postFactory.CreateLike(post.Id, userId, ratingType);

            post.Likes.Add(like);
            post.Rank = (ratingType == RatingType.Positive) ? ++post.Rank : --post.Rank;
        }
Beispiel #6
0
        public async Task <TvDbResponse <UserRatings[]> > GetRatingsAsync(RatingType type, CancellationToken cancellationToken)
        {
            var request  = new ApiRequest("GET", $"/user/ratings/query?itemType={this.UrlHelpers.QuerifyEnum(type)}");
            var response = await this.ApiClient.SendRequestAsync(request, cancellationToken).ConfigureAwait(false);

            return(this.Parser.Parse <TvDbResponse <UserRatings[]> >(response, ErrorMessages.Users.GetRatingsAsync));
        }
Beispiel #7
0
        //--------------------------------- Constructors -------------------------------------------------
        public CarrierRoute(CarrierRouteRow pCarrierRouteRow)
        {
            carrierRouteRow = pCarrierRouteRow;
            CarrierAcctId   = carrierRouteRow.Carrier_acct_id;

            //-- set name
            RouteRow _routeRow;

            using (var _db = new Rbr_Db()) {
                _routeRow = _db.RouteCollection.GetByPrimaryKey(carrierRouteRow.Route_id);
            }
            Name        = _routeRow == null ? AppConstants.Unknown : _routeRow.Name;
            BaseRouteId = _routeRow == null ? carrierRouteRow.Route_id : _routeRow.Route_id;

            //-- set ratingtype
            CarrierAcctRow _carrierAcctRow;

            using (var _db = new Rbr_Db()) {
                _carrierAcctRow = _db.CarrierAcctCollection.GetByPrimaryKey(carrierAcctId);
            }
            if (_carrierAcctRow == null)
            {
                throw new Exception(string.Format("CarrierRoute.Ctor | CarrierAcctRow NOT FOUND, carrierAcctId:{0}", carrierAcctId));
            }
            ratingType = _carrierAcctRow.RatingType;
        }
Beispiel #8
0
        public RatingType Get(int id)
        {
            RatingType ratingType = TypeRepository.Get(id).Map <RatingType>();

            ratingType.RateChoices = GetRateChoices(id);
            return(ratingType);
        }
Beispiel #9
0
        public async Task RemoveRatingAsync(RatingType itemType, int itemId, CancellationToken cancellationToken)
        {
            var request  = new ApiRequest("DELETE", $"/user/ratings/{this.UrlHelpers.QuerifyEnum(itemType)}/{itemId}");
            var response = await this.ApiClient.SendRequestAsync(request, cancellationToken).ConfigureAwait(false);

            var data = this.Parser.Parse <TvDbResponse <UserRatings[]> >(response, ErrorMessages.Users.RemoveFromFavoritesAsync);
        }
Beispiel #10
0
        protected void LoadAllRatingTypesCompletedHelper()
        {
            try
            {
                dispatcher.BeginInvoke
                    (() =>
                {
                    if (Utility.FaultExist(ratingTypeService.Fault))
                    {
                        return;
                    }

                    if (ratingTypeService.Models != null)
                    {
                        ratingTypeService.Models.Insert(0, new Infrastructure.MangoService.RatingType()
                        {
                            Name = "<< Select Rating Type >>"
                        });

                        RatingTypes = new PagedCollectionView(ratingTypeService.Models);
                        RatingTypes.MoveCurrentToFirst();
                        RatingTypes.CurrentChanged += (s, e) =>
                        {
                            RatingType = RatingTypes.CurrentItem as RatingType;
                        };
                    }
                });
            }
            catch (Exception ex)
            {
                Utility.DisplayMessage(ex.Message);
            }
        }
Beispiel #11
0
        private void button1_Click(object sender, EventArgs e)
        {
            RatingType type = RatingType.ALL;

            if (cb_favorit.Checked)
            {
                type = RatingType.FAVORITES;
            }
            else if (cb_gesehen.Checked)
            {
                type = RatingType.SEEN;
            }
            else if (cb_vermerkt.Checked)
            {
                type = RatingType.MARKED;
            }

            List <string> genres = new List <string>();

            foreach (Control control in fp_genreList.Controls)
            {
                if (control.GetType() == typeof(CheckBox))
                {
                    CheckBox box = (CheckBox)control;
                    if (box.Checked)
                    {
                        genres.Add(box.Text);
                    }
                }
            }
            tlPanel.Controls.Clear();
            LoadSeries(GetListOf(type, genres));
        }
Beispiel #12
0
 protected EASALAPL(RatingType rt, string szBaseFar, string szTitle) : base()
 {
     RatingSought = rt;
     BaseFAR      = szBaseFar;
     Title        = szTitle;
     FARLink      = MilestoneProgress.EASA_PART_FCL_LINK;
 }
Beispiel #13
0
        /// <summary>Read in static rating data from a file</summary>
        /// <param name="filename">the name of the file to read from</param>
        /// <param name="user_mapping">mapping object for user IDs</param>
        /// <param name="item_mapping">mapping object for item IDs</param>
        /// <param name="rating_type">the data type to be used for storing the ratings</param>
        /// <param name="ignore_first_line">if true, ignore the first line</param>
        /// <returns>the rating data</returns>
        public static IRatings Read(
            string filename,
			IEntityMapping user_mapping = null, IEntityMapping item_mapping = null,
			RatingType rating_type = RatingType.FLOAT,
			bool ignore_first_line = false)
        {
            string binary_filename = filename + ".bin.StaticRatings";
            if (FileSerializer.Should(user_mapping, item_mapping) && File.Exists(binary_filename))
                return (IRatings) FileSerializer.Deserialize(binary_filename);

            int size = 0;
            using ( var reader = new StreamReader(filename) )
                while (reader.ReadLine() != null)
                    size++;
            if (ignore_first_line)
                size--;

            return Wrap.FormatException<IRatings>(filename, delegate() {
                using ( var reader = new StreamReader(filename) )
                {
                    var ratings = (StaticRatings) Read(reader, size, user_mapping, item_mapping, rating_type);
                    if (FileSerializer.Should(user_mapping, item_mapping) && FileSerializer.CanWrite(binary_filename))
                        ratings.Serialize(binary_filename);
                    return ratings;
                }
            });
        }
Beispiel #14
0
        /// <summary>
        /// gets rating of transfer between two points
        /// </summary>
        /// <param name="type">rating type</param>
        /// <param name="from">first point</param>
        /// <param name="to">second point</param>
        /// <returns>cost of transfer</returns>
        public float GetRating(RatingType type, Point from, Point to)
        {
            int rating = 1;

            switch (type)
            {
            case RatingType.Hiding:
                //rating /= (height / 10);
                //if (bDanger)
                //    rating /= 10;
                //if (bPlayer)
                //    rating /= 10;
                //if (bBlock)
                //    rating = 999999;
                break;

            case RatingType.Explore:
                //rating += height / 10;
                break;

            case RatingType.Direct:
                break;

            case RatingType.Carefull:
                break;

            default:
                break;
            }
            //rating += 2;
            return(rating);
        }
Beispiel #15
0
        public async Task <RatingsWithUserCount> GetRatings(RatingType type)
        {
            var userId  = this.GetCurrentUserId();
            var ratings = await _ratingService.GetRatings(userId, type);

            return(ratings);
        }
        /// <summary>Read in static rating data from a TextReader</summary>
        /// <param name="reader">the <see cref="TextReader"/> to read from</param>
        /// <param name="size">the number of ratings in the file</param>
        /// <param name="user_mapping">mapping object for user IDs</param>
        /// <param name="item_mapping">mapping object for item IDs</param>
        /// <param name="rating_type">the data type to be used for storing the ratings</param>
        /// <param name="ignore_first_line">if true, ignore the first line</param>
        /// <returns>the rating data</returns>
        static public IRatings Read(
            TextReader reader, int size,
            IMapping user_mapping  = null, IMapping item_mapping = null,
            RatingType rating_type = RatingType.FLOAT,
            bool ignore_first_line = false)
        {
            if (user_mapping == null)
            {
                user_mapping = new IdentityMapping();
            }
            if (item_mapping == null)
            {
                item_mapping = new IdentityMapping();
            }
            if (ignore_first_line)
            {
                reader.ReadLine();
            }

            IRatings ratings;

            if (rating_type == RatingType.BYTE)
            {
                ratings = new StaticByteRatings(size);
            }
            else if (rating_type == RatingType.FLOAT)
            {
                ratings = new StaticRatings(size);
            }
            else
            {
                throw new FormatException(string.Format("Unknown rating type: {0}", rating_type));
            }

            string line;

            while ((line = reader.ReadLine()) != null)
            {
                if (line.Length == 0)
                {
                    continue;
                }

                string[] tokens = line.Split(Constants.SPLIT_CHARS);

                if (tokens.Length < 3)
                {
                    throw new FormatException("Expected at least 3 columns: " + line);
                }

                int   user_id = user_mapping.ToInternalID(tokens[0]);
                int   item_id = item_mapping.ToInternalID(tokens[1]);
                float rating  = float.Parse(tokens[2], CultureInfo.InvariantCulture);

                ratings.Add(user_id, item_id, rating);
            }
            ratings.InitScale();
            return(ratings);
        }
Beispiel #17
0
 internal void RemoveRating(RatingType type)
 {
     if (Ratings.ContainsKey(type))
     {
         Ratings.Remove(type);
         RefreshViewModel();
     }
 }
 public StreamingContent(string name, ContentType content, RatingType rating, double duration, GenreType genre)
 {
     Name          = name;
     TypeOfContent = content;
     TypeOfRating  = rating;
     TypeOfGenre   = genre;
     Duration      = duration;
 }
Beispiel #19
0
 protected ATPCanadaBase(string title, string category, string altcategory, string basefar, RatingType ratingtype)
 {
     Title        = title;
     Category     = category;
     AltCategory  = altcategory;
     BaseFAR      = basefar;
     RatingSought = ratingtype;
 }
Beispiel #20
0
 protected CASRLicenseBase(string szBaseFAR, string szTitle, RatingType rt, string szCategoryName)
 {
     Title               = szTitle;
     BaseFAR             = szBaseFAR;
     RatingSought        = rt;
     CategoryRestriction = szCategoryName;
     FARLink             = "https://www.legislation.gov.au/Details/F2015C00762/Html/Volume_2";
 }
Beispiel #21
0
        protected CFIBase(string title, CategoryClass.CatClassID ccid, RatingType rt)
        {
            Title = title;
            requiredCatClassID = ccid;
            BaseFAR            = "61.183";
            RatingSought       = rt;

            miPIC = new MilestoneItem(String.Format(CultureInfo.CurrentCulture, Resources.MilestoneProgress.CFITimeInCategoryClass, CFIMinTime, CategoryClass.CategoryClassFromID(ccid).CatClass), ResolvedFAR("(j)"), string.Empty, MilestoneItem.MilestoneType.Time, CFIMinTime);
        }
 // ReSharper disable once InconsistentNaming
 public Task AddRatingAsync_Makes_The_Right_Request(RatingType itemType, int itemId, decimal rating)
 {
     return(CreateClient()
            .WithErrorMap(ErrorMessages.Users.RateAsync)
            .SetResultObject(new TvDbResponse <UserRatings[]>())
            .WhenCallingAMethod((impl, token) => impl.AddRatingAsync(itemType, itemId, rating, token))
            .ShouldRequest("PUT", $"/user/ratings/{this.UrlHelpers.QuerifyEnum(itemType)}/{itemId}/{rating}")
            .RunAsync());
 }
        protected IFR141Base(string szTitle, string szBaseFAR, RatingType ratingSought)
        {
            Init(szTitle, szBaseFAR, ratingSought);

            miIMCAircraftTime = new MilestoneItem(Resources.MilestoneProgress.MinInstrumentTime141, ResolvedFAR("(a)(1)"), Resources.MilestoneProgress.Note141InstrumentReducedHours, MilestoneItem.MilestoneType.Time, totalIMCTime);
            miIMCFSTime       = new MilestoneItem(Resources.MilestoneProgress.MinInstrumentTime141, ResolvedFAR("(b)(1)"), Resources.MilestoneProgress.Note141InstrumentReducedHours, MilestoneItem.MilestoneType.Time, maxIMCFSTime);
            miIMCFTDTime      = new MilestoneItem(Resources.MilestoneProgress.MinInstrumentTime141, ResolvedFAR("(b)(2)"), Resources.MilestoneProgress.Note141InstrumentReducedHours, MilestoneItem.MilestoneType.Time, maxIMCFTDTime);
            miIMCATDTime      = new MilestoneItem(Resources.MilestoneProgress.MinInstrumentTime141, ResolvedFAR("(b)(3)"), Resources.MilestoneProgress.Note141InstrumentReducedHours, MilestoneItem.MilestoneType.Time, maxIMCATDTime);
        }
Beispiel #24
0
        public Like CreateLike(int PostId, string UserId, RatingType rank)
        {
            var model = new Like()
            {
                PostId = PostId, UserID = UserId, RatingType = rank
            };

            return(model);
        }
Beispiel #25
0
 public static Videa.CuratedRatingNS.Data.DataServices.RatingType ToEntity(this RatingType source)
 {
     return(new Videa.CuratedRatingNS.Data.DataServices.RatingType
     {
         RatingTypeId = source.RatingTypeId,
         RatingTypeName = source.RatingTypeName,
         RatingTypeDescription = source.RatingTypeDescription
     });
 }
 // ReSharper disable once InconsistentNaming
 public Task GetRatingsAsync_Makes_The_Right_Request(RatingType type)
 {
     return(CreateClient()
            .WithErrorMap(ErrorMessages.Users.GetRatingsAsync)
            .SetResultObject(new TvDbResponse <UserRatings[]>())
            .WhenCallingAMethod((impl, token) => impl.GetRatingsAsync(type, token))
            .ShouldRequest("GET", $"/user/ratings/query?itemType={this.UrlHelpers.QuerifyEnum(type)}")
            .RunAsync());
 }
 public async Task <TVDBResponse <List <UserRatings> > > AddRatingAsync(
     RatingType itemType,
     int itemId,
     decimal rating,
     CancellationToken cancellationToken = default)
 {
     return(await PutJsonAsync <TVDBResponse <List <UserRatings> > >($"/user/ratings/{itemType.ToPascalCase()}/{itemId}/{rating}", cancellationToken)
            .ConfigureAwait(false));
 }
Beispiel #28
0
        protected CASRLicenseBase(string szBaseFAR, string szTitle, RatingType rt, string szCategoryName)
        {
            Title               = szTitle;
            BaseFAR             = szBaseFAR;
            RatingSought        = rt;
            CategoryRestriction = szCategoryName;

            m_milestones = new Collection <MilestoneItem>();
        }
Beispiel #29
0
 public RatingType Update(RatingType ratingType)
 {
     TypeRepository.Update(ratingType.Map <DbRatingType>());
     foreach (RateChoice choice in ratingType.RateChoices)
     {
         UpdateChoice(choice);
     }
     return(Get(ratingType.Id));
 }
Beispiel #30
0
        private List <Series> GetListOf(RatingType ratingType, List <string> genres)
        {
            tlPanel.Controls.Clear();
            Dictionary <int, Rating> ratings = dataAccess.GetAllRatings(currentUser.Id);

            currentUser.Ratings = ratings;
            List <Series> resutlSeries = new List <Series>();

            if (ratings != null)
            {
                var filteredList = new List <int>();
                switch (ratingType)
                {
                case RatingType.FAVORITES:
                    filteredList = ratings.Where(x => x.Value.Favorite).Select(x => x.Value.Id_series).ToList();
                    break;

                case RatingType.MARKED:
                    filteredList = ratings.Where(x => x.Value.Marked).Select(x => x.Value.Id_series).ToList();
                    break;

                case RatingType.SEEN:
                    filteredList = ratings.Where(x => x.Value.Seen).Select(x => x.Value.Id_series).ToList();
                    break;

                case RatingType.ALL:
                    filteredList = series.Select(x => x.Id_series).ToList();
                    break;
                }
                List <Series> filteredSeries = series.Where(x => filteredList.Contains(x.Id_series)).ToList();
                if (genres.Count > 0)
                {
                    foreach (Series serie in filteredSeries)
                    {
                        int bananenBrot = 0;
                        foreach (Genre genre in serie.Genres)
                        {
                            if (genres.Contains(genre.Description))
                            {
                                bananenBrot++;
                            }
                        }
                        if (bananenBrot == genres.Count)
                        {
                            resutlSeries.Add(serie);
                        }
                    }
                }
                else
                {
                    resutlSeries = filteredSeries;
                }
            }

            return(resutlSeries);
        }
Beispiel #31
0
        private ActionResult Rate(int?id, RatingType type)
        {
            using (var cx = new ViralContext())
            {
                var existingRating = cx.Ratings.SingleOrDefault(r => r.User.Id == CurrentUserId && r.Comment.Id == id);
                if (existingRating != null)
                {
                    existingRating.RatedTime = DateTime.UtcNow;
                    existingRating.Type      = type;

                    cx.Entry(existingRating).State = EntityState.Modified;
                }
                else
                {
                    var comment = cx.Comments
                                  .Where(p => p.Id == id)
                                  .Include(p => p.Ratings)
                                  .SingleOrDefault();

                    if (comment == null)
                    {
                        return(RedirectToAction("Index", "Home"));
                    }

                    var user = cx.Users
                               .Where(u => u.Id == CurrentUserId)
                               .Include(u => u.Ratings)
                               .Single();

                    var rating = new Rating
                    {
                        RatedTime = DateTime.UtcNow,
                        Type      = type
                    };

                    if (user.Ratings == null)
                    {
                        user.Ratings = new List <Rating>();
                    }
                    user.Ratings.Add(rating);

                    if (comment.Ratings == null)
                    {
                        comment.Ratings = new List <Rating>();
                    }
                    comment.Ratings.Add(rating);

                    cx.Entry(user).State    = EntityState.Modified;
                    cx.Entry(comment).State = EntityState.Modified;
                }

                cx.SaveChanges();

                return(RedirectToAction("Index", "Home"));
            }
        }
        protected IFR141Base(string szTitle, string szBaseFAR, RatingType ratingSought, int minXCDistance = 250)
        {
            MinXCDistance = minXCDistance;
            Init(szTitle, szBaseFAR, ratingSought, "https://www.law.cornell.edu/cfr/text/14/appendix-C_to_part_141");

            miIMCAircraftTime = new MilestoneItem(Resources.MilestoneProgress.MinInstrumentTime141, ResolvedFAR("(a)(1)"), Resources.MilestoneProgress.Note141InstrumentReducedHours, MilestoneItem.MilestoneType.Time, totalIMCTime);
            miIMCFSTime       = new MilestoneItem(Resources.MilestoneProgress.MinInstrumentTime141, ResolvedFAR("(b)(1)"), Resources.MilestoneProgress.Note141InstrumentReducedHours, MilestoneItem.MilestoneType.Time, maxIMCFSTime);
            miIMCFTDTime      = new MilestoneItem(Resources.MilestoneProgress.MinInstrumentTime141, ResolvedFAR("(b)(2)"), Resources.MilestoneProgress.Note141InstrumentReducedHours, MilestoneItem.MilestoneType.Time, maxIMCFTDTime);
            miIMCATDTime      = new MilestoneItem(Resources.MilestoneProgress.MinInstrumentTime141, ResolvedFAR("(b)(3)"), Resources.MilestoneProgress.Note141InstrumentReducedHours, MilestoneItem.MilestoneType.Time, maxIMCATDTime);
        }
Beispiel #33
0
		/// <summary>
		/// This constructor is used when we just what non-violated named condition
		/// </summary>
		public Condition(string name)
		{
			if (name == null)
			{
				System.Diagnostics.Trace.WriteLine( Workshare.Reports.Properties.Resources.TRACE_NULL, "Condition Constructor 1" );
				throw ( new ArgumentNullException( "name", Workshare.Reports.Properties.Resources.TRACE_NULL ) );
			}
			m_name = name;
			m_rating = RatingType.None;
            m_fails = new FailureCollection();
		}
Beispiel #34
0
 /// <summary>
 /// Initializes a new instance of the <see cref="FeedbackItem"/> class.
 /// </summary>
 /// <param name="applicationId">The application id.</param>
 /// <param name="screenName">Name of the screen.</param>
 /// <param name="message">The message.</param>
 /// <param name="ratingType">Type of the rating.</param>
 /// <param name="sessionId">The session id.</param>
 /// <param name="version">The version.</param>
 public FeedbackItem(Guid applicationId, 
     String screenName, String message, RatingType ratingType, Guid sessionId, String version)
 {
     this.ApplicationId = applicationId;
     this.Version = version;
     this.ScreenName = screenName;
     this.Message = message;
     this.Rating = ratingType;
     this.DateCreated = DateTime.Now;
     this.SessionId = sessionId;
 }
        /// <summary>Read in static rating data from a file</summary>
        /// <param name="filename">the name of the file to read from, "-" if STDIN</param>
        /// <param name="user_mapping">mapping object for user IDs</param>
        /// <param name="item_mapping">mapping object for item IDs</param>
        /// <param name="rating_type">the data type to be used for storing the ratings</param>
        /// <returns>the rating data</returns>
        public static IRatings Read(string filename,
            IEntityMapping user_mapping, IEntityMapping item_mapping,
            RatingType rating_type)
        {
            int size = 0;
            using ( var reader = new StreamReader(filename) )
                while (reader.ReadLine() != null)
                    size++;

            using ( var reader = new StreamReader(filename) )
                return Read(reader, size, user_mapping, item_mapping, rating_type);
        }
Beispiel #36
0
        // http://stackoverflow.com/q/424366
        /// <summary>
        /// Gets the link to avatar by gravatar.
        /// </summary>
        /// <param name="content">The content (email).</param>
        /// <param name="size">The size of avatar.</param>
        /// <param name="ratingType">Type of the rating.</param>
        /// <param name="defaultImage">The type of default image.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException">content</exception>
        /// <exception cref="System.ArgumentOutOfRangeException">size;The image size should be between 1 and 2048</exception>
        public static string Get(string content, int size = 80, RatingType ratingType = RatingType.PG, DefaultImage defaultImage = DefaultImage.MM)
        {
            if (content == null) throw new ArgumentNullException("content");

            if (size < 1 | size > 2048)
                throw new ArgumentOutOfRangeException("size",
                    "The image size should be between 1 and 2048");

            return String.Format("{0}?gravatar_id={1}&s={2}&r={3}&d={4}",
                Url,
                MD5.GetHashString(content.ToLower()),
                size,
                ratingType.ToString("G"),
                defaultImage.ToString("G")).ToLower();
        }
        /// <summary>Read in static rating data from a TextReader</summary>
        /// <param name="reader">the <see cref="TextReader"/> to read from</param>
        /// <param name="size">the number of ratings in the file</param>
        /// <param name="user_mapping">mapping object for user IDs</param>
        /// <param name="item_mapping">mapping object for item IDs</param>
        /// <param name="rating_type">the data type to be used for storing the ratings</param>
        /// <param name="test_rating_format">whether there is a rating column in each line or not</param>
        /// <param name="ignore_first_line">if true, ignore the first line</param>
        /// <returns>the rating data</returns>
        public static IRatings Read(
			TextReader reader, int size,
			IMapping user_mapping = null, IMapping item_mapping = null,
			RatingType rating_type = RatingType.FLOAT,
			TestRatingFileFormat test_rating_format = TestRatingFileFormat.WITH_RATINGS,
			bool ignore_first_line = false)
        {
            if (user_mapping == null)
                user_mapping = new IdentityMapping();
            if (item_mapping == null)
                item_mapping = new IdentityMapping();
            if (ignore_first_line)
                reader.ReadLine();

            IRatings ratings;
            if (rating_type == RatingType.BYTE)
                ratings = new StaticByteRatings(size);
            else if (rating_type == RatingType.FLOAT)
                ratings = new StaticRatings(size);
            else
                throw new FormatException(string.Format("Unknown rating type: {0}", rating_type));

            string line;
            while ((line = reader.ReadLine()) != null)
            {
                if (line.Length == 0)
                    continue;

                string[] tokens = line.Split(Constants.SPLIT_CHARS);

                if (test_rating_format == TestRatingFileFormat.WITH_RATINGS && tokens.Length < 3)
                    throw new FormatException("Expected at least 3 columns: " + line);
                if (test_rating_format == TestRatingFileFormat.WITHOUT_RATINGS && tokens.Length < 2)
                    throw new FormatException("Expected at least 2 columns: " + line);

                int user_id = user_mapping.ToInternalID(tokens[0]);
                int item_id = item_mapping.ToInternalID(tokens[1]);
                float rating = test_rating_format == TestRatingFileFormat.WITH_RATINGS ? float.Parse(tokens[2], CultureInfo.InvariantCulture) : 0;

                ratings.Add(user_id, item_id, rating);
            }
            ratings.InitScale();
            return ratings;
        }
        private ExperienceRating(Guid id, ExperienceArea experienceArea, RatingType type, int rating, IClock clock)
        {
            Id = id;
            ExperienceArea = experienceArea;
            Type = type;
            if (rating > 5 || rating < 0)
            {
                throw new InvalidDataException("A rating must be between 0 and 5");
            }
            Status = type == RatingType.Peer ? RatingStatus.Submitted : RatingStatus.Approved;

            if (type == RatingType.Self)
            {
                SelfRating = rating;
                PeerRating = 0;
                TimeOfSelfRating = clock.UtcNow;
            }
            else
            {
                PeerRating = rating;
                SelfRating = 0;
                TimeOfPeerRating = clock.UtcNow;
            }
        }
Beispiel #39
0
        /// <summary>
        /// グループ情報を更新します。
        /// </summary>
        /// <param name="gid"></param>
        /// <param name="groupname"></param>
        /// <param name="keyword"></param>
        /// <param name="groupRating"></param>
        public void UpdateGroup(long gid, string groupname, string keyword, RatingType groupRating)
        {
            GroupId = gid;
            GroupName = groupname;
            GroupKeyword = keyword;
            Rating = groupRating;

            // グループ名を使用したタイトルに変更する。
            MovieTitle = MovieTitle.Replace(keyword, groupname);
        }
Beispiel #40
0
        public void ModifyRating(GroupItem group, RatingType rating)
        {

            using (var tran = _databaseAccessor.BeginTransaction())
            {
                var ids = _databaseAccessor.SelectIdFromGid(group.Gid);
                foreach (var id in ids)
                {
                    _databaseAccessor.UpdateLibraryRating(id, rating);
                }
                tran.Commit();
            }

            group.ModifyIsFavorite(rating == RatingType.Favorite);
        }
Beispiel #41
0
 public void ModifyRating(RatingType newRating)
 {
     Rating = newRating;
 }
    static void Main(string[] args)
    {
        AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(Handlers.UnhandledExceptionHandler);
        Console.CancelKeyPress += new ConsoleCancelEventHandler(AbortHandler);

        // recommender arguments
        string method              = null;
        string recommender_options = string.Empty;

        // help/version
        bool show_help    = false;
        bool show_version = false;

        // arguments for iteration search
        int max_iter   = 100;
        string measure = "RMSE";
        double epsilon = 0;
        double cutoff  = double.MaxValue;

        // other arguments
        bool search_hp             = false;
        int random_seed            = -1;
        string prediction_line     = "{0}\t{1}\t{2}";
        string prediction_header   = null;

        var p = new OptionSet() {
            // string-valued options
            { "training-file=",       v              => training_file        = v },
            { "test-file=",           v              => test_file            = v },
            { "recommender=",         v              => method               = v },
            { "recommender-options=", v              => recommender_options += " " + v },
            { "data-dir=",            v              => data_dir             = v },
            { "user-attributes=",     v              => user_attributes_file = v },
            { "item-attributes=",     v              => item_attributes_file = v },
            { "user-relations=",      v              => user_relations_file  = v },
            { "item-relations=",      v              => item_relations_file  = v },
            { "save-model=",          v              => save_model_file      = v },
            { "load-model=",          v              => load_model_file      = v },
            { "save-user-mapping=",   v              => save_user_mapping_file = v },
            { "save-item-mapping=",   v              => save_item_mapping_file = v },
            { "load-user-mapping=",   v              => load_user_mapping_file = v },
            { "load-item-mapping=",   v              => load_item_mapping_file = v },
            { "prediction-file=",     v              => prediction_file      = v },
            { "prediction-line=",     v              => prediction_line      = v },
            { "prediction-header=",   v              => prediction_header    = v },
            { "chronological-split=", v              => chronological_split  = v },
            { "measure=",             v              => measure              = v },
            // integer-valued options
            { "find-iter=",           (int v)        => find_iter            = v },
            { "max-iter=",            (int v)        => max_iter             = v },
            { "random-seed=",         (int v)        => random_seed          = v },
            { "cross-validation=",    (uint v)       => cross_validation     = v },
            // double-valued options
            { "epsilon=",             (double v)     => epsilon              = v },
            { "cutoff=",              (double v)     => cutoff               = v },
            { "test-ratio=",          (double v)     => test_ratio           = v },
            // enum options
            { "rating-type=",         (RatingType v) => rating_type          = v },
            { "file-format=",         (RatingFileFormat v) => file_format    = v },
            // boolean options
            { "compute-fit",          v => compute_fit       = v != null },
            { "online-evaluation",    v => online_eval       = v != null },
            { "show-fold-results",    v => show_fold_results = v != null },
            { "search-hp",            v => search_hp         = v != null },
            { "no-id-mapping",        v => no_id_mapping     = v != null },
            { "help",                 v => show_help         = v != null },
            { "version",              v => show_version      = v != null },
        };
        IList<string> extra_args = p.Parse(args);

        // ... some more command line parameter actions ...
        bool no_eval = true;
        if (test_ratio > 0 || test_file != null || chronological_split != null)
            no_eval = false;

        if (show_version)
            ShowVersion();
        if (show_help)
            Usage(0);

        if (random_seed != -1)
            MyMediaLite.Util.Random.Seed = random_seed;

        // set up recommender
        if (load_model_file != null)
            recommender = (RatingPredictor) Model.Load(load_model_file);
        else if (method != null)
            recommender = Recommender.CreateRatingPredictor(method);
        else
            recommender = Recommender.CreateRatingPredictor("BiasedMatrixFactorization");
        // in case something went wrong ...
        if (recommender == null && method != null)
            Usage(string.Format("Unknown rating prediction method: '{0}'", method));
        if (recommender == null && load_model_file != null)
            Abort(string.Format("Could not load model from file {0}.", load_model_file));

        CheckParameters(extra_args);

        recommender.Configure(recommender_options, (string m) => { Console.Error.WriteLine(m); Environment.Exit(-1); });

        // ID mapping objects
        if (file_format == RatingFileFormat.KDDCUP_2011 || no_id_mapping)
        {
            user_mapping = new IdentityMapping();
            item_mapping = new IdentityMapping();
        }
        if (load_user_mapping_file != null)
            user_mapping = EntityMappingExtensions.LoadMapping(load_user_mapping_file);
        if (load_item_mapping_file != null)
            item_mapping = EntityMappingExtensions.LoadMapping(load_item_mapping_file);

        // load all the data
        LoadData(!online_eval);

        // if requested, save ID mappings
        if (save_user_mapping_file != null)
            user_mapping.SaveMapping(save_user_mapping_file);
        if (save_item_mapping_file != null)
            item_mapping.SaveMapping(save_item_mapping_file);

        Console.Error.WriteLine(string.Format(CultureInfo.InvariantCulture, "ratings range: [{0}, {1}]", recommender.MinRating, recommender.MaxRating));

        if (test_ratio > 0)
        {
            var split = new RatingsSimpleSplit(training_data, test_ratio);
            recommender.Ratings = training_data = split.Train[0];
            test_data = split.Test[0];
            Console.Error.WriteLine(string.Format( CultureInfo.InvariantCulture, "test ratio {0}", test_ratio));
        }
        if (chronological_split != null)
        {
            var split = chronological_split_ratio != -1
                            ? new RatingsChronologicalSplit((ITimedRatings) training_data, chronological_split_ratio)
                            : new RatingsChronologicalSplit((ITimedRatings) training_data, chronological_split_time);
            recommender.Ratings = training_data = split.Train[0];
            test_data = split.Test[0];
            if (test_ratio != -1)
                Console.Error.WriteLine(string.Format(CultureInfo.InvariantCulture, "test ratio (chronological) {0}", chronological_split_ratio));
            else
                Console.Error.WriteLine(string.Format(CultureInfo.InvariantCulture, "split time {0}", chronological_split_time));
        }

        Console.Write(training_data.Statistics(test_data, user_attributes, item_attributes));

        if (find_iter != 0)
        {
            if ( !(recommender is IIterativeModel) )
                Abort("Only iterative recommenders (interface IIterativeModel) support --find-iter=N.");

            Console.WriteLine(recommender.ToString());

            if (cross_validation > 1)
            {
                recommender.DoIterativeCrossValidation(cross_validation, max_iter, find_iter);
            }
            else
            {
                var iterative_recommender = (IIterativeModel) recommender;
                var eval_stats = new List<double>();

                if (load_model_file == null)
                    recommender.Train();

                if (compute_fit)
                    Console.WriteLine("fit {0} iteration {1}", recommender.Evaluate(training_data), iterative_recommender.NumIter);

                Console.WriteLine("{0} iteration {1}", recommender.Evaluate(test_data), iterative_recommender.NumIter);

                for (int it = (int) iterative_recommender.NumIter + 1; it <= max_iter; it++)
                {
                    TimeSpan time = Wrap.MeasureTime(delegate() {
                        iterative_recommender.Iterate();
                    });
                    training_time_stats.Add(time.TotalSeconds);

                    if (it % find_iter == 0)
                    {
                        if (compute_fit)
                        {
                            time = Wrap.MeasureTime(delegate() {
                                Console.WriteLine("fit {0} iteration {1}", recommender.Evaluate(training_data), it);
                            });
                            fit_time_stats.Add(time.TotalSeconds);
                        }

                        RatingPredictionEvaluationResults results = null;
                        time = Wrap.MeasureTime(delegate() { results = recommender.Evaluate(test_data); });
                        eval_time_stats.Add(time.TotalSeconds);
                        eval_stats.Add(results[measure]);
                        Console.WriteLine("{0} iteration {1}", results, it);

                        Model.Save(recommender, save_model_file, it);
                        if (prediction_file != null)
                            recommender.WritePredictions(test_data, prediction_file + "-it-" + it, user_mapping, item_mapping, prediction_line, prediction_header);

                        if (epsilon > 0.0 && results[measure] - eval_stats.Min() > epsilon)
                        {
                            Console.Error.WriteLine(string.Format(CultureInfo.InvariantCulture, "{0} >> {1}", results["RMSE"], eval_stats.Min()));
                            Console.Error.WriteLine("Reached convergence on training/validation data after {0} iterations.", it);
                            break;
                        }
                        if (results[measure] > cutoff)
                        {
                            Console.Error.WriteLine("Reached cutoff after {0} iterations.", it);
                            break;
                        }
                    }
                } // for
            }
        }
        else
        {
            TimeSpan seconds;

            Console.Write(recommender + " ");

            if (load_model_file == null)
            {
                if (cross_validation > 1)
                {
                    Console.WriteLine();
                    var results = recommender.DoCrossValidation(cross_validation, compute_fit, show_fold_results);
                    Console.Write(results);
                    no_eval = true;
                }
                else
                {
                    if (search_hp)
                    {
                        double result = NelderMead.FindMinimum("RMSE", recommender);
                        Console.Error.WriteLine("estimated quality (on split) {0}", result.ToString(CultureInfo.InvariantCulture));
                    }

                    seconds = Wrap.MeasureTime( delegate() { recommender.Train(); } );
                    Console.Write(" training_time " + seconds + " ");
                }
            }

            if (!no_eval)
            {
                if (online_eval)
                    seconds = Wrap.MeasureTime(delegate() { Console.Write(recommender.EvaluateOnline(test_data)); });
                else
                    seconds = Wrap.MeasureTime(delegate() { Console.Write(recommender.Evaluate(test_data)); });

                Console.Write(" testing_time " + seconds);

                if (compute_fit)
                {
                    Console.Write("\nfit ");
                    seconds = Wrap.MeasureTime(delegate() {
                        Console.Write(recommender.Evaluate(training_data));
                    });
                    Console.Write(" fit_time " + seconds);
                }

                if (prediction_file != null)
                {
                    Console.WriteLine();
                    seconds = Wrap.MeasureTime(delegate() {
                        recommender.WritePredictions(test_data, prediction_file, user_mapping, item_mapping, prediction_line, prediction_header);
                    });
                    Console.Error.Write("prediction_time " + seconds);
                }
            }

            Console.WriteLine();
        }
        Model.Save(recommender, save_model_file);
        DisplayStats();
    }
 /// <summary>
 /// This constructor will assign the item
 /// </summary>
 /// <param name="item">The message added</param>
 public ScanAuditEventArgs(string text, RatingType rating)
 {
     m_text = text;
     m_type = rating;
 }
 public static ExperienceRating Create(Guid id, ExperienceArea experienceArea, RatingType type, int rating, IClock clock)
 {
     return new ExperienceRating(id, experienceArea, type, rating, clock);
 }
Beispiel #45
0
    static public bool SubmitRating(RatingType type, string itemId, int rating)
    {
        string account = DBOption.GetOptions(DBOption.cOnlineUserID);
        if (String.IsNullOrEmpty(account))
        {
            string[] lines = new string[] { Translation.TVDB_INFO_ACCOUNTID_1, Translation.TVDB_INFO_ACCOUNTID_2 };
            //TVSeriesPlugin.ShowDialogOk(Translation.TVDB_INFO_TITLE, lines); //trakt.tv also listens to this, also can store ratings locally.
            MPTVSeriesLog.Write("Cannot submit rating to thetvdb.com, this requires your Account Identifier to be set.");
            return false;
        }

        if (itemId == "0" || rating < 0 || rating > 10)
        {
            MPTVSeriesLog.Write("Cannot submit rating, invalid values...this is most likely a programming error");
            return false;
        }

        if (!DBOnlineMirror.IsMirrorsAvailable)
        {
            // Server maybe available now.
            DBOnlineMirror.Init();
            if (!DBOnlineMirror.IsMirrorsAvailable)
            {
                GUIDialogOK dlgOK = (GUIDialogOK)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_OK);
                dlgOK.SetHeading(Translation.TVDB_ERROR_TITLE);
                if (!TVSeriesPlugin.IsNetworkAvailable)
                {
                    string[] lines = new string[] { Translation.NETWORK_ERROR_UNAVAILABLE_1, Translation.NETWORK_ERROR_UNAVAILABLE_2 };
                    TVSeriesPlugin.ShowDialogOk(Translation.TVDB_ERROR_TITLE, lines);
                }
                else
                {
                    string[] lines = new string[] { Translation.TVDB_ERROR_UNAVAILABLE_1, Translation.TVDB_ERROR_UNAVAILABLE_2 };
                    TVSeriesPlugin.ShowDialogOk(Translation.TVDB_ERROR_TITLE, lines);
                }
                
                MPTVSeriesLog.Write("Cannot submit rating, the online database is unavailable");
                return false;
            }
        }
        // ok we're good
        MPTVSeriesLog.Write(string.Format("Submitting Rating of {2} for {0} {1}", type.ToString(), itemId, rating), MPTVSeriesLog.LogLevel.Debug);
        Generic(string.Format(apiURIs.SubmitRating, account, type.ToString(), itemId, rating), true, false, Format.NoExtension);
        return true;
    }
Beispiel #46
0
        protected static void SetItemColour( ListViewItem item, bool isExternal, RatingType rating )
		{
			if (isExternal)
			{
				// Now work out the colour of the item
				//item.UseItemStyleForSubItems = true;
				// Important note - Make sure that the colours are set after assigning
				// sub items or else the sub items will overwrite the settings!!!
				item.BackColor = Settings.ExternalEmailColour.Background;
				item.ForeColor = Settings.ExternalEmailColour.Foreground;
			}
            // Due the list view being a real pain in the axxx we have to do this again.
            if (rating == RatingType.High)
            {
                Font newFt = new Font(item.Font.FontFamily, item.Font.Size, FontStyle.Regular);
                item.Font = newFt;
                item.BackColor = Settings.HighColour.Background;
                item.ForeColor = Settings.HighColour.Foreground;
            }
            //Just make sure the entire line is coloured if high
            if (View.Columns[0].Name == "Rating")
            {
                switch (rating)
                {
                    case RatingType.High:
                        item.BackColor = Settings.HighColour.Background;
                        item.ForeColor = Settings.HighColour.Foreground;
                        break;
                    case RatingType.Medium:
                        item.BackColor = Settings.MediumColour.Background;
                        item.ForeColor = Settings.MediumColour.Foreground;
                        break;
                    case RatingType.Low:
                        item.BackColor = Settings.LowColour.Background;
                        item.ForeColor = Settings.LowColour.Foreground;
                        break;
                }
            }
		}
Beispiel #47
0
    static void Main(string[] args)
    {
        Assembly assembly = Assembly.GetExecutingAssembly();
        Assembly.LoadFile(Path.GetDirectoryName(assembly.Location) + Path.DirectorySeparatorChar + "MyMediaLiteExperimental.dll");

        AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(Handlers.UnhandledExceptionHandler);
        Console.CancelKeyPress += new ConsoleCancelEventHandler(AbortHandler);

        // recommender arguments
        string method              = "BiasedMatrixFactorization";
        string recommender_options = string.Empty;

        // help/version
        bool show_help    = false;
        bool show_version = false;

        // arguments for iteration search
        int find_iter      = 0;
        int max_iter       = 500;
        double epsilon     = 0;
        double rmse_cutoff = double.MaxValue;
        double mae_cutoff  = double.MaxValue;

        // data arguments
        string data_dir             = string.Empty;
        string user_attributes_file = string.Empty;
        string item_attributes_file = string.Empty;
        string user_relations_file  = string.Empty;
        string item_relations_file  = string.Empty;

        // other arguments
        bool online_eval       = false;
        bool search_hp         = false;
        string save_model_file = string.Empty;
        string load_model_file = string.Empty;
        int random_seed        = -1;
        string prediction_file = string.Empty;
        string prediction_line = "{0}\t{1}\t{2}";
        int cross_validation   = 0;
        double split_ratio     = 0;

           	var p = new OptionSet() {
            // string-valued options
            { "training-file=",       v              => training_file        = v },
            { "test-file=",           v              => test_file            = v },
            { "recommender=",         v              => method               = v },
            { "recommender-options=", v              => recommender_options += " " + v },
           			{ "data-dir=",            v              => data_dir             = v },
            { "user-attributes=",     v              => user_attributes_file = v },
            { "item-attributes=",     v              => item_attributes_file = v },
            { "user-relations=",      v              => user_relations_file  = v },
            { "item-relations=",      v              => item_relations_file  = v },
            { "save-model=",          v              => save_model_file      = v },
            { "load-model=",          v              => load_model_file      = v },
            { "prediction-file=",     v              => prediction_file      = v },
            { "prediction-line=",     v              => prediction_line      = v },
            // integer-valued options
           			{ "find-iter=",           (int v)        => find_iter            = v },
            { "max-iter=",            (int v)        => max_iter             = v },
            { "random-seed=",         (int v)        => random_seed          = v },
            { "cross-validation=",    (int v)        => cross_validation     = v },
            // double-valued options
            { "epsilon=",             (double v)     => epsilon              = v },
            { "rmse-cutoff=",         (double v)     => rmse_cutoff          = v },
            { "mae-cutoff=",          (double v)     => mae_cutoff           = v },
            { "split-ratio=",         (double v)     => split_ratio          = v },
            // enum options
            { "rating-type=",         (RatingType v) => rating_type          = v },
            { "file-format=",         (RatingFileFormat v) => file_format    = v },
            // boolean options
            { "compute-fit",          v => compute_fit  = v != null },
            { "online-evaluation",    v => online_eval  = v != null },
            { "search-hp",            v => search_hp    = v != null },
            { "help",                 v => show_help    = v != null },
            { "version",              v => show_version = v != null },
           	  	};
           		IList<string> extra_args = p.Parse(args);

        // TODO make sure interaction of --find-iter and --cross-validation works properly

        bool no_eval = test_file == null;

        if (show_version)
            ShowVersion();
        if (show_help)
            Usage(0);

        if (extra_args.Count > 0)
            Usage("Did not understand " + extra_args[0]);

        if (training_file == null)
            Usage("Parameter --training-file=FILE is missing.");

        if (cross_validation != 0 && split_ratio != 0)
            Usage("--cross-validation=K and --split-ratio=NUM are mutually exclusive.");

        if (random_seed != -1)
            MyMediaLite.Util.Random.InitInstance(random_seed);

        recommender = Recommender.CreateRatingPredictor(method);
        if (recommender == null)
            Usage(string.Format("Unknown method: '{0}'", method));

        Recommender.Configure(recommender, recommender_options, Usage);

        // ID mapping objects
        if (file_format == RatingFileFormat.KDDCUP_2011)
        {
            user_mapping = new IdentityMapping();
            item_mapping = new IdentityMapping();
        }

        // load all the data
        LoadData(data_dir, user_attributes_file, item_attributes_file, user_relations_file, item_relations_file, !online_eval);

        Console.Error.WriteLine(string.Format(CultureInfo.InvariantCulture, "ratings range: [{0}, {1}]", recommender.MinRating, recommender.MaxRating));

        if (split_ratio > 0)
        {
            var split = new RatingsSimpleSplit(training_data, split_ratio);
            recommender.Ratings = split.Train[0];
            training_data = split.Train[0];
            test_data     = split.Test[0];
        }

        Utils.DisplayDataStats(training_data, test_data, recommender);

        if (find_iter != 0)
        {
            if ( !(recommender is IIterativeModel) )
                Usage("Only iterative recommenders support find_iter.");
            var iterative_recommender = (IIterativeModel) recommender;
            Console.WriteLine(recommender.ToString() + " ");

            if (load_model_file == string.Empty)
                recommender.Train();
            else
                Recommender.LoadModel(iterative_recommender, load_model_file);

            if (compute_fit)
                Console.Write(string.Format(CultureInfo.InvariantCulture, "fit {0,0:0.#####} ", iterative_recommender.ComputeFit()));

            MyMediaLite.Eval.Ratings.DisplayResults(MyMediaLite.Eval.Ratings.Evaluate(recommender, test_data));
            Console.WriteLine(" iteration " + iterative_recommender.NumIter);

            for (int i = (int) iterative_recommender.NumIter + 1; i <= max_iter; i++)
            {
                TimeSpan time = Utils.MeasureTime(delegate() {
                    iterative_recommender.Iterate();
                });
                training_time_stats.Add(time.TotalSeconds);

                if (i % find_iter == 0)
                {
                    if (compute_fit)
                    {
                        double fit = 0;
                        time = Utils.MeasureTime(delegate() {
                            fit = iterative_recommender.ComputeFit();
                        });
                        fit_time_stats.Add(time.TotalSeconds);
                        Console.Write(string.Format(CultureInfo.InvariantCulture, "fit {0,0:0.#####} ", fit));
                    }

                    Dictionary<string, double> results = null;
                    time = Utils.MeasureTime(delegate() { results = MyMediaLite.Eval.Ratings.Evaluate(recommender, test_data); });
                    eval_time_stats.Add(time.TotalSeconds);
                    MyMediaLite.Eval.Ratings.DisplayResults(results);
                    rmse_eval_stats.Add(results["RMSE"]);
                    Console.WriteLine(" iteration " + i);

                    Recommender.SaveModel(recommender, save_model_file, i);
                    if (prediction_file != string.Empty)
                        Prediction.WritePredictions(recommender, test_data, user_mapping, item_mapping, prediction_line, prediction_file + "-it-" + i);

                    if (epsilon > 0.0 && results["RMSE"] - rmse_eval_stats.Min() > epsilon)
                    {
                        Console.Error.WriteLine(string.Format(CultureInfo.InvariantCulture, "{0} >> {1}", results["RMSE"], rmse_eval_stats.Min()));
                        Console.Error.WriteLine("Reached convergence on training/validation data after {0} iterations.", i);
                        break;
                    }
                    if (results["RMSE"] > rmse_cutoff || results["MAE"] > mae_cutoff)
                    {
                            Console.Error.WriteLine("Reached cutoff after {0} iterations.", i);
                            break;
                    }
                }
            } // for

            DisplayStats();
        }
        else
        {
            TimeSpan seconds;

            if (load_model_file == string.Empty)
            {
                if (cross_validation > 0)
                {
                    Console.Write(recommender.ToString());
                    Console.WriteLine();
                    var split = new RatingCrossValidationSplit(training_data, cross_validation);
                    var results = MyMediaLite.Eval.Ratings.EvaluateOnSplit(recommender, split); // TODO if (search_hp)
                    MyMediaLite.Eval.Ratings.DisplayResults(results);
                    no_eval = true;
                    recommender.Ratings = training_data;
                }
                else
                {
                    if (search_hp)
                    {
                        // TODO --search-hp-criterion=RMSE
                        double result = NelderMead.FindMinimum("RMSE", recommender);
                        Console.Error.WriteLine("estimated quality (on split) {0}", result.ToString(CultureInfo.InvariantCulture));
                        // TODO give out hp search time
                    }

                    Console.Write(recommender.ToString());
                    seconds = Utils.MeasureTime( delegate() { recommender.Train(); } );
                    Console.Write(" training_time " + seconds + " ");
                }
            }
            else
            {
                Recommender.LoadModel(recommender, load_model_file);
                Console.Write(recommender.ToString() + " ");
            }

            if (!no_eval)
            {
                if (online_eval)  // TODO support also for prediction outputs (to allow external evaluation)
                    seconds = Utils.MeasureTime(delegate() { MyMediaLite.Eval.Ratings.DisplayResults(MyMediaLite.Eval.Ratings.EvaluateOnline(recommender, test_data)); });
                else
                    seconds = Utils.MeasureTime(delegate() { MyMediaLite.Eval.Ratings.DisplayResults(MyMediaLite.Eval.Ratings.Evaluate(recommender, test_data)); });

                Console.Write(" testing_time " + seconds);
            }

            if (compute_fit)
            {
                Console.Write("fit ");
                seconds = Utils.MeasureTime(delegate() {
                    MyMediaLite.Eval.Ratings.DisplayResults(MyMediaLite.Eval.Ratings.Evaluate(recommender, training_data));
                });
                Console.Write(string.Format(CultureInfo.InvariantCulture, " fit_time {0,0:0.#####} ", seconds));
            }

            if (prediction_file != string.Empty)
            {
                seconds = Utils.MeasureTime(delegate() {
                        Console.WriteLine();
                        Prediction.WritePredictions(recommender, test_data, user_mapping, item_mapping, prediction_line, prediction_file);
                });
                Console.Error.Write("predicting_time " + seconds);
            }

            Console.WriteLine();
            Console.Error.WriteLine("memory {0}", Memory.Usage);
        }
        Recommender.SaveModel(recommender, save_model_file);
    }
Beispiel #48
0
 protected static void SetSubItemColour(ListViewItem item, bool isExternal, ListViewItem.ListViewSubItem subItem, RatingType rating)
 {
     item.UseItemStyleForSubItems = false;
     if (isExternal)
     {
         // Now work out the colour of the item
         //item.UseItemStyleForSubItems = true;
         // Important note - Make sure that the colours are set after assigning
         // sub items or else the sub items will overwrite the settings!!!
         subItem.BackColor = Settings.ExternalEmailColour.Background;
         subItem.ForeColor = Settings.ExternalEmailColour.Foreground;
     }
     if (rating == RatingType.High)
     {
         Font newFt = new Font(subItem.Font.FontFamily, subItem.Font.Size, FontStyle.Regular);
         subItem.Font = newFt;
         subItem.BackColor = Settings.HighColour.Background;
         subItem.ForeColor = Settings.HighColour.Foreground;
     }
     if (subItem.Name == "Rating")
     {                
         switch (rating)
         {
             case RatingType.High:
                 subItem.BackColor = Settings.HighColour.Background;
                 subItem.ForeColor = Settings.HighColour.Foreground;
                 break;
             case RatingType.Medium:
                 subItem.BackColor = Settings.MediumColour.Background;
                 subItem.ForeColor = Settings.MediumColour.Foreground;
                 break;
             case RatingType.Low:
                 subItem.BackColor = Settings.LowColour.Background;
                 subItem.ForeColor = Settings.LowColour.Foreground;
                 break;
         }
     }
 }
Beispiel #49
0
        /// <summary>
        /// Logs the feedback.
        /// </summary>
        /// <param name="screenName">Name of the screen.</param>
        /// <param name="ratingType">Type of the rating.</param>
        /// <param name="comment">The comment.</param>
        public void LogFeedback(string screenName, RatingType ratingType, string comment)
        {
            try
            {
                FeedbackItem feedbackItem = new FeedbackItem(this.applicationId, screenName,
                    comment, ratingType, this.sessionId, this.applicationVersion);

                this.iStorageDal.Save(feedbackItem);

                this.setItemsWaitingToBeUploaded();
                if (this.uploadType == UploadType.WhileUsingAsync)
                {
                    this.uploadIntelligent();
                }
            }
            catch (ExceptionDatabaseLayer ex)
            {
                this.logSystemError(ex);
                throw ex;
            }
        }
 /// <summary>
 /// Creates the image tag.
 /// </summary>
 /// <param name="email">The email address.</param>
 /// <param name="size">The size in pixels (the height &amp; width, as the image is square)</param>
 /// <param name="maxAllowedRating">The max allowed rating.</param>
 /// <param name="defaultImage">The default image, or keyword.</param>
 /// <param name="outputGravatarSiteLink">If set to <c>true</c> wrap image tag in anchor tag..</param>
 /// <param name="linkTitle">The title for the Gravatar site link..</param>
 /// <returns>string of HTML.</returns>
 /// <remarks>For a more detailed description of the parameters, <see cref="GravatarViewComponent"/></remarks>
 public string CreateImageTag(string email, int size, RatingType maxAllowedRating, string defaultImage, bool outputGravatarSiteLink, string linkTitle)
 {
     return GravatarHelper.CreateImageTag(email, size, defaultImage, maxAllowedRating, outputGravatarSiteLink, linkTitle);
 }
Beispiel #51
0
        private void DoAutoConfiguration()
        {
            if (disable) { return; }
            SiteUser currentUser = SiteUtils.GetCurrentSiteUser();
            if (currentUser == null) { disable = true; return; }
            SiteSettings siteSettings = CacheHelper.GetCurrentSiteSettings();
            if (siteSettings == null) { disable = true; return; }

            switch (siteSettings.AvatarSystem)
            {
                case "gravatar":
                    useGravatar = true;
                    disable = false;
                    break;

                case "internal":
                    useGravatar = false;
                    disable = false;
                    break;

                case "none":
                default:
                    useGravatar = false;
                    disable = true;
                    break;

            }

            siteId = siteSettings.SiteId;
            _maxAllowedRating = SiteUtils.GetMaxAllowedGravatarRating();
            userId = currentUser.UserId;
            avatarFile = currentUser.AvatarUrl;
            Email = currentUser.Email;
            if (disableUseLinkWithAutoConfigure)
            {
                UseLink = false;
            }
        }
		/// <summary>
		/// This constructor will assign the item
		/// </summary>
		/// <param name="item">The message added</param>
		public ScanAuditEventArgs( string text )
		{
			m_text = text;
            m_type = RatingType.None;
		}
Beispiel #53
0
        public virtual RatingType[] GetRatingType(long fbUserId, long[] songIds)
        {
            var queriedRatings =
                Ratings.Where(rating => songIds.Contains(rating.Song.Id)).ToArray();

            
            /* in case user didn't vote for all songs, we need to have the
             * array in the size of the original given array and fill in values
             * for those songs that the user has voted for */
            var ratingType = new RatingType[songIds.Length];

            for (int index = 0; index < songIds.Length; index++)
            {
                /* only fill in the voting in the index of the songs the user
                 * really did vote for */
                var foundSongStatisicts = queriedRatings
                    .Where(rating => rating.Song.Id == songIds[index])
                    .FirstOrDefault();
                if (foundSongStatisicts != null)
                {
                    ratingType[index] = foundSongStatisicts.GetCurrentUserRating(fbUserId);
                }
            }
            return ratingType;
        }
Beispiel #54
0
        /// <summary>
        /// This is the default constructor
        /// </summary>
        public DigitalCounter()
        {
            InitializeComponent();
            // Initialise the internal members
            m_numDigits = 5;
            m_overflow = true;
            m_digits = new ImageList();
            m_digits.ImageSize = new Size(15, 20);
            m_numbers = new int[m_numDigits];
			m_rating = RatingType.Medium;
            this.Size = new Size(48, 14);
            // Bitmap

            // Initialise the bitmap stuff
            GetNumbers();
			ShowDigits();
            SetDigits();
            Invalidate();

        }
Beispiel #55
0
		/// <summary>
		/// This method will workout the rating type
		/// </summary>
		/// <param name="rating"></param>
		/// <returns></returns>
		private void WorkoutType( string rating )
		{
			if (string.Compare( rating, "high", true, System.Threading.Thread.CurrentThread.CurrentCulture ) == 0)
				m_rating = RatingType.High;
			else if (string.Compare( rating, "medium", true, System.Threading.Thread.CurrentThread.CurrentCulture ) == 0)
				m_rating = RatingType.Medium;
			else if (string.Compare( rating, "low", true, System.Threading.Thread.CurrentThread.CurrentCulture ) == 0)
				m_rating = RatingType.Low;
			else
				m_rating = RatingType.None;
			System.Diagnostics.Trace.WriteLine( "Risk Rating Type is " + m_rating, "Condition.WorkoutType" );
		}
        /// <summary>
        /// Creates a Gravatar image tag.  
        /// </summary>
        /// <param name="email">The email address.</param>
        /// <param name="size">The size in pixels (the height &amp; width, as the image is square)</param>
        /// <param name="defaultImage">The default image, or keyword.</param>
        /// <param name="maxAllowedRating">The max allowed rating.</param>
        /// <param name="outputGravatarSiteLink">If set to <c>true</c> wrap image tag in anchor tag..</param>
        /// <param name="linkTitle">The title for the Gravatar site link..</param>
        /// <returns>string of HTML.</returns>
        /// <remarks><para>
        /// This is a static method, so that it can be called from a controller without having to 
        /// create an instance of GravatarHelper. </para>
        /// <para>The parameters here are in a slightly different order from the instance methods, to prevent ambigity.
        /// </para>
        /// For a more detailed description of the parameters, <see cref="GravatarViewComponent"/></remarks>
        /// 
        static public string CreateImageTag(string email, int size, string defaultImage, RatingType maxAllowedRating, bool outputGravatarSiteLink, string linkTitle)
        {
            if (string.IsNullOrEmpty(email))
                throw new ArgumentException("Email address must be specified", "email");

            if (size < 1 || size > 512)
                size = 80;

            // build up image url, including MD5 hash for supplied email:
            MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();

            byte[] hashedBytes = md5Hasher.ComputeHash(Encoding.UTF8.GetBytes(email.ToLower()));
            StringBuilder sb = new StringBuilder(hashedBytes.Length * 2);

            foreach(byte b in hashedBytes)
            {
                sb.AppendFormat("{0:x2}", b);
            }
            string format = "";
            if (string.IsNullOrEmpty(defaultImage))
            {
                if (outputGravatarSiteLink)
                    format = @"<a href=""http://www.gravatar.com"" title=""{4}""><img src=""http://www.gravatar.com/avatar/{0}.jpg?rating={1}&size={2}"" height=""{2}"" width=""{2}"" alt=""{4}"" /></a>";
                else
                    format = @"<img src=""http://www.gravatar.com/avatar/{0}.jpg?rating={1}&size={2}"" height=""{2}"" width=""{2}"" alt=""Gravatar"" />";
            }
            else
            {
                if (outputGravatarSiteLink)
                    format = @"<a href=""http://www.gravatar.com"" title=""{4}""><img src=""http://www.gravatar.com/avatar/{0}.jpg?rating={1}&size={2}&default={3}"" height=""{2}"" width=""{2}"" alt=""{4}"" /></a>";
                else
                    format = @"<img src=""http://www.gravatar.com/avatar/{0}.jpg?rating={1}&size={2}&default={3}"" height=""{2}"" width=""{2}"" alt=""Gravatar"" />";
            }

            return string.Format(format, sb, maxAllowedRating, size, HttpUtility.UrlEncode(defaultImage), HttpUtility.HtmlEncode(linkTitle));
		}
Beispiel #57
0
        public static bool SubmitRating(RatingType type, string itemId, int rating)
        {
            string account = DBOption.GetOptions(DBOption.cOnlineUserID);
            if (String.IsNullOrEmpty(account))
            {
            // if there is no tvdb account identifier, but we are using follwit. dont display the
            // "please fill in ID" error.
            if (FollwitConnector.Enabled) {
                return false;
            }

            string[] lines = new string[] { Translation.TVDB_INFO_ACCOUNTID_1, Translation.TVDB_INFO_ACCOUNTID_2 };
            TVSeriesPlugin.ShowDialogOk(Translation.TVDB_INFO_TITLE, lines);
            MPTVSeriesLog.Write("Cannot submit rating, make sure you have your Account identifier set!");
            return false;
            }

            if (itemId == "0" || rating < 0 || rating > 10)
            {
            MPTVSeriesLog.Write("Cannot submit rating, invalid values.....this is most likely a programming error");
            return false;
            }

            if (!DBOnlineMirror.IsMirrorsAvailable)
            {
            // Server maybe available now.
            DBOnlineMirror.Init();
            if (!DBOnlineMirror.IsMirrorsAvailable)
            {
                GUIDialogOK dlgOK = (GUIDialogOK)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_OK);
                dlgOK.SetHeading(Translation.TVDB_ERROR_TITLE);
                if (!TVSeriesPlugin.IsNetworkAvailable)
                {
                    string[] lines = new string[] { Translation.NETWORK_ERROR_UNAVAILABLE_1, Translation.NETWORK_ERROR_UNAVAILABLE_2 };
                    TVSeriesPlugin.ShowDialogOk(Translation.TVDB_ERROR_TITLE, lines);
                }
                else
                {
                    string[] lines = new string[] { Translation.TVDB_ERROR_UNAVAILABLE_1, Translation.TVDB_ERROR_UNAVAILABLE_2 };
                    TVSeriesPlugin.ShowDialogOk(Translation.TVDB_ERROR_TITLE, lines);
                }

                MPTVSeriesLog.Write("Cannot submit rating, the online database is unavailable");
                return false;
            }
            }
            // ok we're good
            MPTVSeriesLog.Write(string.Format("Submitting Rating of {2} for {0} {1}", type.ToString(), itemId, rating), MPTVSeriesLog.LogLevel.Debug);
            Generic(string.Format(apiURIs.SubmitRating, account, type.ToString(), itemId, rating), true, false, Format.NoExtension);
            return true;
        }
 /// <summary>
 /// This will write the text to the text box
 /// </summary>
 /// <param name="text">The text to be written</param>
 private void WriteIt(string text, RatingType rating)
 {
     string msg = (m_isPadding ? text.PadLeft(IndentSize * IndentLevel + text.Length) : text);
     StringBuilder sb = new StringBuilder();
     sb.AppendFormat("[{0}] - {1}",
         DateTime.Now.ToString("HH:mm:ss:fff", System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat),
         msg);
     if (OnAudit != null)
     {
         OnAudit(this, new ScanAuditEventArgs(sb.ToString(), rating));
     }
 }
Beispiel #59
0
        public void ModifyRating(LibraryItem libraryItem, RatingType rating)
        {
            _databaseAccessor.UpdateLibraryRating(libraryItem.Id, rating);
            libraryItem.ModifyRating(rating);

        }
 public void UpdateLibraryRating(long id, RatingType rating)
 {
     SqlExecuter.Execute(SQLResource.UpdateLibraryRating, new { Id = id, Rating = (int)rating });
 }