public bool AreAllStringsLongerThan5(List<string> input)
 {
     return input.Reduce(
         true,
         (acc, str) =>
             (str.Length >= 5) && acc);
 }
示例#2
0
        public Foo()
        {
            _numbers = new List<int>();

            string s = _numbers[10].ToString(10);
            string s2 = _numbers.GetEnumerator().Current.ToString(10);
            string s3 = _numbers.Reduce<int>(delegate(int accumulated, int item) { return accumulated + item; }, 0).ToString(10);

            string s4 = _func(10).EncodeUriComponent();

            Func<int, string> f2 = _func;
            f2(11).Trim();

            Dictionary<string, int> d = new Dictionary<string, int>();
            string s5 = jQuery.ExtendDictionary<string, int>(d, d)["abc"].ToString(10);
            int keys = d.Count;
            bool b = d.ContainsKey("abc");
            d.Remove("abc");

            foreach (KeyValuePair<string, int> de in d) {
            }

            jQuery.AjaxRequest<string>("http://example.com").Success(delegate(string html) {
                Window.Alert(html);
            });

            string json = "";
            Foo f = Json.ParseData<Foo>(json).Setup().Run().Cleanup();

            string name = Document.GetElementById("nameTB").As<InputElement>().Value;
        }
示例#3
0
        public static Option <Scan> Create(ScanFile file, List <Region> regions)
        {
            var validationRules = new List <LazyOption>
            {
                Optional.Lazy(() => file != null, "Scan file cannot be empty"),
                Optional.Lazy(() => regions != null, "List of regions on the scan cannot be null"),
            };

            return(validationRules.Reduce()
                   .Map(() => new Scan(file, regions)));
        }
示例#4
0
        public static Option <ScanNumberRange> Create(uint startingValue, uint finalValue)
        {
            var validationRules = new List <LazyOption>
            {
                Optional.Lazy(() => startingValue > 0, "Starting value of scan number range must be greater than zero"),
                Optional.Lazy(() => finalValue > 0, "Final value of scan number range must be greater than zero"),
                Optional.Lazy(() => finalValue >= startingValue, $"Starting value of scan number range must be smaller than the final one: {{ {startingValue} [too big] - {finalValue} }}"),
            };

            return(validationRules.Reduce().Map(() => new ScanNumberRange(startingValue, finalValue)));
        }
        public static Option <VamasDataSet> Create(string name, HashSet <string> sampleIdentifiers, IEnumerable <Block> blocks)
        {
            var validations = new List <LazyOption>
            {
                Optional.Lazy(() => !string.IsNullOrWhiteSpace(name), "Name cannot be empty"),
                Optional.Lazy(() => sampleIdentifiers != null, "List of sample identifiers cannot be null"),
                Optional.Lazy(() => blocks != null, "List of blocks cannot be null")
            };

            return(validations.Reduce()
                   .Map(() => new VamasDataSet(name, sampleIdentifiers, blocks), "VAMAS data set validation failed"));
        }
示例#6
0
        public void Reduce_CalledWithNumbers_MaxValueReturned()
        {
            //arrange
            var numbers = new List <int> {
                1, 2, 3, 4
            };
            //act
            var sum = numbers.Reduce((acc, cur) => { return(acc < cur ? cur : acc); }, 0);

            //assert
            Assert.AreEqual(4, sum);
        }
示例#7
0
        private static void reductionImmutableVsConcurrentTest(List <Users> users)
        {
            var reduced = users.ReduceParallel();

            Console.WriteLine($"Reduced from {users.Count()} to {reduced.Count()}");

            var now = DateTime.Now;

            reduced = users.Reduce();

            var immutableTime = DateTime.Now.Subtract(now).TotalSeconds;

            now = DateTime.Now;

            reduced = users.Reduce(false);

            var concurrentTime = DateTime.Now.Subtract(now).TotalSeconds;

            Console.WriteLine("Immutable\tConcurrent");
            Console.WriteLine($"{immutableTime}\t{concurrentTime}\n");

            Console.WriteLine($"Reduced from {users.Count()} to {reduced.Count()}");
        }
示例#8
0
        protected bool?AskRemoveDependency(
            IPackage package,
            IList <IPackageRepository> localRepositories,
            IList <FrameworkName> targetFrameworks)
        {
            Debug.Assert(localRepositories.Count == targetFrameworks.Count);

            var allOperations = new List <PackageOperation>();

            for (int i = 0; i < localRepositories.Count; i++)
            {
                var uninstallWalker = new UninstallWalker(
                    localRepositories[i],
                    new DependentsWalker(localRepositories[i], targetFrameworks[i]),
                    targetFrameworks[i],
                    logger: NullLogger.Instance,
                    removeDependencies: true,
                    forceRemove: false)
                {
                    ThrowOnConflicts = false
                };
                var operations = uninstallWalker.ResolveOperations(package);
                allOperations.AddRange(operations);
            }

            allOperations = allOperations.Reduce().ToList();

            var uninstallPackageNames = (from o in allOperations
                                         where o.Action == PackageAction.Uninstall && !PackageEqualityComparer.IdAndVersion.Equals(o.Package, package)
                                         select o.Package)
                                        .Distinct(PackageEqualityComparer.IdAndVersion)
                                        .Select(p => p.ToString())
                                        .ToList();

            bool?removeDependencies = false;

            if (uninstallPackageNames.Count > 0)
            {
                // show each dependency package on one line
                String packageNames = String.Join(Environment.NewLine, uninstallPackageNames);
                String message      = String.Format(CultureInfo.CurrentCulture, Resources.Dialog_RemoveDependencyMessage, package)
                                      + Environment.NewLine
                                      + Environment.NewLine
                                      + packageNames;

                removeDependencies = _userNotifierServices.ShowRemoveDependenciesWindow(message);
            }

            return(removeDependencies);
        }
        public static Expression Multiply(params Expression[] terms)
        {
            TypeInference     type    = new TypeInference(terms);
            List <Expression> factors = type.CastToMaxNumeric()
                                        .Where(x => !Elementary.IsConstantOne(x))
                                        .ToList();

            if (factors.Exists(Elementary.IsConstantZero))
            {
                return(Zero());
            }

            return(factors.Reduce(Expression.Multiply, One()));
        }
