Example #1
1
        public static int GetCurrentPeriodId(IList<Period> periods)
        {
            int currentMonth = DateTime.Now.Month;

            switch (currentMonth)
            {
                case 1:
                case 2:
                case 3:
                    return periods.Single(p => p.NumberGym == 3).Id;
                case 4:
                case 5:
                case 6:
                    return periods.Single(p => p.NumberGym == 4).Id;
                case 7:
                case 8:
                case 9:
                    return periods.Single(p => p.NumberGym == 1).Id;
                case 10:
                case 11:
                case 12:
                    return periods.Single(p => p.NumberGym == 2).Id;
                default:
                    return 0;
            }
        }
Example #2
1
        public static IList<IJigsawPiece> ScramblePieces(IList<IJigsawPiece> pieces, int rows, int cols)
        {
            var random = new Random();
            var temp = new List<KeyValuePair<int, int>>();
            foreach (JigsawPieceBase originPiece in pieces)
            {
                int row = random.Next(0, rows);
                int col = random.Next(0, cols);

                while (temp.Exists(t => (t.Key == row) && (t.Value == col)))
                {
                    row = random.Next(0, rows);
                    col = random.Next(0, cols);
                }
                temp.Add(new KeyValuePair<int, int>(row, col));
                IJigsawPiece targetPiece = pieces.Single(p => p.OriginRow == row && p.OriginColumn == col);

                //swap positions
                var tempPoint = new Point(originPiece.Position.X, originPiece.Position.Y);
                originPiece.Position = new Point(targetPiece.Position.X, targetPiece.Position.Y);
                targetPiece.Position = tempPoint;

                //Swap column and row numbers
                int targetColumn = targetPiece.CurrentColumn;
                int targetRow = targetPiece.CurrentRow;
                targetPiece.CurrentColumn = originPiece.CurrentColumn;
                targetPiece.CurrentRow = originPiece.CurrentRow;
                originPiece.CurrentColumn = targetColumn;
                originPiece.CurrentRow = targetRow;
            }
            return pieces;
        }
Example #3
1
        public virtual VoucherInformation GetPrimeCredit(IList<VoucherInformation> vouchers)
        {
            int numberOfCredit = vouchers.Count(v => v.voucher.documentType == DocumentTypeEnum.Cr);

            if (numberOfCredit == 1)
            {
                return vouchers.Single(v => v.voucher.documentType == DocumentTypeEnum.Cr);
            }
            else if (numberOfCredit > 1)
            {
                var creditVouchers = vouchers.Where(v => v.voucher.documentType == DocumentTypeEnum.Cr);

                if (creditVouchers.Any(v => !string.IsNullOrEmpty(v.GetExtraAuxDom())))
                {
                    return creditVouchers.Last(v => !string.IsNullOrEmpty(v.GetExtraAuxDom()));
                }
                else if (creditVouchers.Any(v => !string.IsNullOrEmpty(v.GetAuxDom())))
                {
                    return creditVouchers.Last(v => !string.IsNullOrEmpty(v.GetAuxDom()));
                }
                else
                {
                    return creditVouchers.Last();
                }
            }

            return null;
        }
Example #4
1
        public static Geopoint GetCentralGeopoint(IList<Geopoint> geoPoints)
        {
            if (geoPoints.Count == 1)
            {
                return geoPoints.Single();
            }

            double x = 0;
            double y = 0;
            double z = 0;

            foreach (var geopoint in geoPoints)
            {
                var latitude = geopoint.Position.Latitude * Math.PI / 180;
                var longitude = geopoint.Position.Longitude * Math.PI / 180;

                x += Math.Cos(latitude) * Math.Cos(longitude);
                y += Math.Cos(latitude) * Math.Sin(longitude);
                z += Math.Sin(latitude);
            }

            var total = geoPoints.Count;

            x = x / total;
            y = y / total;
            z = z / total;

            var centralLongitude = Math.Atan2(y, x);
            var centralSquareRoot = Math.Sqrt(x * x + y * y);
            var centralLatitude = Math.Atan2(z, centralSquareRoot);

            return new Geopoint(new BasicGeoposition { Latitude = centralLatitude * 180 / Math.PI, Longitude = centralLongitude * 180 / Math.PI });
        }
 private static IEnumerable<PlayerGameweekPerformance> RetrievePlayerPerformances(IEnumerable<int> playerIds, int gameweek, IList<Player> upToDatePlayers)
 {
     foreach (var playerId in playerIds)
     {
         int id = playerId;
         var upToDatePlayer = upToDatePlayers.Single(x => x.Id == id);
         var gameweekFixtures =
             upToDatePlayer.PastFixtures.Where(x => x.GameWeek == gameweek);
         yield return PerformanceMappingHelper.CreatePlayerPerformanceFromFixtures(upToDatePlayer.Id, upToDatePlayer.Name, upToDatePlayer.Position, gameweekFixtures);
     }
 }
Example #6
1
        private string GetJobDependencies(Job current, string result, IList<Job> jobs)
        {
            if (result.Contains(current.Name))
                return "";
            if (string.IsNullOrEmpty(current.DependencyName))
                return current.Name;

            ThrowIfCircularDependencyFound(current);

            return GetJobDependencies(jobs.Single(x => x.Name == current.DependencyName), result, jobs) + current.Name;
        }
