Esempio n. 1
0
        public void NoBooks()
        {
            var ratingSystem = new RatingSystem();
            var results      = ratingSystem.ComputeRating(new RatingInput[] { });

            Assert.AreEqual(0, results.Count());
        }
Esempio n. 2
0
    void Start()
    {
        //height = width;
        instance = this;
        //myCamera = gameObject.GetComponent<Camera>();
        shutterSound = GetComponent <AudioSource>();

        AudioManager          = GameObject.Find("---AudioManager").GetComponent <AudioManager>();
        ScreenCapDirectory    = Application.persistentDataPath;
        FinalCameraController = GetComponent <FinalCameraController>();
        //CalculateInventory = GameObject.Find("---InventoryController").GetComponent<CalculateInventory>();
        RatingSys = GameObject.Find("FloatingUI").GetComponent <RatingSystem>();

        if (FinalCameraController != null)
        {
            AdsController = GameObject.Find("---AdsController").GetComponent <AdsController>();
        }


        //        postImage = GetComponent<Image>();
        //        //print(postImage.name);

        if (!FinalCameraController.isTutorial)
        {
            //KararaTop = KararaTopImage.sprite.name;
            //KararaBottom = KararaBottomImage.sprite.name;
            //KararaShoe = KararaShoeImage.sprite.name;
        }
    }
Esempio n. 3
0
        public void SimpleRatings()
        {
            var tests = new[]
            {
                new RatingInput {
                    BookId = Guid.NewGuid(), Title = "abc", IsForeign = false
                },
                new RatingInput {
                    BookId = Guid.NewGuid(), Title = "abc", IsForeign = true
                },
                new RatingInput {
                    BookId = Guid.NewGuid(), Title = "super abc", IsForeign = false
                },
                new RatingInput {
                    BookId = Guid.NewGuid(), Title = "super abc", IsForeign = true
                },
            };

            var ratingSystem = new RatingSystem();
            var ratings      = ratingSystem.ComputeRating(tests);

            Assert.AreEqual(
                "0.00, 0.00, 100.00, 120.00",
                string.Join(", ", ratings.Select(r => r.Value.ToString("f2", CultureInfo.InvariantCulture))));
        }
Esempio n. 4
0
        public RatingSystem Load(RtKind kind)
        {
            string fileName = GetFileName(kind);

            XmlSerializer serializer = new XmlSerializer(typeof(RatingSystem));
            var           result     = new RatingSystem();
            Stream        stream     = null;

            try
            {
                stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                result = (RatingSystem)serializer.Deserialize(stream);
            }
            catch (Exception ex)
            {/* ... */
                ex.ToString();
            }
            finally
            {
                if (null != stream)
                {
                    stream.Close();
                }
            }
            result.Kind = kind;

            OnLoad(result);

            return(result);
        }
Esempio n. 5
0
 // Use this for initialization
 void Start()
 {
     if (RatingSystem.lSystems.Count <= 0)
     {
         Debug.Log("Initializing LSystems...");
         SqlManager.SqlManagerInstance.StartCoroutine(SqlConnection.GetPopulation(12, retrievedLSystems =>
         {
             Debug.Log("got 'em " + retrievedLSystems.Count());
             foreach (LSystemWrapper w in retrievedLSystems)
             {
                 Debug.Log(w.GetString());
             }
             InitializeLSystems(retrievedLSystems);
             loadXMLs();
             LoadScreenshots(0);
         }));
     }
     else
     {
         for (int i = 0; i < RatingSystem.levelData.Count; ++i)
         {
             if (RatingSystem.levelData[i][0].levelSprite == null)
             {
                 //Debug.Log("LSystem " + i + " does not have screenshots generated");
                 LoadScreenshots(i);
                 return;
             }
         }
         RatingSystem.EndGeneratingScreenshots();
     }
     loading.gameObject.SetActive(false);
 }