示例#10
0
        private bool InstallPackageIntoProjects(IList <Project> allProjects, HashSet <string> selectedProjectsSet, IPackage package)
        {
            var allOperations = new List <PackageOperation>();

            foreach (Project project in allProjects)
            {
                if (selectedProjectsSet.Contains(project.UniqueName))
                {
                    IList <PackageOperation> operations;
                    CheckInstallPSScripts(
                        package,
                        PackageManager.GetProjectManager(project).LocalRepository,
                        PackageManager.SourceRepository,
                        targetFramework: project.GetTargetFrameworkName(),
                        includePrerelease: true,
                        operations: out operations);

                    allOperations.AddRange(operations);
                }
            }

            bool accepted = ShowLicenseAgreement(PackageManager, allOperations.Reduce());

            if (!accepted)
            {
                return(false);
            }

            // now install the packages that are checked
            // Bug 1357: It's crucial that we perform all installs before uninstalls
            // to avoid the package file being deleted before an install.
            foreach (Project project in allProjects)
            {
                if (selectedProjectsSet.Contains(project.UniqueName))
                {
                    try
                    {
                        // if the project is checked, install package into it
                        InstallPackageToProject(project, package, includePrerelease: true);
                    }
                    catch (Exception ex)
                    {
                        AddFailedProject(project, ex);
                    }
                }
            }

            return(true);
        }
示例#11
0
        private static string BuildInsertUnionSql <T>(IEnumerable <T> entities)
        {
            Type type    = GetType(typeof(T));
            var  keys    = new List <string>(GetKeysCache(type).Keys);
            var  columns = new List <string>(GetColumnsCache(type).Keys);

            columns.Reduce(keys);

            string sql = SqlTemplates.InsertByUnion.Replace("{{table}}", GetTypeName(type), StringComparison.OrdinalIgnoreCase)
                         .Replace("{{columns}}", columns.ToClause(), StringComparison.OrdinalIgnoreCase);

            string selectUnion = BuildSelectUnion(columns, entities.Count());

            return(sql.Replace("{{select}}", selectUnion, StringComparison.OrdinalIgnoreCase));
        }
示例#12
0
        public static Option <Region> Create(string name, ulong creationTimeUnix, double startingEnergyValue, IEnumerable <double> counts, ushort excitationEnergy, double stepTime, double energyStep, string energyMode)
        {
            var validationRules = new List <LazyOption>
            {
                Optional.Lazy(() => !string.IsNullOrWhiteSpace(name), "Name cannot be empty"),
                Optional.Lazy(() => creationTimeUnix > 0, "Creation time must be greater than zero"),
                Optional.Lazy(() => counts != null, "List of counts cannot be null"),
                Optional.Lazy(() => excitationEnergy > 0, "Excitation energy must be greater than zero"),
                Optional.Lazy(() => stepTime > 0, $"Step time must be greater than zero (was {stepTime})"),
                Optional.Lazy(() => energyStep > 0, $"Energy step must be greater than zero (was {energyStep})"),
                Optional.Lazy(() => !string.IsNullOrWhiteSpace(energyMode), "Energy mode cannot be empty")
            };

            return(validationRules.Reduce()
                   .FlatMap(() => counts.ToList().SomeWhen(cc => cc.Count > 0, "List of counts cannot be empty"))
                   .Map(cc => new Region(name, creationTimeUnix, startingEnergyValue, cc.AsReadOnly(), excitationEnergy, stepTime, energyStep, energyMode), "Region validation failed"));
        }
示例#13
0
        public void Reduce_CalledWithEmployees_SeniorEmployeeReturned()
        {
            //arrange
            var employees = new List <Employee> {
                new Employee {
                    Age = 60, Name = "Bala"
                },
                new Employee {
                    Age = 23, Name = "Murugan"
                }
            };
            //act
            var senior = employees.Reduce((acc, cur) => { return(acc.Age < cur.Age ? cur : acc); }, employees.First());

            //assert
            Assert.AreEqual("Bala", senior.Name);
        }
示例#14
0
        public static async Task<Option<ConversionDefinition>> Read(string filepath)
        {
            var validationRules = new List<LazyOption>
            {
                Optional.Lazy(() => !string.IsNullOrWhiteSpace(filepath), "Provided filepath cannot be empty"),
                Optional.Lazy(() => File.Exists(filepath), $"File '{filepath}' does not exist")
            };

            return await validationRules.Reduce()
                                        .FlatMapNone("Failed to read conversion definition file")
                                        .FlatMapAsync(async () =>
                                        {
                                            await using var fs = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.Asynchronous | FileOptions.SequentialScan);

                                            return await Read(filepath, fs);
                                        });
        }