Example #7
1
 private void AddRecursive(IList<NavigationNode> navigationNodes, NavigationNode toAdd)
 {
     if (navigationNodes.Contains(toAdd))
     {
         foreach (var node in toAdd.Children)
         {
             AddRecursive(navigationNodes.Single(x => x.Name == toAdd.Name).Children, node);
         }
     }
     else
         navigationNodes.Add(toAdd);
 }
        /// <summary>
        /// Verifies that the resulting java model matches our expectations.
        /// </summary>
        private void VerifyJavaModel(
            IList<JavaClass> expectedModel,
            IList<JavaClass> actualModel)
        {
            Assert.Equal(expectedModel.Count, actualModel.Count);

            foreach (var actualJavaClass in actualModel)
            {
                var expectedJavaClass = expectedModel
                    .Single(c => c.Type == actualJavaClass.Type);

                VerifyJavaClass(expectedJavaClass, actualJavaClass);
            }
        }
Example #9
1
        public HangmanGame(string solution)
        {
            Answer = solution;
            Id = Guid.NewGuid();

            _alphabet = "abcdefghijklmnopqrstuvwxyz ".ToArray()
                .Select(letter => new Tile { Letter = letter.ToString() })
                .ToArray();

            _alphabet.Single(t => t.Letter == " ").State = TileState.Hit;

            _solution = solution.ToArray()
                .Select(letter => _alphabet.FirstOrDefault(t => t.Letter == letter.ToString()))
                .ToArray();
        }
Example #10
1
        private void SyncRoles(IList<RoleCheckbox> checkboxes, IList<RoleNames> roles)
        {
            var selectedRoles = new List<RoleNames>();
            foreach (var role in Database.Session.Query<RoleNames>())
            {
                var checkbox = checkboxes.Single(c => c.Id == role.Id);
                checkbox.Role = role.Role;

                if (checkbox.IsChecked)
                    selectedRoles.Add(role);
            }
            foreach (var toAdd in selectedRoles.Where(t => !roles.Contains(t)))
                roles.Add(toAdd);

            foreach (var toRemove in roles.Where(t => !selectedRoles.Contains(t)).ToList())
                roles.Remove(toRemove);
        }
        public Team AdjustTeamToGameweek(Team team, IList<Player> allUpToDatePlayers, int gameweek)
        {
            if (team == null) throw new ArgumentNullException("team");
            if (gameweek < 1 || gameweek > 38) throw new ArgumentException("gameweek");
            if (allUpToDatePlayers == null) throw new ArgumentNullException("allUpToDatePlayers");

            _logger.Log(Tag.Adjusting, string.Concat("Adjusting team to gameweek ", gameweek));

            var updatedTeam = new Team();

            foreach (var playerInTeam in team.Players)
            {
                //find player that is up to date to adjust
                Player inTeam = playerInTeam;

                var playerToAdjust = allUpToDatePlayers.Single(x => x.Id == inTeam.Id);

                //bring them back to the current gameweek
                var adjustedPlayer = AdjustPlayer(playerToAdjust, gameweek);

                if(adjustedPlayer.NowCost != playerInTeam.NowCost)
                {
                    _logger.Log(Tag.Adjusting, string.Format("{0} value has {1} from {2} to {3}", playerInTeam.Name, adjustedPlayer.NowCost > playerInTeam.NowCost ? "increased" : "decreased", playerInTeam.NowCost.ToMoney(), adjustedPlayer.NowCost.ToMoney()));
                }

                //now copy over anything that is special about a player being in your team

                //todo: check this is correct when we find out property for purchase cost
                adjustedPlayer.OriginalCost = playerInTeam.OriginalCost;

                updatedTeam.Players.Add(adjustedPlayer);
            }

            //now switch over captains
            updatedTeam.Captain = updatedTeam.Players.Single(p => p.Id == team.Captain.Id);
            updatedTeam.ViceCaptain = updatedTeam.Players.Single(p => p.Id == team.ViceCaptain.Id);

            return updatedTeam;
        }
Example #12
1
        public RoomViewModel(MainViewModel mainViewModel, Room room, IList<User> users)
            : base(true)
        {
            Description = room;
              MainViewModel = mainViewModel;
              Messages = new ObservableCollection<MessageViewModel>();
              allInRoom = new UserViewModel(new User("Все в комнате", Color.Black), this);
              messageIds = new HashSet<long>();
              Users = new ObservableCollection<UserViewModel>(users == null
            ? Enumerable.Empty<UserViewModel>()
            : room.Users.Select(user => new UserViewModel(users.Single(u => u.Equals(user)), this)));

              SendMessageCommand = new Command(SendMessage, Obj => ClientModel.Client != null);
              PastReturnCommand = new Command(PastReturn);
              AddFileCommand = new Command(AddFile, Obj => ClientModel.Client != null);
              InviteInRoomCommand = new Command(InviteInRoom, Obj => ClientModel.Client != null);
              KickFromRoomCommand = new Command(KickFromRoom, Obj => ClientModel.Client != null);
              ClearSelectedMessageCommand = new Command(ClearSelectedMessage, Obj => ClientModel.Client != null);

              MainViewModel.AllUsers.CollectionChanged += AllUsersCollectionChanged;
              NotifierContext.ReceiveMessage += ClientReceiveMessage;
              NotifierContext.RoomRefreshed += ClientRoomRefreshed;
        }