Esempio n. 6
0
        private bool CreatePoints(RatingSystem system, RatingSystem.Person person)
        {
            bool result = false;

            result &= system != null && DrawLines(system.Ratings.FindAll(item => person != null && item.PersonId == person.Id), polyLine, cvRating, null, null);

            string footer1    = null;
            string footer2    = null;
            var    tourRating = _bc.GetRatingGrowth(_tournamentView.Tournament, _tournamentView.CurrentRoundNumber, _player.Id);

            if (tourRating.Count > 0)
            {
                double delta = tourRating[0].Rating - _player.Rating;
                double dAbs  = delta >= 0 ? delta : -delta;
                footer1 = _player.Capt.NewRating + ": " + Math.Round(tourRating[0].Rating, 2).ToString() +
                          " (" + (delta < 0 ? "-" : "+") + Math.Round(dAbs, 2).ToString() + ")" +
                          (_player.RatingAbnormal ? " - " + LangResources.LR.AbnormalGrowth : string.Empty);
            }

            footer2 = _player.Capt.Round + " " + Tour.ToRoman(_tournamentView.CurrentRoundNumber);

            result &= DrawLines(tourRating, newLine, cvTournamentRating, footer1, footer2);

            return(result);
        }
        public static RatingSystem CreateRatingSystem(int gameTypeId, string gameTypeName)
        {
            RatingSystem rs = new RatingSystem(gameTypeId, gameTypeName);

            BuildRatingSystem(gameTypeId, rs.Players, rs.Competitions, DateTime.MaxValue);
            return(rs);
        }
Esempio n. 8
0
        public bool Save(RatingSystem rs)
        {
            bool result = false;

            string fileName = GetFileName(rs.Kind);
            string filePath = System.IO.Path.GetDirectoryName(fileName);

            if (!Directory.Exists(filePath))
            {
                try
                {
                    Directory.CreateDirectory(filePath);
                }
                catch (Exception) { }
            }

            if (!string.IsNullOrEmpty(fileName))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(RatingSystem));
                TextWriter    writer     = new StreamWriter(fileName);
                try
                {
                    serializer.Serialize(writer, rs);
                    result = true;
                }
                catch { /* ... */ }
                finally
                {
                    writer.Close();
                }
            }
            return(result);
        }
Esempio n. 9
0
 private void OnLoad(RatingSystem rts)
 {
     foreach (var item in rts.Persons)
     {
         item.ClubsLink = rts.Clubs;
     }
 }
Esempio n. 10
0
    // Update is called once per frame
    void Update()
    {
        if (RatingSystem.IsGenerating)
        {
            //Debug.Log(System.DateTime.Now.ToString() + "\tStability: " + GetLevelStability());
            // Wait until level is stable, then take screenshot
            if (stabilityCounter <= 0f && (IsLevelStable() || timeToStable >= STABILITY_TIMEOUT))
            {
                if (!RatingSystem.IsEvolution)
                {
                    Camera        camera    = GameplayCam.GetCamera();
                    int           resWidth  = camera.pixelWidth;
                    int           resHeight = camera.pixelHeight;
                    RenderTexture rt        = new RenderTexture(resWidth, resHeight, 24);
                    camera.targetTexture = rt;
                    Texture2D screenShot = new Texture2D(resWidth, resHeight, TextureFormat.RGB24, false);
                    camera.Render();
                    RenderTexture.active = rt;
                    screenShot.ReadPixels(new Rect(0, 0, resWidth, resHeight), 0, 0);
                    screenShot.Apply();
                    camera.targetTexture = null;
                    RenderTexture.active = null; // JC: added to avoid errors
                    Destroy(rt);

                    // for saving screenshot as png
                    //byte[] bytes = screenShot.EncodeToPNG();
                    //string filename = string.Format("{0}/screenshots/screen_{1}x{2}_{3}.png",
                    //              Application.dataPath,
                    //              resWidth, resHeight,
                    //              System.DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss"));
                    //System.IO.File.WriteAllBytes(filename, bytes);
                    //Debug.Log(string.Format("Took screenshot to: {0}", filename));

                    // save sprite
                    Sprite levelSprite = Sprite.Create(screenShot, new Rect(0, 0, resWidth, resHeight), new Vector2(0, 0));
                    RatingSystem.AddLevel(LevelList.Instance.CurrentIndex, levelSprite, HUD.Instance.GetScore(), timeToStable, _pigs.Count > 0);
                    //Debug.Log(System.DateTime.Now.ToString() + "\tLevel Count: " + RatingSystem.levelData.Count);
                }
                else
                {
                    RatingSystem.keptForEvolution[RatingSystem.CurrentLSystemIndex].fitness += RatingSystem.GetLevelFitness(_pigs.Count > 0, HUD.Instance.GetScore(), timeToStable) / RatingSystem.MAX_LEVELS;
                }
                // go to next level
                NextLevel();
            }
            else
            {
                stabilityCounter -= Time.deltaTime;
                timeToStable     += Time.deltaTime;
            }
        }
        else
        {
            // Check if birds was trown, if it died and swap them when needed
            ManageBirds();
        }
    }