示例#15
0
        public static ulong CalculateDifficulty(Blockchain Blockchain)
        {
            Block[]    Chain           = Blockchain.GetLastSectionBlocks();
            List <int> TimeDifferences = new List <int> {
            };

            // Walk backwards through the blockchain. Saves some absolute conversions (this is
            // because the blockchain implicitly is an ordered list).
            for (int i = Chain.Length - 1; i > 0; i--)
            {
                Block CurrentBlock  = Chain[i];
                Block PreviousBlock = Chain[i - 1];

                TimeDifferences.Add(Convert.ToInt32(CurrentBlock.Timestamp.Subtract(PreviousBlock.Timestamp).TotalSeconds));
            }

            // if we have a full section of blocks (which is always except when the chain is shorter
            // than 6 blocks) continue calculating the averages, otherwise return
            // the diff of the genesis block
            if (TimeDifferences.Count == 5)
            {
                // The average time diff can never be zero, sixty seconds is the minimum (20%). This comes
                // down to the maximum percentile decrease in diff (lowerbound) is 80%.
                int   AverageTimeDifference = Math.Max(120, TimeDifferences.Reduce(R.Total, 0) / TimeDifferences.Count);
                ulong AverageDifficulty     = Chain.Map(block => block.GetDifficulty()).Reduce <ulong>(R.Total, 0) / (ulong)Chain.Length;

                // If the average time difference is larger than the mean time between blocks we decrease
                // difficulty. However, is the time difference smaller than the mean time then we
                // increase the difficulty.

                // We don't need if's, the deltapercentage is either positive or negative. We do cap
                // the maximum change to 0.8 (or 80%) (upperbound) change. This is to cut off large pauses in between
                // blocks being mined. Normally you won't see this behaviour being coded in, but this
                // blockchain is adapted for longer periods of not mining and then suddenly mining again.
                // Without giving strange large swings in diff. Keep in mind that 'stabilizing' the chain
                // will take some time after pauses.
                float DeltaPercentage = Math.Min((float)0.8, ((float)AverageTimeDifference - (float)MeanTimeBetweenBlocks) / (float)MeanTimeBetweenBlocks);
                Console.WriteLine(DeltaPercentage);
                // We loose some precision with the ulong cast, but its too small to have any effect so its okay.
                ulong TargetDiff = (ulong)(AverageDifficulty + AverageDifficulty * DeltaPercentage);
                return(TargetDiff != 0 ? TargetDiff : UInt64.MaxValue);
            }

            return(Chain[0].GetDifficulty());
        }
        public static Option <ConversionDefinition> Create(string filepath, string scanFilesDirectoryPath, IEnumerable <SampleInformationString> sampleInformationStrings)
        {
            var validationRules = new List <LazyOption>
            {
                Optional.Lazy(() => !string.IsNullOrWhiteSpace(filepath), "Filepath to conversion definition file cannot be empty"),
                Optional.Lazy(() => !string.IsNullOrWhiteSpace(scanFilesDirectoryPath), "Scan files directory path cannot be empty"),
                Optional.Lazy(() => sampleInformationStrings != null, "List of sample information strings cannot be null")
            };

            return(validationRules.Reduce()
                   .FlatMap(() =>
            {
                var sampleInformationStringList = sampleInformationStrings.ToList();

                return sampleInformationStringList.SomeWhen(siss => siss.Count > 0, "Definition must contain at least one sample information string");
            })
                   .Map(siss => new ConversionDefinition(filepath, scanFilesDirectoryPath, siss), "Conversion definition validation failed"));
        }
示例#17
0
        public static Option <Block> Create(string name, string sampleIdentifier, ILocalTime creationTimeLocal, string scanFilepath, string regionName, string species, double startingEnergyValue, double energyStep, IEnumerable <double> counts)
        {
            var validationRules = new List <LazyOption>
            {
                Optional.Lazy(() => !string.IsNullOrWhiteSpace(name), "Name cannot be empty"),
                Optional.Lazy(() => !string.IsNullOrWhiteSpace(sampleIdentifier), "Sample identifier cannot be empty"),
                Optional.Lazy(() => creationTimeLocal != null, "Local creation time cannot be null"),
                Optional.Lazy(() => !string.IsNullOrWhiteSpace(scanFilepath), "Scan filepath cannot be empty"),
                Optional.Lazy(() => !string.IsNullOrWhiteSpace(regionName), "Region name cannot be empty"),
                Optional.Lazy(() => !string.IsNullOrWhiteSpace(species), "Species cannot be empty"),
                Optional.Lazy(() => energyStep > 0, $"Energy step must be greater than zero (was {energyStep})"),
                Optional.Lazy(() => counts != null, "List of counts cannot be null")
            };

            return(validationRules.Reduce()
                   .FlatMap(() => counts.ToList().SomeWhen(cc => cc.Count > 0, "List of counts cannot be empty"))
                   .Map(cc => new Block(name, sampleIdentifier, creationTimeLocal, scanFilepath, regionName, species, startingEnergyValue, energyStep, cc), "Block validation failed"));
        }
            public static Option <SampleInformationString> Create(string sampleName, IEnumerable <ScanNumberRange> scanNumberRanges, Option <ushort> kineticEnergy)
            {
                return(Optional.SomeWhen(scanNumberRanges != null, "List of scan number ranges in sample information string cannot be null").FlatMap(() =>
                {
                    var scanNumberRangesList = scanNumberRanges !.ToList();

                    var validationRules = new List <LazyOption>
                    {
                        Optional.Lazy(() => !string.IsNullOrWhiteSpace(sampleName), "Name of sample in sample information string cannot be empty"),
                        Optional.Lazy(() => scanNumberRangesList.Count > 0, "List of scan number ranges in sample information string must contain at least one number range"),
                        Optional.Lazy(() => !kineticEnergy.HasValue || kineticEnergy.Exists(ke => ke > 0), "Specified kinetic energy value in sample information string must be greater than zero")
                    };

                    return validationRules.Reduce().Map(() => new SampleInformationString(sampleName,
                                                                                          scanNumberRangesList,
                                                                                          kineticEnergy));
                }));
            }