Example #13
1
        public static void Sync(IList<RoleCheckBox> checkBoxes, IList<Role> userRoles)
        {
            var selectedRoles = new List<Role>();

            foreach (var role in Database.Session.Query<Role>())
            {
                var checkBox = checkBoxes.Single(c => c.Id == role.Id);

                checkBox.Name = role.Name;

                if (checkBox.IsChecked)
                    selectedRoles.Add(role);
            }

            foreach (var roleToAdd in selectedRoles.Where(sr => !userRoles.Contains(sr)))
            {
                userRoles.Add(roleToAdd);
            }

            foreach (var roleToRemove in userRoles.Where(cr => !selectedRoles.Contains(cr)).ToList())
            {
                userRoles.Remove(roleToRemove);
            }
        }
Example #14
1
        public virtual void UpdateFromSeriesEditor(IList<Series> editedSeries)
        {
            var allSeries = GetAllSeries();

            foreach(var series in allSeries)
            {
                //Only update parameters that can be changed in MassEdit
                var edited = editedSeries.Single(s => s.SeriesId == series.SeriesId);
                series.QualityProfileId = edited.QualityProfileId;
                series.Monitored = edited.Monitored;
                series.SeasonFolder = edited.SeasonFolder;
                series.BacklogSetting = edited.BacklogSetting;
                series.Path = edited.Path;
            }

            _database.UpdateMany(allSeries);
        }
        public async Task<IList<DiagnosisResultDTO>> Process(IList<FuzzySymptomDTO> symptomes)
        {
            var symptomIds = symptomes.Select(s => s.SymptomId).ToArray();

            var diagnosesRepo = _unitOfWork.RepositoryAsync<Diagnosis>();
            var diagnosis = diagnosesRepo.Query(d => d.Symptoms.Any(s => symptomIds.Any(id => id == s.SymptomId))).Select().Distinct().OrderBy(d => d.Id).ToList();
            var diagnosesIds = diagnosis.Select(d => d.Id).ToArray();

            var IS = await InitFuzzyEngineDiagnosis(symptomIds, diagnosesIds);

            var symptomRepo = _unitOfWork.RepositoryAsync<Symptom>();
            var symptoms = await symptomRepo.Queryable().Where(s => symptomIds.Any(sId => sId == s.Id)).ToListAsync();
            foreach(var s in symptoms)
            {
                var fuzzySymptom = symptomes.Single(fs => fs.SymptomId == s.Id);
                var fuzzy = fuzzySymptom.FuzzySet != null ? fuzzySymptom.FuzzySet : SymptomFuzzySet.Common;
                var average = (fuzzy.RightLimit + fuzzy.LeftLimit) / 2;
                try
                {
                    IS.SetInput(s.Name, average);
                }
                catch(Exception exc)
                {

                }
            }

            var result = new List<DiagnosisResultDTO>();

            var evaluate = IS.Evaluate("Diagnosis");

            var i = 0;
            foreach (var diagnoses in diagnosis)
            {
                i++;

                var predel = new Tuple<int, int>(i > 1 ? (i - 1) * 100 : -1, i * 100);

                if(predel.Item1 <= (int)evaluate && predel.Item2 >= (int)evaluate)
                {
                    result.Add(new DiagnosisResultDTO
                    {
                        DiagnosisId = diagnoses.Id,
                        DiagnosisName = diagnoses.DisplayName,
                        Coefficient = 100//TODO:
                    });
                    break;
                }
                //try
                //{
                //    result.Add(new DiagnosisResultDTO {
                //        DiagnosisId = diagnoses.Id,
                //        DiagnosisName = diagnoses.DisplayName,
                //        Coefficient = IS.Evaluate(diagnoses.Name)
                //    });
                //}
                //catch(Exception exc)
                //{

                //}
            }

            return result;
        }
Example #16
0
 private QueryNode MergeResultsIntoQueryNode(IList<QueryConditionNodeResult> mergedLeafNodes, QueryNode originalQueryNode)
 {
     if (originalQueryNode is QueryGroupNode) {
         var qng = originalQueryNode as QueryGroupNode;
         for (var i = 0; i < qng.Nodes.Count; ++i) {
             if (qng.Nodes[i] is QueryGroupNode) {
                 qng.Nodes[i] = MergeResultsIntoQueryNode(mergedLeafNodes, qng.Nodes[i]);
             } else {
                 var qnr = qng.Nodes[i] as QueryConditionNode;
                 qng.Nodes[i] = mergedLeafNodes.Single(mn => mn.Id == qnr.Id);
             }
         }
         return qng;
     } else {
         return mergedLeafNodes.Single(mn => mn.Id == (originalQueryNode as QueryConditionNode).Id);
     }
 }
        internal static async Task<IEnumerable<CodeActionOperation>> VerifyInputsAndGetOperationsAsync(
            int index, IList<CodeAction> actions, CodeActionPriority? priority = null)
        {
            Assert.NotNull(actions);
            if (actions.Count == 1)
            {
                var suppressionAction = actions.Single() as SuppressionCodeAction;
                if (suppressionAction != null)
                {
                    actions = suppressionAction.GetCodeActions().ToList();
                }
            }

            Assert.InRange(index, 0, actions.Count - 1);

            var action = actions[index];
            if (priority != null)
            {
                Assert.Equal(priority.Value, action.Priority);
            }
            return await action.GetOperationsAsync(CancellationToken.None);
        }