Esempio n. 11
0
    public void LoadScreenshots(int lSystemIndex)
    {
        RatingSystem.StartGeneratingScreenshots(lSystemIndex);
        ABLevelSelector sel = gameObject.AddComponent <ABLevelSelector>();

        sel.LevelIndex = lSystemIndex * RatingSystem.MAX_LEVELS;

        LoadNextScene("GameWorld", true, sel.UpdateLevelList);
    }
Esempio n. 12
0
        public RatingType GetRatingType(int universityId, int disciplineId)
        {
            RatingSystem ratingSystem = Database.RatingSystemRepository.Find(rs => rs.UniversityId == universityId && rs.DisciplineId == disciplineId).FirstOrDefault();

            if (ratingSystem != null)
            {
                return(Database.RatingTypeRepository.Get(ratingSystem.RatingTypeId));
            }
            return(Database.RatingTypeRepository.Get(1));
        }
Esempio n. 13
0
        public void UnknownTitle()
        {
            var bookWithoutTitle = new RatingInput
            {
                BookId    = Guid.NewGuid(),
                Title     = null,
                IsForeign = false
            };

            var ratingSystem = new RatingSystem();
            var result       = ratingSystem.ComputeRating(new[] { bookWithoutTitle }).Single();

            Assert.AreEqual(bookWithoutTitle.BookId, result.BookId);
            Assert.AreEqual(0, result.Value);
        }
Esempio n. 14
0
        /// <summary>
        /// Открывает и обновляет рейтинговую систему
        /// </summary>
        /// <param name="GameTypeId">Id рейтинговой системы</param>
        public void Open(int gameTypeId, string gameTypeName)
        {
#if FEDITION || STANDARD || FEDITION_PLUS || STANDARD_PLUS
            RS = RatingSystemBuilder.CreateRatingSystem(gameTypeId, gameTypeName);
            PlayersRatingList current_rating = RatingSystemBuilder.GetPlayersRating(gameTypeId, FRatingDate);
            FPlayers = new PlayerRating[current_rating.Count];
            int i = 0;
            foreach (PlayerRating player in current_rating.Values)
            {
                FPlayers[i] = player;
                i++;
            }
            SortedBy = SortBy.Name;
            SetScrollBars();
#endif
        }
Esempio n. 15
0
    public void SubmitRatings()
    {
        RatingSystem.SubmitRatings();

        // IMPORTANT: Use the new List<bool> isStarred to determine which LSystem's have been selected by the player
        // the index in isStarred corresponds to the index in lSystems
        //Debug.Log("creating wrapper list...");
        List <LSystemWrapper> wrappers = new List <LSystemWrapper>();

        for (int i = 0; i < RatingSystem.lSystems.Count; i++)
        {
            //Debug.Log("in loop i=" + i);
            LSystem lSystem = RatingSystem.lSystems[i];
            //Debug.Log("got lSystem");
            LSystemWrapper wrapper       = new LSystemWrapper();
            string[]       axiomAndRules = LSystem.Encode(lSystem).Split('~');
            //Debug.Log("created axiomAndRules");
            wrapper.Axiom = axiomAndRules[0];
            //Debug.Log("set Axiom");
            wrapper.Rules = axiomAndRules[1];
            // Debug.Log("set Rules");
            wrapper.IsStarred = RatingSystem.isStarred[i];
            //Debug.Log("set isStarred");
            wrapper.PopulationId = SqlConnection.PopulationId.Value;
            // Debug.Log("set PopulationId");
            wrappers.Add(wrapper);
        }
        //Debug.Log("finished creating wrapper list");

        Debug.Log("started coroutine");
        SqlManager.SqlManagerInstance.StartCoroutine(SqlConnection.PostRating(wrappers.ToArray(), () =>
        {
            // keep some levels (starred ones?)

            for (int i = 0; i < RatingSystem.MAX_LSYSTEMS; ++i)
            {
                // add starred level to kept list
                if (RatingSystem.isStarred[i])
                {
                    RatingSystem.keptForEvolution.Add(new RatingSystem.LSystemEvolution(RatingSystem.lSystems[i]));
                }
            }
            // TODO: MUST HAVE A BACKUP PLAN IF PLAYER DOES NOT STAR ENOUGH LEVELS
            int numLSystemsNeeded = RatingSystem.MAX_LSYSTEMS - RatingSystem.keptForEvolution.Count;
            SqlManager.SqlManagerInstance.StartCoroutine(SqlConnection.GetPopulation((int)(numLSystemsNeeded * 0.8f), GetPopulationCallBack));
        }));
    }