示例#19
0
        static void Main(string[] args)
        {
            List <int> list = new List <int>(new[] { 1, 2, 3, 4 });


            List <string> listString = list.Map <string, int>((x) => x.ToString());


            string T = list.Reduce <int, string>("", (x, y) =>

            {
                int z = 0;
                foreach (var item in list)
                {
                    z += item;
                }
                return(z.ToString());
            });
        }
示例#20
0
    // Token: 0x060016E5 RID: 5861 RVA: 0x0007EA34 File Offset: 0x0007CC34
    private void OnEnable()
    {
        int num  = (GameState.Current.PlayerData.Team != TeamID.BLUE) ? GameState.Current.ScoreRed : GameState.Current.ScoreBlue;
        int num2 = (GameState.Current.PlayerData.Team != TeamID.BLUE) ? GameState.Current.ScoreBlue : GameState.Current.ScoreRed;

        this.panel.gameObject.SetActive(true);
        this.blueLabel.text = GameState.Current.ScoreBlue.ToString();
        this.redLabel.text  = GameState.Current.ScoreRed.ToString();
        bool isTeamGame = GameState.Current.IsTeamGame;

        this.blueLabel.enabled = isTeamGame;
        this.blueBgr.enabled   = isTeamGame;
        this.redLabel.enabled  = isTeamGame;
        this.redBgr.enabled    = isTeamGame;
        if (isTeamGame)
        {
            if (num > num2)
            {
                this.titleLabel.text = "Your Team Won!";
            }
            else if (num < num2)
            {
                this.titleLabel.text = "Your Team Lost";
            }
            else
            {
                this.titleLabel.text = "Draw";
            }
        }
        else
        {
            List <GameActorInfo> list = new List <GameActorInfo>(GameState.Current.Players.Values);
            int maxScore = list.Reduce((GameActorInfo player, int prev) => Mathf.Max((int)player.Kills, prev), int.MinValue);
            List <GameActorInfo> list2 = list.FindAll((GameActorInfo el) => (int)el.Kills == maxScore);
            string str = string.Empty;
            list2.ForEach(delegate(GameActorInfo el)
            {
                str = str + el.PlayerName + " ";
            });
            this.titleLabel.text = str + "won!";
        }
        base.StartCoroutine(this.Wait5Seconds());
    }
        public void ReduceSuccess()
        {
            int sum(int acc, int x) => acc + x;

            List <int> lst = new List <int>();

            for (int i = 0; i < 100; i++)
            {
                lst.Add(i);
            }

            int accumulator = 0;

            foreach (int n in lst)
            {
                accumulator += n;
            }

            Assert.AreEqual(accumulator, lst.Reduce(sum, 0));
        }
示例#22
0
        protected bool ShowLicenseAgreementForAllPackages(IVsPackageManager activePackageManager)
        {
            var allOperations = new List <PackageOperation>();

            var allPackages = SelectedNode.GetPackages(String.Empty, IncludePrerelease).ToList();

            foreach (var package in allPackages)
            {
                var installWalker = new InstallWalker(
                    LocalRepository,
                    activePackageManager.SourceRepository,
                    _project.GetTargetFrameworkName(),
                    logger: this,
                    ignoreDependencies: false,
                    allowPrereleaseVersions: IncludePrerelease);

                var operations = installWalker.ResolveOperations(package);
                allOperations.AddRange(operations);
            }

            return(ShowLicenseAgreement(activePackageManager, allOperations.Reduce()));
        }
示例#23
0
        public static IHtmlString ToCheckBoxes(Dictionary <string, bool> isJoinedDictionary, string dictionaryName)
        {
            List <string> elements = new List <string>();

            foreach (var keyval in isJoinedDictionary)
            {
                var displayName = keyval.Key.Split(':')[0];
                var name        = string.Format("{0}[{1}]", dictionaryName, keyval.Key);

                var checkBox = checkBoxSetter(dictionaryName, name, keyval.Value, false);

                var hidden = hiddenInputSetter(name);

                var label = labelSetter(displayName);

                elements.Add(checkBox + hidden + label);
            }

            var reduced = elements.Reduce("", (x, y) => { return(x += " " + y); });

            return(new HtmlString(reduced));
        }