Example #18
0
            public Reign.Unit ToUnit(IList<UnitData> data)
            {
                var uData = data.Single(u => u.ID == _id);

                return new Reign.Unit(uData, _rank, _exp, _obCount) {
                    Acted = _acted
                };
            }
Example #19
0
        private static void PopulateStorage(IList<Tuple<IOverlayNodeService, IOverlayStorageService>> p2pServices, ServiceDescription[] serviceDescriptions, int? avgRegistrationsPerSecond)
        {
            var newStats = new Statistics();

            System.Console.WriteLine("Populating the data storage...");
            DbMgr.Clear();

            newStats.NodesCount = p2pServices.Count;
            newStats.AVPairsCount = serviceDescriptions.SelectMany(x => x.Data.Select(y => y.AttrValue)).Count();
            newStats.AvgRegistrationsPerSecond = avgRegistrationsPerSecond;

            foreach (var srv in serviceDescriptions) {
                srv.OwnerNode = p2pServices.Select(p => p.Item1.Node).ElementAt(Rnd.Next(p2pServices.Count()));

                var ownerNodeStorageSrv = p2pServices.Single(s => s.Item2.Node.Equals(srv.OwnerNode)).Item2;
                var putSrvResult = ownerNodeStorageSrv.PutService(srv);
                if (!putSrvResult) {
                    newStats.ServiceRegistrationFailsCount++;
                }
                if (avgRegistrationsPerSecond.HasValue) {
                    Thread.Sleep((int)Math.Round(GetPoissonInterarrivalDelay(avgRegistrationsPerSecond.Value) * 1000));
                }
            }

            var allServices = new Dictionary<long, ServiceDescription[]>();
            foreach (var storageSrv in p2pServices.Select(x => x.Item2)) {
                allServices.Add(storageSrv.Node.Id, storageSrv.GetServicesLocal());
            }

            newStats.NodesOverAVThresholdCount = allServices.Count(x => x.Value.Any(y => y.StorageState == ServiceStorageState.Failed));

            Stats.Add(newStats);
            System.Console.WriteLine("Populating the data storage - Finished");
        }