Esempio n. 16
0
    // private List<GameObject> tempLevelButtons;


    public void InitializeLSystems(LSystemWrapper[] retrievedLSystems)
    {
        int retrieved = retrievedLSystems?.Length ?? 0;

        for (int i = 0; i < RatingSystem.MAX_LSYSTEMS; i++)
        {
            if (i < retrieved)
            {
                RatingSystem.lSystems.Add(LSystem.Decode(retrievedLSystems[i].GetString()));
            }
            else
            {
                RatingSystem.lSystems.Add(new LSystem(16, 3, 0.2f));
            }
            RatingSystem.GenerateXMLs(i, 5);
        }
    }
        public static PlayersRatingList GetPlayersRating(int gameTypeId, DateTime date)
        {
            PlayersRatingList players      = new PlayersRatingList();
            CompetitionsList  competitions = new CompetitionsList();

            BuildRatingSystem(gameTypeId, players, competitions, date);
#if FEDITION
            foreach (PlayerRating player in players.Values)
            {
                if (player.LastRatingDate != DateTime.MinValue)
                {
                    player.Rating -= (RatingSystem.GetMonthCount(player.LastRatingDate, date) / 3) * 25;
                }
            }
#endif
            return(players);
        }
Esempio n. 18
0
    /// <summary>
    /// When its the sql call is done
    /// retrievedLSystems will be null numLSystemsNeeded was 0
    /// </summary>
    /// <param name="retrievedLSystems"></param>
    public void GetPopulationCallBack(LSystemWrapper[] retrievedLSystems)
    {
        //int retrieved = retrievedLSystems?.Length ?? 0;

        //int kept = RatingSystem.keptForEvolution.Count;

        foreach (LSystemWrapper wrapper in retrievedLSystems)
        {
            RatingSystem.keptForEvolution.Add(new RatingSystem.LSystemEvolution(LSystem.Decode(wrapper.GetString())));
        }

        while (RatingSystem.keptForEvolution.Count < RatingSystem.MAX_LSYSTEMS)
        {
            RatingSystem.keptForEvolution.Add(new RatingSystem.LSystemEvolution(new LSystem(16, 3, 0.2f)));
        }

        //for (int i = kept; i < RatingSystem.MAX_LSYSTEMS; i++)
        //{
        //    if (i - kept < retrieved)
        //    {
        //        RatingSystem.keptForEvolution.Add(new RatingSystem.LSystemEvolution(LSystem.Decode(retrievedLSystems[i].GetString())));
        //    }
        //    else
        //    {
        //        RatingSystem.keptForEvolution.Add(new RatingSystem.LSystemEvolution(new LSystem(10, 3)));
        //    }
        //}
        // keptforevolution will contain a list of levels to run evolution on
        // TODO: Run evolution here and replace RatingSystem.keptForEvolution with the list of newly created LSystems

        RatingSystem.ClearAll();
#if UNITY_WEBGL && !UNITY_EDITOR
        EvolveScene.iterations = 5;
#else
        EvolveScene.iterations = 10;
#endif
        //ABSceneManager.Instance.LoadScene("LevelSelectMenu");
        ABSceneManager.Instance.LoadScene("Evolution");
        //RatingSystem.GenerateXMLs(RatingSystem.CurrentLSystemIndex, 5); // hardcoded height
        //LoadScreenshots(RatingSystem.CurrentLSystemIndex);
        //GenerateNewLevels(RatingSystem.CurrentLSystemIndex);
    }
Esempio n. 19
0
    void Start()
    {
        //find the horizontal scroll snap script
        //myHSS = GameObject.Find("Horizontal Scroll Snap").GetComponent<HorizontalScrollSnap>();

        myAudio = GetComponent <AudioSource>();

        myImage = GetComponent <Image>();
//        secondImage = GetComponentInChildren<Image>();
        hitTime = 0;


        AudioManager = GameObject.Find("---AudioManager").GetComponent <AudioManager>();

        ClothInMachineController = GameObject.Find("---ClothInMachineController");
        FinalCameraController    = GameObject.Find("Main Camera").GetComponent <FinalCameraController>();
        SubwayMovement           = GameObject.Find("---StationController").GetComponent <SubwayMovement>();
        cameraMovement           = GameObject.Find("Main Camera").GetComponent <CameraMovement>();
        RatingSys      = GameObject.Find("FloatingUI").GetComponent <RatingSystem>();
        SpriteLoader   = GameObject.Find("---SpriteLoader").GetComponent <SpriteLoader>();
        BagsController = GameObject.Find("---BagsController").GetComponent <BagsController>();
        ValueEditor    = GameObject.Find("---ValueEditor").GetComponent <ValueEditor>();
        AllMachines    = ClothInMachineController.GetComponent <AllMachines>();

        myAnimator = this.transform.gameObject.GetComponent <Animator>();
        //todo: generate clothes
        //Debug.Log(this.transform.gameObject.tag);

        owner = SpriteLoader.NPCDic[this.transform.gameObject.tag];

        GenerateCloth();

        if (!FinalCameraController.AllStationClothList.ContainsKey(owner.name))
        {
            FinalCameraController.AllStationClothList.Add(owner.name, new List <Sprite>());
        }


        myImage.enabled = true;
        stage           = FinalCameraController.LevelManager.stage;
    }