示例#24
0
        /// Processing
        private static List <List <string> > processWordsByLength(List <string> all)
        {
            var processValues            = new List <string>(all.Clone());
            List <List <string> > result = new List <List <string> >();

            int length    = 1;
            int maxLength = processValues.Reduce((previous, current) =>
            {
                return(System.Math.Max(previous, current.Length));
            }, 0);

            while (processValues.Count > 0 && length <= maxLength)
            {
                var found = processValues.FindAll(test => test.Length == length);
                // TODO: specify index to match Length - 1 purposefully to be safe
                result.Add(found);
                processValues.RemoveAll(found);
                length++;
            }

            return(result);
        }
        protected bool ShowLicenseAgreement(
            IPackage package,
            IVsPackageManager packageManager,
            IEnumerable <Project> projects,
            out IList <PackageOperation> operations)
        {
            var allOperations = new List <PackageOperation>();

            foreach (Project project in projects)
            {
                var walker = new InstallWalker(
                    packageManager.GetProjectManager(project).LocalRepository,
                    packageManager.SourceRepository,
                    project.GetTargetFrameworkName(),
                    this,
                    ignoreDependencies: false,
                    allowPrereleaseVersions: IncludePrerelease);

                allOperations.AddRange(walker.ResolveOperations(package));
            }

            operations = allOperations.Reduce();
            return(ShowLicenseAgreement(packageManager, operations));
        }
示例#26
0
 //implementar aquí métodos de ejercicios 1, 2 y 3
 public void ej1(int formato)
 {
     List<int> duraciones = new List<int>(canciones.Filter(x => x.FormatoID == formato).Select(x => x.Duracion));
     int media = duraciones.Reduce((x,y) => x + y) / canciones.Filter(x => x.FormatoID == formato).Count();
     Console.WriteLine(duraciones.Map(x => (x-media)*(x-media)).Sum());
 }
        protected bool? AskRemoveDependency(
            IPackage package,
            IList<IPackageRepository> localRepositories,
            IList<FrameworkName> targetFrameworks)
        {
            Debug.Assert(localRepositories.Count == targetFrameworks.Count);

            var allOperations = new List<PackageOperation>();

            for (int i = 0; i < localRepositories.Count; i++)
            {
                var uninstallWalker = new UninstallWalker(
                    localRepositories[i],
                    new DependentsWalker(localRepositories[i], targetFrameworks[i]),
                    targetFrameworks[i],
                    logger: NullLogger.Instance,
                    removeDependencies: true,
                    forceRemove: false)
                    {
                        ThrowOnConflicts = false
                    };
                var operations = uninstallWalker.ResolveOperations(package);
                allOperations.AddRange(operations);
            }

            allOperations = allOperations.Reduce().ToList();

            var uninstallPackageNames = (from o in allOperations
                                         where o.Action == PackageAction.Uninstall && !PackageEqualityComparer.IdAndVersion.Equals(o.Package, package)
                                         select o.Package)
                                         .Distinct(PackageEqualityComparer.IdAndVersion)
                                         .Select(p => p.ToString())
                                         .ToList();

            bool? removeDependencies = false;
            if (uninstallPackageNames.Count > 0)
            {
                // show each dependency package on one line
                String packageNames = String.Join(Environment.NewLine, uninstallPackageNames);
                String message = String.Format(CultureInfo.CurrentCulture, Resources.Dialog_RemoveDependencyMessage, package)
                        + Environment.NewLine
                        + Environment.NewLine
                        + packageNames;

                removeDependencies = _userNotifierServices.ShowRemoveDependenciesWindow(message);
            }

            return removeDependencies;
        }
示例#28
0
 public static List <Result> Map <T, Result>(this List <T> l, Func <T, Result> func)
 {
     return(l.Reduce((x, list) => { list.Add(func(x)); return list; }, new List <Result>()));
 }
        protected bool CheckPSScriptAndShowLicenseAgreement(
            PackageItem item, IList<Project> projects, IVsPackageManager packageManager, out IList<PackageOperation> operations)
        {
            ShowProgressWindow();

            // combine the operations of all selected project
            var allOperations = new List<PackageOperation>();
            foreach (Project project in projects)
            {
                IProjectManager projectManager = packageManager.GetProjectManager(project);

                IList<PackageOperation> projectOperations;
                CheckInstallPSScripts(
                    item.PackageIdentity,
                    projectManager.LocalRepository,
                    packageManager.SourceRepository,
                    project.GetTargetFrameworkName(),
                    IncludePrerelease,
                    out projectOperations);

                allOperations.AddRange(projectOperations);
            }

            // reduce the operations before checking for license agreements
            operations = allOperations.Reduce();

            return ShowLicenseAgreement(packageManager, operations);
        }
示例#30
0
        protected bool ShowLicenseAgreement(
            IPackage package,
            IVsPackageManager packageManager,
            IEnumerable<Project> projects,
            out IList<PackageOperation> operations)
        {
            var allOperations = new List<PackageOperation>();

            foreach (Project project in projects)
            {
                var walker = new InstallWalker(
                    packageManager.GetProjectManager(project).LocalRepository,
                    packageManager.SourceRepository,
                    project.GetTargetFrameworkName(),
                    this,
                    ignoreDependencies: false,
                    allowPrereleaseVersions: IncludePrerelease,
                    dependencyVersion: packageManager.DependencyVersion);

                allOperations.AddRange(walker.ResolveOperations(package));
            }

            operations = allOperations.Reduce();
            return ShowLicenseAgreement(packageManager, operations);
        }