Example #20
0
        /*
         导入结构:
         * 总目录-|
         *        -供应商-|
         *                -图片文件夹
         *                -产品数据.xls
         *
         * 结果目录:
         *  总目录-
         *        --合格数据
         *        --不合格数据
         *               --供应商
         *                   --没有产品信息的图片
         *                   --没有图片的产品.xls
         */
        /// <summary>
        /// 将结果保存到磁盘:
        /// </summary>
        /// <param name="productHasImages"></param>
        public void HandlerCheckResult(string supplierName, IList<Product> productHasImages, IList<Product> productNotHasImages,
            IList<Product> productsExistedInDb,
            IList<FileInfo> imagesHasProduct, IList<FileInfo> imagesNotHasProduct,
            string outputFolder)
        {
            DirectoryInfo dirRoot = new DirectoryInfo(outputFolder);
            DataExport transfer = new DataExport();
            DataSet ds = new DataSet();
            //如果没有合格数据 则不需要创建
            if (productHasImages.Count > 0)
            {
                DirectoryInfo dirQuanlified = IOHelper.EnsureDirectory(outputFolder + "合格数据\\");
                DirectoryInfo dirSupplierQuanlified = IOHelper.EnsureDirectory(dirQuanlified.FullName + supplierName + "\\");
                DirectoryInfo dirSupplierQuanlifiedImages = IOHelper.EnsureDirectory(dirSupplierQuanlified.FullName + supplierName + "\\");
                foreach (Product product in productHasImages)
                {
                    try
                    {
                        FileInfo imageFile = imagesHasProduct.Single(x => StringHelper.ReplaceSpace(Path.GetFileNameWithoutExtension(x.Name))
                          .Equals(StringHelper.ReplaceSpace(product.ModelNumber), StringComparison.OrdinalIgnoreCase));
                        File.Copy(imageFile.FullName, dirSupplierQuanlified.FullName + supplierName + "\\" + imageFile.Name, true);

                    }
                    catch (Exception ex)
                    {
                        throw new Exception("图片复制出错:" + dirSupplierQuanlified.FullName + "---" + product.ModelNumber + "---" + ex.Message);
                    }
                }

                DataTable dtProductsHasImage = ObjectConvertor.ToDataTable<Product>(productHasImages);
                ds.Clear();
                ds.Tables.Add(dtProductsHasImage);
                transfer.DataToExport = ds;
                transfer.SaveWorkBook(dirSupplierQuanlified.FullName + "\\" + supplierName + ".xls");
            }

            //没有图片的产品
            string dirPathNotQuanlified = outputFolder + "不合格数据\\";
            string dirPathSupplierNotQuanlified = dirPathNotQuanlified + supplierName + "\\";
            if (productNotHasImages.Count > 0)
            {
                DirectoryInfo dirSupplierNotQuanlified = IOHelper.EnsureDirectory(dirPathSupplierNotQuanlified);
                DataTable dtProductsNotHasImage = ObjectConvertor.ToDataTable<Product>(productNotHasImages);
                ds.Clear();
                ds.Tables.Add(dtProductsNotHasImage);
                transfer.DataToExport = ds;
                transfer.SaveWorkBook(dirSupplierNotQuanlified + "没有图片的数据_" + supplierName + ".xls");

            }
            //没有产品的图片
            if (imagesNotHasProduct.Count > 0)
            {

                string dirPathSupplierNotQuanlifiedImages = dirPathSupplierNotQuanlified + "多余图片_" + supplierName + "\\";
                DirectoryInfo dirSupplierNotQuanlifiedImages = IOHelper.EnsureDirectory(dirPathSupplierNotQuanlifiedImages);
               foreach (FileInfo file in imagesNotHasProduct)
                {
                    file.CopyTo(dirSupplierNotQuanlifiedImages + file.Name, true);
                }
            }
            //多余的图片

            //重复数据
            if (productsExistedInDb.Count > 0)
            {
                string dirPathSupplierRepeated = dirPathSupplierNotQuanlified + "数据库内已存在的数据_" + supplierName + "\\";
                DirectoryInfo dirSupplierRepeated = IOHelper.EnsureDirectory(dirPathSupplierRepeated);

                DataTable dtProductsRepeated = ObjectConvertor.ToDataTable<Product>(productsExistedInDb);
                ds.Clear();
                ds.Tables.Add(dtProductsRepeated);
                transfer.DataToExport = ds;
                transfer.SaveWorkBook( dirSupplierRepeated.FullName+"\\" + supplierName + ".xls");
            }
        }
        private static void InitAccounts()
        {
            Accounts = new List<Account>
            {
               
                new PremiumAccount()
                {
                    Id = 1,
                    Name = "Name1",
                    AccountInfo = new AccountInfo()
                    {
                        NickName = "NickName1"
                    },
                    Address = new GlobalAddress()
                    {
                        City = "Redmond",
                        Street = "1 Microsoft Way",
                        CountryCode="US"
                    },
                    Tags = new Tags(),
                    Since=new DateTimeOffset(new DateTime(2014,5,22),TimeSpan.FromHours(8)),
                },
                new Account()
                {
                    Id = 2,
                    Name = "Name2",
                    AccountInfo = new AccountInfo()
                    {
                        NickName = "NickName2"
                    },
                    Address =  new Address()
                    {
                        City = "Shanghai",
                        Street = "Zixing Road"
                    },
                    Tags = new Tags()
                },
                new Account()
                {
                    Id = 3,
                    Name = "Name3",
                    AccountInfo = new AccountInfo()
                    {
                        NickName = "NickName3"
                        
                    },
                    Address = new Address()
                    {
                        City = "Beijing",
                        Street = "Danling Street"
                    },
                    Tags = new Tags()
                }
            };

            Account account = Accounts.Single(a => a.Id == 1);
            account.DynamicProperties["OwnerAlias"] = "jinfutan";
            account.DynamicProperties["OwnerGender"] = Gender.Female;
            account.DynamicProperties["IsValid"] = true;
            account.DynamicProperties["ShipAddresses"] = new List<Address>(){
                new Address
                {
                    City = "Beijing",
                    Street = "Danling Street"
                },
                new Address
                {
                    City="Shanghai",
                    Street="Zixing",
                }
            };

            Accounts[0].AccountInfo.DynamicProperties["Age"] = 10;

            Accounts[0].AccountInfo.DynamicProperties["Gender"] = Gender.Male;

            Accounts[0].AccountInfo.DynamicProperties["Subs"] = new string[] { "Xbox", "Windows", "Office" };

            Accounts[0].Address.DynamicProperties["Country"] = "US";
            Accounts[0].Tags.DynamicProperties["Tag1"] = "Value 1";
            Accounts[0].Tags.DynamicProperties["Tag2"] = "Value 2";

            Accounts[1].AccountInfo.DynamicProperties["Age"] = 20;

            Accounts[1].AccountInfo.DynamicProperties["Gender"] = Gender.Female;

            Accounts[1].AccountInfo.DynamicProperties["Subs"] = new string[] { "Xbox", "Windows" };

            Accounts[1].Address.DynamicProperties["Country"] = "China";
            Accounts[1].Tags.DynamicProperties["Tag1"] = "abc";

            Accounts[2].AccountInfo.DynamicProperties["Age"] = 30;

            Accounts[2].AccountInfo.DynamicProperties["Gender"] = Gender.Female;

            Accounts[2].AccountInfo.DynamicProperties["Subs"] = new string[] { "Windows", "Office" };

            Accounts[2].Address.DynamicProperties["Country"] = "China";
        }
 private void CheckFieldValues(int size, int[][] expectedValues, IList<Field> fieldList)
 {
     for (int i = 0; i < size; i++)
     {
         for (int j = 0; j < size; j++)
         {
             fieldList.Single(f => f.Row == i && f.Column == j).Value.Should().Be(expectedValues[i][j], string.Format("{0}/{1}", i, j));
         }
     }
 }
        /// <summary>
        /// Syncs selected roles in front-end to user roles in database
        /// </summary>
        /// <param name="checkboxes">Roles selected in frontend</param>
        /// <param name="roles">Roles already assigned to user</param>
        private void SyncRoles(IList<RoleCheckbox> checkboxes, IList<Role> roles)
        {
            List<Role> selectedRoles = new List<Role>();

            foreach (Role role in DatabaseManager.Session.Query<Role>().ToList())
            {
                // Get the checkbox that matches the role id
                RoleCheckbox checkbox = checkboxes.Single(c => c.Id == role.Id);

                if (checkbox.IsChecked)
                {
                    checkbox.RoleName = role.RoleName;
                    selectedRoles.Add(role);
                }
            }

            // Add roles which were selected and not contained already in user roles
            foreach (var toAdd in selectedRoles.Where(r => !roles.Contains(r)).ToList())
                roles.Add(toAdd);

            // Remove roles which were de-selected
            foreach (var toRemove in roles.Where(r => !selectedRoles.Contains(r)).ToList())
                roles.Remove(toRemove);
        }
        protected static IEnumerable<CodeActionOperation> VerifyInputsAndGetOperations(int index, IList<CodeAction> actions)
        {
            Assert.NotNull(actions);
            if (actions.Count == 1)
            {
                var suppressionAction = actions.Single() as SuppressionCodeAction;
                if (suppressionAction != null)
                {
                    actions = suppressionAction.NestedActions.ToList();
                }
            }

            Assert.InRange(index, 0, actions.Count - 1);

            var action = actions[index];
            return action.GetOperationsAsync(CancellationToken.None).Result;
        }