Esempio n. 20
0
    void Start()
    {
        Resources.UnloadUnusedAssets();

        FinalCameraController = GameObject.Find("Main Camera").GetComponent <FinalCameraController>();
        SubwayMovement        = GameObject.Find("---StationController").GetComponent <SubwayMovement>();
        RatingSystem          = GameObject.Find("FloatingUI").GetComponent <RatingSystem>();
        FishBossNotification  = GameObject.Find("FishBossUI").GetComponent <FishBossNotification>();



        PathFollower = MapCar.GetComponent <PathFollower>();
        carCG        = MapCar.GetComponent <CanvasGroup>();

        int skipInstruction = PlayerPrefs.GetInt("skip", -1);

        if (skipInstruction == 1)
        {
            skip = true;
        }

        GameObject.Find("Main Camera").transform.position = new Vector3(0, 0, -20);

        if (!skip)
        {
        }
        else
        {
            //FinalCameraController.myCameraState = FinalCameraController.CameraState.Subway;
            //ShowRatingSys(false);
            //CloseInstruction();
            EndMapTutorial();
        }



        comicList.Add(new List <Sprite>());
        comicList[0].AddRange(comics1);
        comicList.Add(new List <Sprite>());
        comicList[1].AddRange(comics2);
    }
        /// <summary>
        /// Посторение рейтинговой системы и расчет рейтинга
        /// </summary>
        public static void BuildRatingSystem(int gameTypeId, PlayersRatingList players, CompetitionsList competitions, DateTime date)
        {
            // Загрузить список игроков с начальным рейтингом
            TA.DB.Manager.DatabaseManager.CurrentDb.ReadPlayerRatingList(gameTypeId, players);
#if FEDITION
            // Загрузить результаты по порядку возрастания даты
            TA.DB.Manager.DatabaseManager.CurrentDb.ReadRatingCompetitionList(gameTypeId, competitions, date);
            // Пересчитать рейтинги для каждого турнира по мере возрастания даты
            foreach (CompetitionInfo comp in competitions)
            {
                if (comp.IsRating)
                {
                    int avg_rating = 0;
                    foreach (PlayersCompetitionResult result in comp.Results.Values)
                    {
                        PlayerRating player = players[result.PlayerId];
                        // 1 - Посчитать штрафы за пропуск в зависимости от даты турнира и даты из списка игроков
                        if (player.LastRatingDate != DateTime.MinValue)
                        {
                            result.Penalty = (RatingSystem.GetMonthCount(player.LastRatingDate, comp.Date) / 3) * 25;
                        }
                        // 2 - Расчитать начальный рейтинг (Рейтинг из списка - штраф)
                        result.RatingBegin = player.Rating - result.Penalty;
                        avg_rating        += result.RatingBegin;
                    }
                    foreach (PlayersCompetitionResult result in comp.Results.Values)
                    {
                        PlayerRating player = players[result.PlayerId];
                        // 4 - Расчитать дельту для кажого игрока
                        result.Delta = Convert.ToInt32(Math.Round(10.0 * (result.Points - result.OpponentsCount * RatingSystem.Pexp(result.RatingBegin - result.AvgOppRating(comp.Results)))));
                        // 5 - Обновить рейтинг и дату в списке игроков
                        player.Rating         = result.RatingBegin + result.Delta;
                        player.LastRatingDate = comp.Date;
                    }
                }
            }
#endif
        }
Esempio n. 22
0
    // Start is called before the first frame update
    void Start()
    {
        Debug.Log("PERSISTENT:" + Application.persistentDataPath);
        if (!isTutorial)
        {
            setting.SetActive(false);
            instruction.SetActive(false);
        }
        //        myCameraState = CameraState.Subway;
        myAppState = AppState.Mainpage;

        CameraMovement = transform.gameObject.GetComponent <CameraMovement>();

        InstagramController  = GameObject.Find("---InstagramController").GetComponent <InstagramController>();
        RatingSys            = GameObject.Find("FloatingUI").GetComponent <RatingSystem>();
        inventorySlotMgt     = GameObject.Find("---InventoryController").GetComponent <InventorySlotMgt>();
        FishBossNotification = GameObject.Find("FishBossUI").GetComponent <FishBossNotification>();
        BagsController       = GameObject.Find("---BagsController").GetComponent <BagsController>();
        FishTextManager      = GameObject.Find("---FishTextManager").GetComponent <FishTextManager>();
        FishBossNotification.HideFish();


        fishTalk.SetActive(false);
        Hide(frontPage);
        Hide(TakePhoto);
        Posture.SetActive(false);



        fishTalkText = fishTalk.gameObject.GetComponentInChildren <TextMeshPro>();
        Hide(Inventory);
        Hide(fishShoutCG);

        ChapterOneEnd = false;

        alreadyClothUI = false;
    }