示例#31
0
        protected bool ShowLicenseAgreementForAllPackages(IVsPackageManager activePackageManager)
        {
            var allOperations = new List<PackageOperation>();

            var allPackages = SelectedNode.GetPackages(String.Empty, IncludePrerelease).ToList();
            foreach (var package in allPackages)
            {
                var installWalker = new InstallWalker(
                    LocalRepository,
                    activePackageManager.SourceRepository,
                    _project.GetTargetFrameworkName(),
                    logger: this,
                    ignoreDependencies: false,
                    allowPrereleaseVersions: IncludePrerelease);

                var operations = installWalker.ResolveOperations(package);
                allOperations.AddRange(operations);
            }

            return ShowLicenseAgreement(activePackageManager, allOperations.Reduce());
        }
 public static List <T> ReduceAuto <T>(this List <T> originalSet, bool subSample = false)
 {
     return(originalSet.Count() > ParallelThreshold ? originalSet.ReduceParallelOptimized(subSample) : originalSet.Reduce());
 }
示例#33
0
        public void Collections_Reduce()
        {
            const int value = 42;

            var validationRules1 = new List <LazyOption>
            {
                Optional.Lazy(() => (value & 1) == 1, Success.Create("Value is odd"), "Value must be odd"),
                Optional.Lazy(() => value / 2 == 77, Success.Create("Value divided by two is 77"), "Value divided by two must equal 77"),
            };

            var validationRulesReduced1 = validationRules1.Reduce();

            Assert.False(validationRulesReduced1.IsSuccessful);
            validationRulesReduced1.Match(
                some: _ => Assert.True(false, "Failed"),
                none: e => Assert.Equal("Value must be odd", e.Message)
                );


            var validationRules2 = new List <LazyOption>
            {
                Optional.Lazy(() => value % 2 == 0, Success.Create("Value is even"), "Value must be even"),
                Optional.Lazy(() => value == 42, Success.Create("Value is 42"), "Value must be equal to 42"),
            };

            var validationRulesReduced2 = validationRules2.Reduce();

            Assert.True(validationRulesReduced2.IsSuccessful);



            var validationRules3 = new List <LazyOption>
            {
                Optional.Lazy(() => value % 2 == 0, Success.Create("Value is even"), "Value must be even"),
                Optional.Lazy(() => value / 2 == 77, Success.Create("Value divided by two is 77"), "Value divided by two must equal 77"),
            };

            var validationRulesReduced3 = validationRules3.Reduce();

            Assert.False(validationRulesReduced3.IsSuccessful);
            validationRulesReduced3.Match(
                some: _ => Assert.True(false, "Failed"),
                none: e => Assert.Equal("Value divided by two must equal 77", e.Message)
                );



            bool validationRun1 = false, validationRun2 = false, validationRun3 = false, validationRun4 = false;

            var validationRules4 = new List <LazyOption>
            {
                Optional.Lazy(() =>
                {
                    validationRun1 = true;

                    return((value & 1) == 1);
                }, Success.Create("SUCCESS"), "ERROR"),

                Optional.Lazy(() =>
                {
                    validationRun2 = true;

                    return((value & 1) == 1);
                }, Success.Create("SUCCESS"), "ERROR"),

                Optional.Lazy(() =>
                {
                    validationRun3 = true;

                    return((value & 1) == 1);
                }, Success.Create("SUCCESS"), "ERROR"),

                Optional.Lazy(() =>
                {
                    validationRun4 = true;

                    return((value & 1) == 1);
                }, Success.Create("SUCCESS"), "ERROR"),
            };

            var validationRulesReduced4 = validationRules4.Reduce();

            Assert.False(validationRulesReduced4.IsSuccessful);

            Assert.True(validationRun1);
            Assert.False(validationRun2);
            Assert.False(validationRun3);
            Assert.False(validationRun4);
        }
示例#34
0
        public async Task <Option> Write(VamasDataSet dataSet, Stream stream)
        {
            var validationRules = new List <LazyOption>
            {
                Optional.Lazy(() => dataSet != null, "VAMAS data set cannot be null"),
                Optional.Lazy(() => stream != null, "Stream to write to cannot be null"),
                Optional.Lazy(() => stream.CanWrite, "Stream to write to must be writable"),
            };

            return(await validationRules.Reduce()
                   .FlatMapAsync(async() =>
            {
                try
                {
                    await using var sw = new StreamWriter(stream);

                    var blockIndex = 0;

                    await sw.WriteAsync(await FormatFileHeader());

                    foreach (var block in dataSet.Blocks)
                    {
                        await sw.WriteAsync(await FormatBlock(block, blockIndex++));

                        foreach (var count in block.Counts)
                        {
                            await sw.WriteLineAsync(count.ToString("G17", CultureInfo.InvariantCulture));
                        }
                    }

                    await sw.WriteAsync(await FormatFileFooter());
                }
                catch (Exception e)
                {
                    return Optional.None(e);
                }

                return Optional.Some(Success.Create("VAMAS data set written to stream successfully"));
            }, "Failed to write VAMAS file to stream"));

            async Task <string> FormatFileHeader()
            {
                return(string.Format((await _templates)["FILE_HEADER"],

                                     3 + dataSet.SampleIdentifiers.Count,
                                     string.Join("", dataSet.SampleIdentifiers.Select(c => $"{Environment.NewLine}CasaRowLabel:{c}")),
                                     dataSet.Blocks.Count));
            }

            async Task <string> FormatBlock(Block block, int blockIndex)
            {
                return(string.Format((await _templates)["BLOCK"],

                                     block.Name,
                                     block.SampleIdentifier,
                                     block.CreationTimeLocal.Value.Year,
                                     block.CreationTimeLocal.Value.Month,
                                     block.CreationTimeLocal.Value.Day,
                                     block.CreationTimeLocal.Value.Hour,
                                     block.CreationTimeLocal.Value.Minute,
                                     block.CreationTimeLocal.Value.Second,
                                     block.CreationTimeLocal.UtcOffset,
                                     Path.GetFileNameWithoutExtension(block.ScanFilepath),
                                     block.RegionName,
                                     Path.GetDirectoryName(block.ScanFilepath),
                                     blockIndex,
                                     block.Species,
                                     block.StartingEnergyValue.ToString("0.#", CultureInfo.InvariantCulture),
                                     block.EnergyStep.ToString("0.0##", CultureInfo.InvariantCulture),
                                     block.Counts.Count,
                                     block.Counts.Min().ToString("G17", CultureInfo.InvariantCulture),
                                     block.Counts.Max().ToString("G17", CultureInfo.InvariantCulture)));
            }

            async Task <string> FormatFileFooter()
            {
                return((await _templates)["FILE_FOOTER"]);
            }
        }