Example #25
0
        /// <summary>
        /// Generates SriptSharp files
        /// </summary>
        /// <param name="entries">List of jQueryUI entries.</param>
        public void Render(IList<Entry> entries)
        {
            if (entries == null) {
                return;
            }

            DirectoryInfo destination = new DirectoryInfo(DestinationPath);
            if (destination.Exists) {
                destination.Delete(true);
            }

            foreach (Entry entry in entries) {
                Messages.WriteLine("Generating " + Path.Combine(DestinationPath, Utils.PascalCase(entry.Name)));

                Entry baseEntry = null;
                if (!string.IsNullOrEmpty(entry.Type)) {
                    // find the base entry
                    baseEntry = entries.SingleOrDefault(e => e.Name.ToLowerInvariant() == entry.Type.ToLowerInvariant());
                }

                RenderEntry(entry, baseEntry);
            }

            Messages.WriteLine("Generating jQueryUI base files.");
            RenderEventHandler();
            RenderBox();
            RenderSize();
            RenderEffectExtensionMethods(entries.Where(e => e.Category == "effects" && e.Name != "effect"));
            RenderInteractionOrWidgetExtensionMethods("Interaction", entries.Where(e => e.Category == "interactions"));
            RenderInteractionOrWidgetExtensionMethods("Widget", entries.Where(e => e.Category == "widgets" && e.Name != "widget"));
            RenderPositionExtensionMethods(entries.Single(e => e.Name == "position"));
        }
Example #26
0
        public void SetUpTests()
        {
            _newItem = GetProduct();
            _allProducts = GetProducts();

            // Mock repository
            _mockProductRepo = new Mock<IProductRepository>();

            // Get
            _mockProductRepo.Setup(c => c.GetAll()).Returns(_allProducts);

            // GetById
            _mockProductRepo
                .Setup(mr => mr.FindById(It.IsAny<int>()))
                .Returns((int i) => _allProducts.Single(x => x.ID == i));

            _service = new ProductService(
                    CompositionService,
                    _mockProductRepo.Object
                );
        }
        public async Task<IList<BuildUpdate>> CheckForUpdatedBuilds(IList<SubscribedBuild> subscribedBuilds)
        {
            List<List<SubscribedBuild>> groupedBuilds = subscribedBuilds.GroupBy(b => new
            {
                b.AccountDetails.AccountName,
                b.AccountDetails.ProjectId
            })
            .Select(grp => grp.ToList())
            .ToList();

            var updates = new List<BuildUpdate>();

            foreach (List<SubscribedBuild> groupedBuild in groupedBuilds)
            {
                IList<Build> buildsForAccount =
                    await
                        _vsoClient.GetBuilds(groupedBuild.First().AccountDetails,
                            groupedBuild.Select(g => g.BuildDefinitionId).ToList());
            
                List<List<Build>> buildsByDefinition = buildsForAccount
                    .GroupBy(b => b.BuildDefinitionId)
                    .Select(grp => grp.ToList())
                    .ToList();

                foreach (List<Build> buildList in buildsByDefinition)
                {
                    if (!buildList.Any()) continue;
                    
                    SubscribedBuild subscribedBuildToUpdate = subscribedBuilds.Single(sb => sb.BuildDefinitionId == buildList.First().BuildDefinitionId);
                    updates.AddRange(CheckForUpdateInternal(buildList, subscribedBuildToUpdate));
                }
            }

            SaveSubscribedBuilds(subscribedBuilds);

            if (!GetNotifyOnStart())
            {
                updates.RemoveAll(u => u.Result == null);
            }

            if (!GetNotifyOnFinish())
            {
                updates.RemoveAll(u => u.Result != null);
            }

            return updates;
        }
Example #28
0
            public void OverrideData(Reign.Area area, IList<Reign.Province> provs, IList<UnitData> data)
            {
                var prov = provs.Single(p => p.No == _provNo);
                area.Province = prov;

                area.NumCity100 = _nCity;
                area.NumRoad100 = _nRoad;
                area.NumWall100 = _nWall;

                area.Units.Clear();
                area.Units.AddRange(_units.Select(u => u.ToUnit(data)));
            }