Esempio n. 23
0
        public ContestantReadViewModel(
            RatingSystem ratingSystem,
            Contestant contestant)
        {
            if (ratingSystem == null)
            {
                throw new ArgumentNullException(nameof(ratingSystem));
            }
            var gamesDb       = ratingSystem.GamesDb;
            var contestantsDb = ratingSystem.ContestantsDb;

            Contestant  = contestant ?? throw new ArgumentNullException(nameof(contestant));
            _statistics = gamesDb.StatisticsConnect(contestant.Guid, contestantsDb)
                          .ObserveOn(RxApp.MainThreadScheduler)
                          .ToProperty(this, nameof(Statistics), ContestantStatistics.GetDefault(contestant.Guid));
            _rating = ratingSystem
                      .RatingsForContestantsConnect()
                      .Filter(rating => rating.ContestantGuid == contestant.Guid)
                      .QueryWhenChanged(set => set.Items.First().Score)
                      .ObserveOn(RxApp.MainThreadScheduler)
                      .ToProperty(this, nameof(Rating));
            _winTotalRatioPercentage = this.WhenAnyValue(x => x.Statistics,
                                                         statistics =>
                                                         statistics.IsCalibrated
                        ? $"{statistics.WinTotalRatioPercentage:F1}%"
                        : "-")
                                       .ToProperty(this, nameof(WinTotalRatioPercentage));
            _scorePosition = ratingSystem
                             .RatingsForContestantsConnect()
                             .QueryWhenChanged(ratings => ratings.Items
                                               .OrderByDescending(x => x.Score)
                                               .Count(x => x.Score > ratingSystem.RatingsForContestants
                                                      .First(y => y.ContestantGuid == contestant.Guid).Score) + 1)
                             .ObserveOn(RxApp.MainThreadScheduler)
                             .ToProperty(this, nameof(Rating));
        }
Esempio n. 24
0
        private RatingSystem ImportRatingSystem(string url)
        {
            WebRequest request;

            XmlSerializer serializer = new XmlSerializer(typeof(RatingSystem));
            var           result     = new RatingSystem();

            try
            {
                request = (HttpWebRequest)WebRequest.Create(url);
                using (WebResponse response = request.GetResponse())
                {
                    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                    {
                        result = (RatingSystem)serializer.Deserialize(reader);
                    }
                }
            }
            catch (Exception)
            {
            }

            return(result);
        }
Esempio n. 25
0
        public RatingSystem ImportRatingSystem(RtKind kind)
        {
            RatingSystem result  = null;
            string       urlBase = @"http://kfgo.org.ua/autokorsak/rating/";

            switch (kind)
            {
            case RtKind.ua:
            {
                result = ImportRatingSystem(urlBase + "ar_rs_ua.xml?stamp=" + DateTime.Now.Ticks.ToString());
                break;
            }

            case RtKind.ru:
            {
                result = ImportRatingSystem(urlBase + "ar_rs_ru.xml?stamp=" + DateTime.Now.Ticks.ToString());
                break;
            }
            }

            OnLoad(result);

            return(result);
        }
Esempio n. 26
0
 public void Star()
 {
     RatingSystem.RateLSystem(lSystemIndex, star);
 }
Esempio n. 27
0
 public void GenerateNewLevels()
 {
     RatingSystem.GenerateXMLs(lSystemIndex, 5);
     ABLevelSelect.loadXMLs();
     levelSelect.LoadScreenshots(lSystemIndex);
 }