示例#35
0
        protected bool ShowLicenseAgreementForAllPackages(IVsPackageManager activePackageManager, out List<PackageOperation> allOperations)
        {
            allOperations = new List<PackageOperation>();

            var installWalker = new InstallWalker(
                LocalRepository,
                activePackageManager.SourceRepository,
                _project.GetTargetFrameworkName(),
                logger: this,
                ignoreDependencies: false,
                allowPrereleaseVersions: IncludePrerelease);

            var allPackages = SelectedNode.GetPackages(String.Empty, IncludePrerelease);
            foreach (var package in allPackages)
            {
                if (allOperations.FindIndex(
                        operation => operation.Action == PackageAction.Install &&
                                     operation.Package.Id == package.Id &&
                                     operation.Package.Version == package.Version) == -1)
                {
                    var operations = installWalker.ResolveOperations(package);
                    allOperations.AddRange(operations);
                }
            }

            allOperations = (List<PackageOperation>)allOperations.Reduce();
            return ShowLicenseAgreement(activePackageManager, allOperations);
        }
示例#36
0
        // The starting point of our application
        static void Main(string[] args)
        {
            #region PrintList
            // Print a title
            Console.WriteLine("PRINTLIST");

            // We create a list with even numbers
            List <int> evenNumber = new List <int>()
            {
                0, 2, 4, 6, 8
            };

            // We check out the content of the list using the printList function
            evenNumber.PrintList();

            // Make space
            Console.WriteLine("\n\n");
            #endregion

            #region Map
            // Print a title
            Console.WriteLine("MAP");

            // We create a lambda function that multiplies the input
            Func <int, int> Multiplier = (input) => input * 2;

            // We print all the numbers in evenNumbers multiplied by two
            evenNumber
            .Map(Multiplier)
            .PrintList();

            // Make space
            Console.WriteLine("\n\n");
            #endregion

            #region Reduce
            // Print a title
            Console.WriteLine("REDUCE");

            // We create a method call summer, which adds the value of an item to an accumulator
            Func <int, int, int> Summer = (result, item) => result + item;

            // We ask for the sum of evenNumbers
            int sum = evenNumber.Reduce(0, Summer);

            // We print the result of the reduce function
            System.Console.WriteLine(sum);

            // Make space
            Console.WriteLine("\n\n");
            #endregion

            #region Where
            // Print a title
            Console.WriteLine("WHERE");

            // Create a list with multiplications of three
            List <int> threeMultiplications = new List <int>()
            {
                0, 3, 6, 9
            };

            // We create a function that checks whether an item is uneven
            Func <int, bool> isUneven = (number) => number % 2 != 0;

            // We print the list of uneven items in evenNumber
            evenNumber
            .Where(isUneven)
            .PrintList();

            // We print the list of uneven items in threeMultiplications
            threeMultiplications
            .Where(isUneven)
            .PrintList();

            // Make space
            Console.WriteLine("\n\n");
            #endregion

            #region Join
            // Print a title
            Console.WriteLine("JOIN");

            // We join the evenNumber list with the threeMultiplications list using SimpleJoin
            // We want the combinations where the sum of both numbers is even
            evenNumber
            .SimpleJoin(threeMultiplications, (left, right) => ((left + right) % 2) == 0)
            .PrintList();

            // We join the evenNumber list with the threeMultiplications list using Join
            // Because of the lambda that always returns true, we will receive the cartesian product
            evenNumber
            .Join(threeMultiplications, (left, right) => true)
            .PrintList();
            #endregion
        }
        private bool InstallPackageIntoProjects(IList<Project> allProjects, HashSet<string> selectedProjectsSet, IPackage package)
        {
            var allOperations = new List<PackageOperation>();
            foreach (Project project in allProjects)
            {
                if (selectedProjectsSet.Contains(project.UniqueName))
                {
                    IList<PackageOperation> operations;
                    CheckInstallPSScripts(
                        package,
                        PackageManager.GetProjectManager(project).LocalRepository,
                        PackageManager.SourceRepository,
                        targetFramework: project.GetTargetFrameworkName(),
                        includePrerelease: true,
                        operations: out operations);

                    allOperations.AddRange(operations);
                }
            }

            bool accepted = ShowLicenseAgreement(PackageManager, allOperations.Reduce());
            if (!accepted)
            {
                return false;
            }

            // now install the packages that are checked
            // Bug 1357: It's crucial that we perform all installs before uninstalls
            // to avoid the package file being deleted before an install.
            foreach (Project project in allProjects)
            {
                if (selectedProjectsSet.Contains(project.UniqueName))
                {
                    try
                    {
                        // if the project is checked, install package into it  
                        InstallPackageToProject(project, package, includePrerelease: true);
                    }
                    catch (Exception ex)
                    {
                        AddFailedProject(project, ex);
                    }
                }
            }

            return true;
        }