Example #29
0
        public BuildingModel(SiteContext context, string categoryId, string subCategoryId, int contentType, string articleId=null)
            : base(context, null)
        {
            _categoryId = categoryId;
            _subCategoryId = subCategoryId;
            _contentId = subCategoryId ?? categoryId;

            _buildings = context.Building.Include("Children").Include("BuildingItems").Where(b => b.ContentType == contentType).ToList();

            if (categoryId != null)
                if (subCategoryId == null)
                    ParentTitle = _buildings.Single(t => t.CategoryLevel == 0).Title;

            Building = _buildings.FirstOrDefault(t => t.Name == _contentId) ?? _buildings.First(t => t.CategoryLevel == 0);




            if (!HttpContext.Current.Request.IsAuthenticated)
            {
                if (Building.CategoryLevel == 0 && !Building.Active)
                {
                    Building = _buildings.Where(t => t.Parent == null && t.CategoryLevel != 0).Where(t => t.SortOrder == _buildings.Min(c => (int?)c.SortOrder)).FirstOrDefault();
                    //Building = _buildings.FirstOrDefault(t => t.Parent == null && t.CategoryLevel != 0);
                    if (Building != null)
                    {
                        ActiveCategoryNotFound = true;
                        RedirectCategoryId = Building.Name;
                        return;
                    }
                }
                if (Building != null)
                {
                    if (Building.CategoryLevel != 0 && !Building.Active && Building.Children.Any())
                    {
                        ActiveCategoryNotFound = true;
                        RedirectCategoryId = Building.Name;
                        RedirectSubCategoryId = Building.Children.First().Name;
                        return;
                    }
                }
            }

            if (Building != null)
            {
                if (Building.Parent != null)
                {
                    ParentTitle = Building.Parent.Title;
                }
                SeoDescription = Building.SeoDescription;
                SeoKeywords = Building.SeoKeywords;
            }
            GetMenu();
            if (contentType == 1)
            {
                BuildingObjects = context.BuildingObj.ToList();
            }


            if (articleId != null)
                Article = context.Article.First(a => a.Name == articleId);
        }
        public string GenerateManifest(string dlcName, IList<Arrangement> arrangements, SongInfo songInfo, Platform platform)
        {
            var manifest = Manifest;
            manifest.Entries = new Dictionary<string, Dictionary<string, Attributes>>();
            bool firstarrangset = false;

            Arrangement vocal = null;
            if (arrangements.Any<Arrangement>(a => a.ArrangementType == Sng.ArrangementType.Vocal))
                vocal = arrangements.Single<Arrangement>(a => a.ArrangementType == Sng.ArrangementType.Vocal);

            var manifestFunctions = new ManifestFunctions(platform.version);
            var songPartition = new SongPartition();

            foreach (var x in arrangements)
            {
                var isVocal = x.ArrangementType == Sng.ArrangementType.Vocal;
                var song = (isVocal) ? null : Song.LoadFromFile(x.SongXml.File);

                var attribute = new Attributes();
                attribute.AlbumArt = String.Format("urn:llid:{0}", AggregateGraph.AlbumArt.LLID);
                attribute.AlbumNameSort = attribute.AlbumName = songInfo.Album;
                attribute.ArrangementName = x.Name.ToString();
                attribute.ArtistName = songInfo.Artist;
                attribute.ArtistNameSort = songInfo.ArtistSort;
                attribute.AssociatedTechniques = new List<string>();
                //Should be 51 for bass, 49 for vocal and guitar
                attribute.BinaryVersion = x.ArrangementType == Sng.ArrangementType.Bass ? 51 : 49;
                attribute.BlockAsset = String.Format("urn:emergent-world:{0}", AggregateGraph.XBlock.Name);
                attribute.ChordTemplates = null;
                attribute.DISC_DLC_OTHER = "Disc";
                attribute.DisplayName = songInfo.SongDisplayName;
                attribute.DLCPreview = false;
                attribute.EffectChainMultiplayerName = string.Empty;
                attribute.EffectChainName = isVocal ? "" : (dlcName + "_" + x.ToneBase == null ? "Default" : x.ToneBase.Replace(' ', '_'));
                attribute.EventFirstTimeSortOrder = 9999;
                attribute.ExclusiveBuild = new List<object>();
                attribute.FirstArrangementInSong = false;
                if (isVocal && !firstarrangset)
                {
                    firstarrangset = true;
                    attribute.FirstArrangementInSong = true;
                }
                attribute.ForceUseXML = true;
                attribute.Tag = "PLACEHOLDER Tag";
                attribute.InputEvent = isVocal ? "Play_Tone_Standard_Mic" : "Play_Tone_";
                attribute.IsDemoSong = false;
                attribute.IsDLC = true;
                attribute.LastConversionDateTime = "";
                int masterId = isVocal ? 1 : x.MasterId;
                attribute.MasterID_PS3 = masterId;
                attribute.MasterID_Xbox360 = masterId;
                attribute.MaxPhraseDifficulty = 0;
                attribute.PersistentID = x.Id.ToString().Replace("-", "").ToUpper();
                attribute.PhraseIterations = new List<PhraseIteration>();
                attribute.Phrases = new List<Phrase>();
                attribute.PluckedType = x.PluckedType == Sng.PluckedType.Picked ? "Picked" : "Not Picked";
                attribute.RelativeDifficulty = isVocal ? 0 : song.Levels.Count();
                attribute.RepresentativeArrangement = false;
                attribute.Score_MaxNotes = 0;
                attribute.Score_PNV = 0;
                attribute.Sections = new List<Section>();
                attribute.Shipping = true;
                attribute.SongAsset = String.Format("urn:llid:{0}", x.SongFile.LLID);
                attribute.SongEvent = String.Format("Play_{0}", dlcName);
                attribute.SongKey = dlcName;
                attribute.SongLength = 0;
                attribute.SongName = songInfo.SongDisplayName;
                attribute.SongNameSort = songInfo.SongDisplayNameSort;
                attribute.SongXml = String.Format("urn:llid:{0}", x.SongXml.LLID);
                attribute.SongYear = songInfo.SongYear;
                attribute.TargetScore = 0;
                attribute.ToneUnlockScore = 0;
                attribute.TwoHandTapping = false;
                attribute.UnlockKey = "";
                attribute.Tuning = x.Tuning;
                attribute.VocalsAssetId = x.ArrangementType == Sng.ArrangementType.Vocal ? "" : (vocal != null) ? String.Format("{0}|GRSong_{1}", vocal.Id, vocal.Name) : "";
                attribute.ChordTemplates = new List<ChordTemplate>();
                manifestFunctions.GenerateDynamicVisualDensity(attribute, song, x);

                if (!isVocal)
                {
                    #region "Associated Techniques"

                    attribute.PowerChords = song.HasPowerChords();
                    if (song.HasPowerChords()) AssociateTechniques(x, attribute, "PowerChords");
                    attribute.BarChords = song.HasBarChords();
                    if (song.HasBarChords()) AssociateTechniques(x, attribute, "BarChords");
                    attribute.OpenChords = song.HasOpenChords();
                    if (song.HasOpenChords()) AssociateTechniques(x, attribute, "ChordIntro");
                    attribute.DoubleStops = song.HasDoubleStops();
                    if (song.HasDoubleStops()) AssociateTechniques(x, attribute, "DoubleStops");
                    attribute.Sustain = song.HasSustain();
                    if (song.HasSustain()) AssociateTechniques(x, attribute, "Sustain");
                    attribute.Bends = song.HasBends();
                    if (song.HasBends()) AssociateTechniques(x, attribute, "Bends");
                    attribute.Slides = song.HasSlides();
                    if (song.HasSlides()) AssociateTechniques(x, attribute, "Slides");
                    attribute.Tremolo = song.HasTremolo();
                    if (song.HasTremolo()) AssociateTechniques(x, attribute, "Tremolo");
                    attribute.SlapAndPop = song.HasSlapAndPop();
                    if (song.HasSlapAndPop()) AssociateTechniques(x, attribute, "Slap");
                    attribute.Harmonics = song.HasHarmonics();
                    if (song.HasHarmonics()) AssociateTechniques(x, attribute, "Harmonics");
                    attribute.PalmMutes = song.HasPalmMutes();
                    if (song.HasPalmMutes()) AssociateTechniques(x, attribute, "PalmMutes");
                    attribute.HOPOs = song.HasHOPOs();
                    if (song.HasHOPOs()) AssociateTechniques(x, attribute, "HOPOs");
                    attribute.FretHandMutes = song.HasFretHandMutes();
                    if (song.HasFretHandMutes()) AssociateTechniques(x, attribute, "FretHandMutes");
                    attribute.DropDPowerChords = song.HasDropDPowerChords();
                    if (song.HasDropDPowerChords()) AssociateTechniques(x, attribute, "DropDPowerChords");
                    attribute.Prebends = song.HasPrebends();
                    if (song.HasPrebends()) AssociateTechniques(x, attribute, "Prebends");
                    attribute.Vibrato = song.HasVibrato();
                    if (song.HasVibrato()) AssociateTechniques(x, attribute, "Vibrato");

                    //Bass exclusive
                    attribute.TwoFingerPlucking = song.HasTwoFingerPlucking();
                    if (song.HasTwoFingerPlucking()) AssociateTechniques(x, attribute, "Plucking");
                    attribute.FifthsAndOctaves = song.HasFifthsAndOctaves();
                    if (song.HasFifthsAndOctaves()) AssociateTechniques(x, attribute, "Octave");
                    attribute.Syncopation = song.HasSyncopation();
                    if (song.HasSyncopation()) AssociateTechniques(x, attribute, "Syncopation");

                    #endregion

                    attribute.AverageTempo = songInfo.AverageTempo;
                    attribute.RepresentativeArrangement = true;
                    attribute.SongPartition = songPartition.GetSongPartition(x.Name, x.ArrangementType);
                    attribute.SongLength = (float)Math.Round((decimal)song.SongLength, 3, MidpointRounding.AwayFromZero); //rounded
                    attribute.LastConversionDateTime = song.LastConversionDateTime;
                    attribute.TargetScore = 100000;
                    attribute.ToneUnlockScore = 70000;
                    attribute.SongDifficulty = (float)song.PhraseIterations.Average(it => song.Phrases[it.PhraseId].MaxDifficulty);
                    manifestFunctions.GenerateChordTemplateData(attribute, song);
                    manifestFunctions.GeneratePhraseData(attribute, song);
                    manifestFunctions.GenerateSectionData(attribute, song);
                    manifestFunctions.GeneratePhraseIterationsData(attribute, song, platform.version);
                }
                var attrDict = new Dictionary<string, Attributes> { { "Attributes", attribute } };
                manifest.Entries.Add(attribute.PersistentID, attrDict);
            }
            manifest.ModelName = "GRSong_Asset";
            manifest.IterationVersion = 2;
            return JsonConvert.SerializeObject(manifest, Formatting.Indented);
        }