Esempio n. 28
0
        public RatingSystem ImportFromRatingLists(RtKind kind)
        {
            RatingSystem result = new RatingSystem();

            result.Kind = kind;

            DateTime maxDate = DateTime.MinValue;

            var rlBc = new RatingListBC();

            foreach (string dir in System.IO.Directory.EnumerateDirectories(RatingListDL.LocalDataFolder))
            {
                string fileName = dir + "\\" + System.IO.Path.GetFileName(rlBc.GetFileName(kind));
                var    lst      = rlBc.LoadRatingList(kind, fileName);
                if (lst != null)
                {
                    foreach (var item in lst.Items)
                    {
                        string fn     = item.FirstName == null ? string.Empty : item.FirstName.Trim();
                        string ln     = item.LastName == null ? string.Empty : item.LastName.Trim();
                        var    person = result.Persons.Find(fnd => fnd != null && item != null &&
                                                            string.Compare(fnd.LastName, ln, true) == 0 && string.Compare(fnd.FirstName, fn, true) == 0);
                        if (person == null)
                        {
                            person           = new RatingSystem.Person();
                            person.Id        = result.Persons.Count + 1;
                            person.FirstName = fn;
                            person.LastName  = ln;
                            result.Persons.Add(person);
                        }

                        person.Rating  = item.Rating;
                        person.Rank    = item.Rank;
                        person.Grade   = Grade.Parse(item.Grade);
                        person.Comment = item.Comment;

                        if (!string.IsNullOrEmpty(item.City))
                        {
                            string nm = item.City == null ? string.Empty : item.City.Trim();
                            if (!string.IsNullOrEmpty(nm))
                            {
                                var club = result.Clubs.Find(fnd => string.Compare(fnd.Name, nm, true) == 0);
                                if (club == null)
                                {
                                    club      = new RatingSystem.Club();
                                    club.Id   = result.Clubs.Count + 1;
                                    club.Name = nm;
                                    result.Clubs.Add(club);
                                }
                                person.ClubId = club.Id;
                            }
                        }

                        string date = System.IO.Path.GetFileName(dir);
                        int    y    = 0;
                        int    m    = 0;
                        int    d    = 0;
                        if (int.TryParse(date.Substring(0, 4), out y) &&
                            int.TryParse(date.Substring(5, 2), out m) &&
                            int.TryParse(date.Substring(8, 2), out d))
                        {
                            DateTime dt   = new DateTime(y, m, d);
                            var      prev = result.Ratings.Find(fnd => fnd.PersonId == person.Id);
                            if (!(prev != null && prev.Rating == item.Rating))
                            {
                                result.Ratings.Insert(0, new RatingSystem.RatingRec()
                                {
                                    Date = dt, Rating = item.Rating, PersonId = person.Id
                                });
                            }

                            if (maxDate.CompareTo(dt) < 0)
                            {
                                maxDate = dt;
                            }
                        }
                    }
                }
            }

            result.Clubs.Sort(delegate(RatingSystem.Club item1, RatingSystem.Club item2) { return(string.Compare(item1.Name, item2.Name)); });
            result.Persons.Sort(delegate(RatingSystem.Person item1, RatingSystem.Person item2)
            {
                int r = string.Compare(item1.LastName, item2.LastName);
                if (r == 0)
                {
                    r = string.Compare(item1.FirstName, item2.FirstName);
                }
                return(r);
            });
            result.Ratings.Sort(delegate(RatingSystem.RatingRec item1, RatingSystem.RatingRec item2)
            {
                int r = item1.PersonId - item2.PersonId;
                if (r == 0)
                {
                    r = string.Compare(item2.DateStr, item1.DateStr, true);
                }
                return(r);
            });

            result.Date = maxDate.Day + "." + (maxDate.Month < 10 ? "0" : string.Empty) + maxDate.Month + "." + maxDate.Year;

            Save(result);
            return(result);
        }
Esempio n. 29
0
 public bool Save(RatingSystem rs)
 {
     return(GetDL().Save(rs));
 }