示例#38
0
        protected bool?AskRemoveDependencyAndCheckUninstallPSScript(
            IPackage package,
            IList <IPackageRepository> localRepositories,
            IList <FrameworkName> targetFrameworks)
        {
            Debug.Assert(localRepositories.Count == targetFrameworks.Count);

            var allOperations = new List <PackageOperation>();

            for (int i = 0; i < localRepositories.Count; i++)
            {
                var uninstallWalker = new UninstallWalker(
                    localRepositories[i],
                    new DependentsWalker(localRepositories[i], targetFrameworks[i]),
                    targetFrameworks[i],
                    logger: NullLogger.Instance,
                    removeDependencies: true,
                    forceRemove: false)
                {
                    ThrowOnConflicts = false
                };
                var operations = uninstallWalker.ResolveOperations(package);
                allOperations.AddRange(operations);
            }

            allOperations = allOperations.Reduce().ToList();

            var uninstallPackageNames = (from o in allOperations
                                         where o.Action == PackageAction.Uninstall && !PackageEqualityComparer.IdAndVersion.Equals(o.Package, package)
                                         select o.Package)
                                        .Distinct(PackageEqualityComparer.IdAndVersion)
                                        .Select(p => p.ToString())
                                        .ToList();

            bool?removeDependencies = false;

            if (uninstallPackageNames.Count > 0)
            {
                // show each dependency package on one line
                String packageNames = String.Join(Environment.NewLine, uninstallPackageNames);
                String message      = String.Format(CultureInfo.CurrentCulture, Resources.Dialog_RemoveDependencyMessage, package)
                                      + Environment.NewLine
                                      + Environment.NewLine
                                      + packageNames;

                removeDependencies = _userNotifierServices.ShowRemoveDependenciesWindow(message);
            }

            if (removeDependencies == null)
            {
                return(removeDependencies);
            }

            bool hasScriptPackages;

            if (removeDependencies == true)
            {
                // if user wants to remove dependencies, we need to check all of them for PS scripts
                var scriptPackages = from o in allOperations
                                     where o.Package.HasPowerShellScript()
                                     select o.Package;
                hasScriptPackages = scriptPackages.Any();
            }
            else
            {
                // otherwise, just check the to-be-uninstalled package
                hasScriptPackages = package.HasPowerShellScript(new string[] { PowerShellScripts.Uninstall });
            }

            if (hasScriptPackages)
            {
                if (!RegistryHelper.CheckIfPowerShell2Installed())
                {
                    throw new InvalidOperationException(Resources.Dialog_PackageHasPSScript);
                }
            }

            return(removeDependencies);
        }
示例#39
0
        protected bool? AskRemoveDependencyAndCheckUninstallPSScript(
            IPackage package,
            IList<IPackageRepository> localRepositories,
            IList<FrameworkName> targetFrameworks)
        {
            Debug.Assert(localRepositories.Count == targetFrameworks.Count);

            var allOperations = new List<PackageOperation>();

            for (int i = 0; i < localRepositories.Count; i++)
            {
                var uninstallWalker = new UninstallWalker(
                    localRepositories[i],
                    new DependentsWalker(localRepositories[i], targetFrameworks[i]),
                    targetFrameworks[i],
                    logger: NullLogger.Instance,
                    removeDependencies: true,
                    forceRemove: false)
                    {
                        ThrowOnConflicts = false
                    };
                var operations = uninstallWalker.ResolveOperations(package);
                allOperations.AddRange(operations);
            }

            allOperations = allOperations.Reduce().ToList();

            var uninstallPackageNames = (from o in allOperations
                                         where o.Action == PackageAction.Uninstall && !PackageEqualityComparer.IdAndVersion.Equals(o.Package, package)
                                         select o.Package)
                                         .Distinct(PackageEqualityComparer.IdAndVersion)
                                         .Select(p => p.ToString())
                                         .ToList();

            bool? removeDependencies = false;
            if (uninstallPackageNames.Count > 0)
            {
                // show each dependency package on one line
                String packageNames = String.Join(Environment.NewLine, uninstallPackageNames);
                String message = String.Format(CultureInfo.CurrentCulture, Resources.Dialog_RemoveDependencyMessage, package)
                        + Environment.NewLine
                        + Environment.NewLine
                        + packageNames;

                removeDependencies = _userNotifierServices.ShowRemoveDependenciesWindow(message);
            }

            if (removeDependencies == null)
            {
                return removeDependencies;
            }

            bool hasScriptPackages;
            if (removeDependencies == true)
            {
                // if user wants to remove dependencies, we need to check all of them for PS scripts
                var scriptPackages = from o in allOperations
                                     where o.Package.HasPowerShellScript()
                                     select o.Package;
                hasScriptPackages = scriptPackages.Any();
            }
            else
            {
                // otherwise, just check the to-be-uninstalled package
                hasScriptPackages = package.HasPowerShellScript(new string[] { PowerShellScripts.Uninstall });
            }

            if (hasScriptPackages)
            {
                if (!RegistryHelper.CheckIfPowerShell2Installed())
                {
                    throw new InvalidOperationException(Resources.Dialog_PackageHasPSScript);
                }
            }

            return removeDependencies;
        }