Esempio n. 30
0
        public RatingSystem MergeWithRatingList(RtKind kind)
        {
            RatingSystem result = Load(kind);

            var rlBc = new RatingListBC();

            string fileName = rlBc.GetFileName(kind);
            var    lst      = rlBc.LoadRatingList(kind, fileName);

            if (lst != null)
            {
                foreach (var item in lst.Items)
                {
                    string fn = item.FirstName == null ? string.Empty : item.FirstName.Trim();
                    string ln = item.LastName == null ? string.Empty : item.LastName.Trim();

                    //Find in default and Ua langs
                    var person = result.Persons.Find(fnd => fnd != null && item != null &&
                                                     (
                                                         (string.Compare(fnd.LastName, ln, true) == 0 && string.Compare(fnd.FirstName, fn, true) == 0) ||
                                                         (string.Compare(fnd.LastNameUa, ln, true) == 0 && string.Compare(fnd.FirstNameUa, fn, true) == 0)
                                                     ));

                    if (person == null)
                    {
                        person    = new RatingSystem.Person();
                        person.Id = result.Persons.Count + 1;

                        person.FirstName   = fn;
                        person.LastName    = ln;
                        person.FirstNameUa = item.FirstNameUa;
                        person.LastNameUa  = item.LastNameUa;

                        result.Persons.Add(person);
                    }
                    else
                    {
                        //Update Names
                        if (string.Compare(person.LastName, ln, true) == 0 && string.Compare(person.FirstName, fn, true) == 0)
                        {
                            if (string.IsNullOrEmpty(person.FirstNameUa) && !string.IsNullOrEmpty(item.FirstNameUa))
                            {
                                person.FirstNameUa = item.FirstNameUa;
                            }
                            if (string.IsNullOrEmpty(person.LastNameUa) && !string.IsNullOrEmpty(item.LastNameUa))
                            {
                                person.LastNameUa = item.LastNameUa;
                            }
                        }
                        else
                        {
                            if (string.IsNullOrEmpty(person.FirstName) && !string.IsNullOrEmpty(item.FirstName))
                            {
                                person.FirstName = item.FirstName;
                            }
                            if (string.IsNullOrEmpty(person.FirstName) && !string.IsNullOrEmpty(item.LastName))
                            {
                                person.LastName = item.LastName;
                            }
                        }
                    }

                    person.Rating  = item.Rating;
                    person.Rank    = item.Rank;
                    person.Grade   = Grade.Parse(item.Grade);
                    person.Comment = item.Comment;

                    if (!string.IsNullOrEmpty(item.City))
                    {
                        string nm   = item.City == null ? string.Empty : item.City.Trim();
                        string nmUa = item.CityUa == null ? string.Empty : item.CityUa.Trim();
                        if (!string.IsNullOrEmpty(nm))
                        {
                            var club = result.Clubs.Find(fnd =>
                                                         string.Compare(fnd.Name, nm, true) == 0 ||
                                                         string.Compare(fnd.NameUa, nm, true) == 0);

                            if (club == null)
                            {
                                club    = new RatingSystem.Club();
                                club.Id = result.Clubs.Count + 1;

                                club.Name   = nm;
                                club.NameUa = nmUa;

                                result.Clubs.Add(club);
                            }
                            else
                            {
                                //Update Names
                                if (string.Compare(club.Name, nm, true) == 0)
                                {
                                    if (string.IsNullOrEmpty(club.NameUa) && !string.IsNullOrEmpty(nmUa))
                                    {
                                        club.NameUa = nmUa;
                                    }
                                }
                                else
                                {
                                    if (string.IsNullOrEmpty(club.Name) && !string.IsNullOrEmpty(nm))
                                    {
                                        club.Name = nm;
                                    }
                                }
                            }

                            person.ClubId = club.Id;
                        }
                    }

                    string date = !string.IsNullOrEmpty(item.Date) ? item.Date : lst.Date;
                    if (!string.IsNullOrEmpty(date))
                    {
                        string[] arr = date.Split('.');
                        if (arr.Length > 2)
                        {
                            int y = 0;
                            int m = 0;
                            int d = 0;
                            if (int.TryParse(arr[2], out y) &&
                                int.TryParse(arr[1], out m) &&
                                int.TryParse(arr[0], out d))
                            {
                                var      prev = result.Ratings.Find(fnd => fnd.PersonId == person.Id);
                                DateTime dt   = new DateTime(y, m, d);
                                if (!(prev != null && prev.Rating == item.Rating))
                                {
                                    if (result.Ratings.Find(fnd => fnd.PersonId == person.Id && fnd.Date == dt) == null)
                                    {
                                        result.Ratings.Add(new RatingSystem.RatingRec()
                                        {
                                            Date = dt, Rating = item.Rating, PersonId = person.Id
                                        });
                                        result.Date = lst.Date;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            result.Clubs.Sort(delegate(RatingSystem.Club item1, RatingSystem.Club item2) { return(string.Compare(item1.Name, item2.Name)); });
            result.Persons.Sort(delegate(RatingSystem.Person item1, RatingSystem.Person item2)
            {
                int r = string.Compare(item1.LastName, item2.LastName);
                if (r == 0)
                {
                    r = string.Compare(item1.FirstName, item2.FirstName);
                }
                return(r);
            });
            result.Ratings.Sort(delegate(RatingSystem.RatingRec item1, RatingSystem.RatingRec item2)
            {
                int r = item1.PersonId - item2.PersonId;
                if (r == 0)
                {
                    r = string.Compare(item2.DateStr, item1.DateStr, true);
                }
                return(r);
            });

            Save(result);
            return(result);
        }