예제 #1
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @SuppressWarnings("unchecked") public static java.util.stream.IntStream toBooleanStream(Object list)
        public static IntStream ToBooleanStream(object list)
        {
            if (list == null)
            {
                return(IntStream.empty());
            }
            else if (list is SequenceValue)
            {
                throw new System.ArgumentException("Need to implement support for SequenceValue in CompiledConversionUtils.toBooleanStream");
            }
            else if (list is System.Collections.IList)
            {
                return(((System.Collections.IList)list).Select(n => (( Number )n).intValue()));
            }
            else if (list.GetType().IsAssignableFrom(typeof(object[])))
            {
                return(java.util.( object[] )list.Select(n => (( Number )n).intValue()));
            }
            else if (list is bool[])
            {
                bool[] array = ( bool[] )list;
                return(IntStream.range(0, array.Length).map(i => (array[i]) ? 1 : 0));
            }
//JAVA TO C# CONVERTER WARNING: The .NET Type.FullName property will not always yield results identical to the Java Class.getName method:
            throw new System.ArgumentException(format("Can not be converted to stream: %s", list.GetType().FullName));
        }
    public static void Main()
    {
        IntStream        stream = new IntStream();
        PrimeStream      prime  = new PrimeStream();
        RandomStream     rand   = new RandomStream();
        RandomWordStream word   = new RandomWordStream();

        Console.WriteLine("Next z klasy IntStream");
        for (int i = 0; i <= 5; i++)
        {
            Console.WriteLine(stream.next());
        }
        Console.WriteLine("Next z klasy PrimeStream");
        for (int i = 0; i <= 5; i++)
        {
            Console.WriteLine(prime.next());
        }

        Console.WriteLine("Next z klasy RandomStream");
        for (int i = 0; i <= 5; i++)
        {
            Console.WriteLine(rand.next());
        }

        Console.WriteLine("Next z klasy RandomWordStream");
        for (int i = 0; i <= 5; i++)
        {
            Console.WriteLine(word.next());
        }
    }
예제 #3
0
    static void Main()
    {
        IntStream         strumNaturalny           = new IntStream();
        PrimeStream       strumPierwszych          = new PrimeStream();
        RandomStream      strumRandomowych         = new RandomStream();
        RandomWorldStream strumRandomowychStringow = new RandomWorldStream();

        Console.Write("Kolejna liczba naturalna: {0} \n", strumNaturalny.next());
        Console.Write("Kolejna liczba naturalna: {0} \n", strumNaturalny.next());
        Console.Write("Kolejna liczba naturalna: {0} \n", strumNaturalny.next());
        Console.Write("Reset strumienia.\n");
        strumNaturalny.reset();
        Console.Write("Kolejna liczba naturalna: {0} \n", strumNaturalny.next());
        Console.Write("Kolejna liczba naturalna: {0} \n", strumNaturalny.next());
        if (strumNaturalny.eos() == false)
        {
            Console.Write("\tStan eos: falsz.\n");
        }
        else
        {
            Console.Write("\tStan eos: prawda.\n");
        }
        Console.Write("Kolejna liczba pierwsza: {0} \n", strumPierwszych.next());
        Console.Write("Kolejna liczba pierwsza: {0} \n", strumPierwszych.next());
        Console.Write("Kolejna liczba pierwsza: {0} \n", strumPierwszych.next());
        Console.Write("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
        Console.WriteLine("Kolejna liczba losowa: {0} ", strumRandomowych.next());
        Console.WriteLine("Kolejna liczba losowa: {0}", strumRandomowych.next());
        Console.WriteLine("Kolejna liczba losowa: {0} ", strumRandomowych.next());
        Console.Write("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
        Console.Write("Kolejny losowy string: {0}\n", strumRandomowychStringow.nextL());
        Console.Write("Kolejny losowy string: {0}\n", strumRandomowychStringow.nextL());
        Console.Write("Kolejny losowy string: {0}\n", strumRandomowychStringow.nextL());
    }
예제 #4
0
        public void BuildFromIntStream__Test()
        {
            Day08 day = new Day08();

            IntStream         values = new IntStream("2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2");
            ChronoLicenceNode result = ChronoLicenceNode.BuildFromIntStream(values);

            Assert.AreEqual(2, result.Childs.Count);
            Assert.AreEqual(3, result.Metadata.Count);
            Assert.AreEqual(1, result.Metadata[0]);
            Assert.AreEqual(1, result.Metadata[1]);
            Assert.AreEqual(2, result.Metadata[2]);

            Assert.AreEqual(0, result.Childs[0].Childs.Count);
            Assert.AreEqual(3, result.Childs[0].Metadata.Count);
            Assert.AreEqual(10, result.Childs[0].Metadata[0]);
            Assert.AreEqual(11, result.Childs[0].Metadata[1]);
            Assert.AreEqual(12, result.Childs[0].Metadata[2]);

            Assert.AreEqual(1, result.Childs[1].Childs.Count);
            Assert.AreEqual(1, result.Childs[1].Metadata.Count);
            Assert.AreEqual(2, result.Childs[1].Metadata[0]);

            Assert.AreEqual(0, result.Childs[1].Childs[0].Childs.Count);
            Assert.AreEqual(1, result.Childs[1].Childs[0].Metadata.Count);
            Assert.AreEqual(99, result.Childs[1].Childs[0].Metadata[0]);
        }
예제 #5
0
        // Tests that a listener is only invoked by a single thread at any time even if multiple threads are
        // invoking the wrapper concurrently.
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public void concurrentExecution() throws InterruptedException
        public virtual void concurrentExecution()
        {
            int nThreads         = Runtime.Runtime.availableProcessors();
            int resultsPerThread = 10;
            ConcurrentLinkedQueue <string> errors = new ConcurrentLinkedQueue <string>();

            System.Threading.CountdownEvent latch = new System.Threading.CountdownEvent(1);
            int      expectedResultCount          = nThreads * resultsPerThread;
            Listener listener = new Listener(errors, latch);

            System.Action <CalculationResults> wrapper = new ListenerWrapper(listener, expectedResultCount, ImmutableList.of(), ImmutableList.of());
            ExecutorService    executor = Executors.newFixedThreadPool(nThreads);
            CalculationResult  result   = CalculationResult.of(0, 0, Result.failure(FailureReason.ERROR, "foo"));
            CalculationTarget  target   = new CalculationTargetAnonymousInnerClass(this);
            CalculationResults results  = CalculationResults.of(target, ImmutableList.of(result));

            IntStream.range(0, expectedResultCount).forEach(i => executor.submit(() => wrapper(results)));

            latch.await();
            executor.shutdown();

            if (!errors.Empty)
            {
//JAVA TO C# CONVERTER TODO TASK: Most Java stream collectors are not converted by Java to C# Converter:
                string allErrors = errors.collect(joining("\n"));
                fail(allErrors);
            }
        }
        public TradeReport runReport(ReportCalculationResults results, TradeReportTemplate reportTemplate)
        {
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: com.google.common.collect.ImmutableTable.Builder<int, int, com.opengamma.strata.collect.result.Result<?>> resultTable = com.google.common.collect.ImmutableTable.builder();
            ImmutableTable.Builder <int, int, Result <object> > resultTable = ImmutableTable.builder();

            for (int reportColumnIdx = 0; reportColumnIdx < reportTemplate.Columns.Count; reportColumnIdx++)
            {
                TradeReportColumn reportColumn = reportTemplate.Columns[reportColumnIdx];
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: java.util.List<com.opengamma.strata.collect.result.Result<?>> columnResults;
                IList <Result <object> > columnResults;

                if (reportColumn.Value.Present)
                {
                    columnResults = ValuePathEvaluator.evaluate(reportColumn.Value.get(), results);
                }
                else
                {
                    columnResults = IntStream.range(0, results.Targets.Count).mapToObj(i => Result.failure(FailureReason.INVALID, "No value specified in report template")).collect(toImmutableList());
                }
                int rowCount = results.CalculationResults.RowCount;

                for (int rowIdx = 0; rowIdx < rowCount; rowIdx++)
                {
                    resultTable.put(rowIdx, reportColumnIdx, columnResults[rowIdx]);
                }
            }

            return(TradeReport.builder().runInstant(Instant.now()).valuationDate(results.ValuationDate).columns(reportTemplate.Columns).data(resultTable.build()).build());
        }
 public virtual void coverage()
 {
     MapStream.empty().filter(e => false).distinct().sorted().sorted((e1, e2) => 0).peek(e => e.ToString()).limit(0).skip(0).sequential().parallel().unordered().onClose(() => Console.WriteLine()).close();
     MapStream.empty().anyMatch(e => true);
     MapStream.empty().allMatch(e => true);
     MapStream.empty().noneMatch(e => true);
     MapStream.empty().count();
     MapStream.empty().findAny();
     MapStream.empty().findFirst();
     MapStream.empty().max((e1, e2) => 0);
     MapStream.empty().min((e1, e2) => 0);
     MapStream.empty().GetEnumerator();
     MapStream.empty().spliterator();
     MapStream.empty().Parallel;
     MapStream.empty().map(e => e);
     MapStream.empty().mapToInt(e => 0);
     MapStream.empty().mapToLong(e => 0);
     MapStream.empty().mapToDouble(e => 0);
     MapStream.empty().flatMap(e => Stream.empty());
     MapStream.empty().flatMapToDouble(e => DoubleStream.empty());
     MapStream.empty().flatMapToInt(e => IntStream.empty());
     MapStream.empty().flatMapToLong(e => LongStream.empty());
     MapStream.empty().collect(toList());
     MapStream.empty().collect(() => null, (o, e) => Console.WriteLine(), (o1, o2) => Console.WriteLine());
     MapStream.empty().toArray();
     MapStream.empty().toArray(i => new object[0]);
     MapStream.empty().forEach(e => Console.WriteLine());
     MapStream.empty().forEachOrdered(e => Console.WriteLine());
     MapStream.empty().reduce(new AbstractMap.SimpleEntry <>(null, null), (o1, o2) => null);
     MapStream.empty().reduce((o1, o2) => null);
     MapStream.empty().reduce(null, (o, e) => null, (o1, o2) => null);
 }
예제 #8
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldCorrectlyReturnCoreMemberRoles()
        public virtual void ShouldCorrectlyReturnCoreMemberRoles()
        {
            //given
            int numMembers = 3;

            IList <MemberId> members = IntStream.range(0, numMembers).mapToObj(ignored => new MemberId(System.Guid.randomUUID())).collect(Collectors.toList());

//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @SuppressWarnings("unchecked") com.hazelcast.core.IAtomicReference<org.neo4j.causalclustering.core.consensus.LeaderInfo> leaderRef = mock(com.hazelcast.core.IAtomicReference.class);
            IAtomicReference <LeaderInfo> leaderRef = mock(typeof(IAtomicReference));
            MemberId chosenLeaderId = members[0];

            when(leaderRef.get()).thenReturn(new LeaderInfo(chosenLeaderId, 0L));

//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @SuppressWarnings("unchecked") com.hazelcast.core.IMap<String,java.util.UUID> uuidDBMap = mock(com.hazelcast.core.IMap.class);
            IMap <string, System.Guid> uuidDBMap = mock(typeof(IMap));

            when(uuidDBMap.Keys).thenReturn(Collections.singleton(DEFAULT_DB_NAME));
            when(_hzInstance.getAtomicReference <LeaderInfo>(startsWith(DB_NAME_LEADER_TERM_PREFIX))).thenReturn(leaderRef);
            when(_hzInstance.getMap <string, System.Guid>(eq(CLUSTER_UUID_DB_NAME_MAP))).thenReturn(uuidDBMap);

            // when
            IDictionary <MemberId, RoleInfo> roleMap = HazelcastClusterTopology.GetCoreRoles(_hzInstance, new HashSet <MemberId, RoleInfo>(members));

            // then
            assertEquals("First member was expected to be leader.", RoleInfo.Leader, roleMap[chosenLeaderId]);
        }
예제 #9
0
        private ISet <string> MakeWithPrefix(string prefix, int n)
        {
            ISet <string> set = new LinkedHashSet <string>();

            IntStream.range(0, n).forEach(i => set.Add(prefix + i));
            return(set);
        }
예제 #10
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldBootstrapWhenBootstrappable() throws Throwable
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldBootstrapWhenBootstrappable()
        {
            // given
//JAVA TO C# CONVERTER TODO TASK: Method reference arbitrary object instance method syntax is not converted by Java to C# Converter:
            IDictionary <MemberId, CoreServerInfo> members = IntStream.range(0, _minCoreHosts).mapToObj(i => Pair.of(new MemberId(System.Guid.randomUUID()), TestTopology.addressesForCore(i, false))).collect(Collectors.toMap(Pair::first, Pair::other));

            CoreTopology bootstrappableTopology = new CoreTopology(null, true, members);

            CoreTopologyService topologyService = mock(typeof(CoreTopologyService));

            when(topologyService.LocalCoreServers()).thenReturn(bootstrappableTopology);
            when(topologyService.SetClusterId(any(), eq("default"))).thenReturn(true);
            CoreSnapshot snapshot = mock(typeof(CoreSnapshot));

            when(_coreBootstrapper.bootstrap(any())).thenReturn(snapshot);

            ClusterBinder binder = ClusterBinder(new StubSimpleStorage <ClusterId>(this), topologyService);

            // when
            BoundState boundState = binder.BindToCluster();

            // then
            verify(_coreBootstrapper).bootstrap(any());
            Optional <ClusterId> clusterId = binder.Get();

            assertTrue(clusterId.Present);
            verify(topologyService).setClusterId(clusterId.get(), "default");
            assertTrue(boundState.Snapshot().Present);
            assertEquals(boundState.Snapshot().get(), snapshot);
        }
예제 #11
0
    public static void Main()
    {
        var primeStream  = new PrimeStream();
        var intStream    = new IntStream();
        var stringStream = new RandomWordStream();

        Console.WriteLine("How many strings do you want to generate?");
        Console.WriteLine("(Enter a number smaller than 1 to generate the entire stream)");
        var input = Console.ReadLine();
        int amount;

        if (!int.TryParse(input, out amount))
        {
            Console.WriteLine("Invalid input!");
            return;
        }

        if (amount <= 0)
        {
            while (!stringStream.Eos())
            {
                Console.WriteLine("{0}) {1} characters: {2}", intStream.Next(), primeStream.Next(), stringStream.Next());
            }
        }
        else
        {
            for (int i = intStream.Next(); i < amount; i++)
            {
                Console.WriteLine("{0}) {1} characters: {2}", intStream.Next(), primeStream.Next(), stringStream.Next());
            }
        }
    }
예제 #12
0
    public static void Main(string[] args)
    {
        IntStream test = new IntStream();

        Console.WriteLine("{0}", test.x);
        Console.WriteLine("{0}", test.next());
        Console.WriteLine("{0}", test.next());
        test.x = int.MaxValue;
        Console.WriteLine("{0}", test.eos());
        RandomStream tescik = new RandomStream();

        Console.WriteLine(tescik.x);
        tescik.reset();
        Console.WriteLine(tescik.x);
        Console.WriteLine(tescik.next());
        Console.WriteLine(tescik.eos());
        PrimeStream tescik2 = new PrimeStream();

        for (int i = 0; i < 5; i++)
        {
            Console.WriteLine(tescik2.next());
        }

        RandomWordStream a = new RandomWordStream();

        for (int i = 0; i < 20; i++)
        {
            Console.WriteLine(a.next());
        }
    }
예제 #13
0
        static void Main()
        {
            IntStream a = new IntStream();

            System.Console.WriteLine(a.next());
            System.Console.WriteLine(a.next());
            System.Console.WriteLine();

            a.reset();
            System.Console.WriteLine(a.next());
            System.Console.WriteLine(a.next());
            System.Console.WriteLine();

            Primestream p = new Primestream();

            System.Console.WriteLine(p.next());
            System.Console.WriteLine(p.next());
            System.Console.WriteLine(p.next());
            System.Console.WriteLine(p.next());
            System.Console.WriteLine();

            RandomStream r = new RandomStream();

            System.Console.WriteLine(r.next());
            System.Console.WriteLine(r.next());
            System.Console.WriteLine(r.next());
            System.Console.WriteLine();

            RandomWordStream rs = new RandomWordStream();

            System.Console.WriteLine(rs.next());
            System.Console.WriteLine(rs.next());
            System.Console.WriteLine(rs.next());
            System.Console.Read();
        }
        //-------------------------------------------------------------------------
        /// <summary>
        /// Outputs the report table in CSV format.
        /// </summary>
        /// <param name="report">  the report </param>
        /// <param name="out">  the output stream to write to </param>
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @SuppressWarnings("resource") public void writeCsv(R report, java.io.OutputStream out)
        public virtual void writeCsv(R report, Stream @out)
        {
            StreamWriter outputWriter = new StreamWriter(@out, Encoding.UTF8);
            CsvOutput    csvOut       = CsvOutput.safe(outputWriter);

            csvOut.writeLine(report.ColumnHeaders);
            IntStream.range(0, report.RowCount).mapToObj(rowIdx => formatRow(report, rowIdx, ReportOutputFormat.CSV)).forEach(csvOut.writeLine);
            Unchecked.wrap(outputWriter.flush);
        }
        private MarketDataBox <R> combineWithMultiple <U, R>(MarketDataBox <U> other, System.Func <T, U, R> fn)
        {
            ScenarioArray <U> otherValue = other.ScenarioValue;
            int scenarioCount            = otherValue.ScenarioCount;

            IList <R> values = IntStream.range(0, scenarioCount).mapToObj(i => fn(value, other.getValue(i))).collect(toImmutableList());

            return(MarketDataBox.ofScenarioValues(values));
        }
예제 #16
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void consistencyCheckerMustBeAbleToRunOnStoreWithFulltextIndexes() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ConsistencyCheckerMustBeAbleToRunOnStoreWithFulltextIndexes()
        {
            GraphDatabaseService db = CreateDatabase();

//JAVA TO C# CONVERTER TODO TASK: Method reference constructor syntax is not converted by Java to C# Converter:
            Label[] labels = IntStream.range(1, 7).mapToObj(i => Label.label("LABEL" + i)).toArray(Label[] ::new);
//JAVA TO C# CONVERTER TODO TASK: Method reference constructor syntax is not converted by Java to C# Converter:
            RelationshipType[] relTypes = IntStream.range(1, 5).mapToObj(i => RelationshipType.withName("REL" + i)).toArray(RelationshipType[] ::new);
//JAVA TO C# CONVERTER TODO TASK: Method reference constructor syntax is not converted by Java to C# Converter:
            string[]     propertyKeys = IntStream.range(1, 7).mapToObj(i => "PROP" + i).toArray(string[] ::new);
            RandomValues randomValues = RandomValues.create();

            using (Transaction tx = Db.beginTx())
            {
                ThreadLocalRandom rng  = ThreadLocalRandom.current();
                int          nodeCount = 1000;
                IList <Node> nodes     = new List <Node>(nodeCount);
                for (int i = 0; i < nodeCount; i++)
                {
//JAVA TO C# CONVERTER TODO TASK: Method reference constructor syntax is not converted by Java to C# Converter:
                    Label[] nodeLabels = rng.ints(rng.Next(labels.Length), 0, labels.Length).distinct().mapToObj(x => labels[x]).toArray(Label[] ::new);
                    Node    node       = Db.createNode(nodeLabels);
                    Stream.of(propertyKeys).forEach(p => node.setProperty(p, rng.nextBoolean() ? p : randomValues.NextValue().asObject()));
                    nodes.Add(node);
                    int localRelCount = Math.Min(nodes.Count, 5);
                    rng.ints(localRelCount, 0, localRelCount).distinct().mapToObj(x => node.CreateRelationshipTo(nodes[x], relTypes[rng.Next(relTypes.Length)])).forEach(r => Stream.of(propertyKeys).forEach(p => r.setProperty(p, rng.nextBoolean() ? p : randomValues.NextValue().asObject())));
                }
                tx.Success();
            }

            using (Transaction tx = Db.beginTx())
            {
                for (int i = 1; i < labels.Length; i++)
                {
//JAVA TO C# CONVERTER TODO TASK: Method reference arbitrary object instance method syntax is not converted by Java to C# Converter:
//JAVA TO C# CONVERTER TODO TASK: Method reference constructor syntax is not converted by Java to C# Converter:
                    Db.execute(format(NODE_CREATE, "nodes" + i, array(java.util.labels.Take(i).Select(Label::name).ToArray(string[] ::new)), array(Arrays.copyOf(propertyKeys, i)))).close();
                }
                for (int i = 1; i < relTypes.Length; i++)
                {
//JAVA TO C# CONVERTER TODO TASK: Method reference arbitrary object instance method syntax is not converted by Java to C# Converter:
//JAVA TO C# CONVERTER TODO TASK: Method reference constructor syntax is not converted by Java to C# Converter:
                    Db.execute(format(RELATIONSHIP_CREATE, "rels" + i, array(java.util.relTypes.Take(i).Select(RelationshipType::name).ToArray(string[] ::new)), array(Arrays.copyOf(propertyKeys, i)))).close();
                }
                tx.Success();
            }

            using (Transaction tx = Db.beginTx())
            {
                Db.schema().awaitIndexesOnline(1, TimeUnit.MINUTES);
                tx.Success();
            }

            Db.shutdown();

            AssertIsConsistent(CheckConsistency());
        }
예제 #17
0
파일: zad1.cs 프로젝트: rafpacut/ii
    public static void Main()
    {
        System.Console.WriteLine("IntStream");
        //IntStream
        IntStream iss = new IntStream();

        writeout(iss.next());
        writeout(iss.next());
        System.Console.WriteLine(iss.eos());
        iss.reset();
        System.Console.WriteLine(iss.eos());
        writeout(iss.next());

        while (!iss.eos())
        {
            iss.next();
        }
        System.Console.WriteLine("PrimeStream");


        //PrimeStream
        PrimeStream ps = new PrimeStream();

        for (int i = 0; i < 12; i++)
        {
            writeout(ps.next());
        }
        ps.reset();
        for (int i = 0; i < 12; i++)
        {
            writeout(ps.next());
        }
        System.Console.WriteLine("RandomStream");

        //RandomStream
        RandomStream rst = new RandomStream();

        writeout(rst.next());
        writeout(rst.next());
        writeout(rst.next());
        writeout(rst.next());

        System.Console.WriteLine("RandomWordStream");

        //RandomWordStream

        RandomWordStream rws = new RandomWordStream();
        RandomStream     rs1 = new RandomStream();
        PrimeStream      ps1 = new PrimeStream();

        for (int i = 0; i < 12; i++)
        {
            int prime = ps1.next();
            System.Console.WriteLine(rws.next(prime, rs1));
        }
    }
예제 #18
0
        public override CombinedCurve withPerturbation(ParameterPerturbation perturbation)
        {
            Curve newBaseCurve   = baseCurve.withPerturbation((idx, value, meta) => perturbation(idx, baseCurve.getParameter(idx), baseCurve.getParameterMetadata(idx)));
            int   offset         = baseCurve.ParameterCount;
            Curve newSpreadCurve = spreadCurve.withPerturbation((idx, value, meta) => perturbation(idx + offset, spreadCurve.getParameter(idx), spreadCurve.getParameterMetadata(idx)));

            IList <ParameterMetadata> newParamMeta = Stream.concat(IntStream.range(0, newBaseCurve.ParameterCount).mapToObj(i => newBaseCurve.getParameterMetadata(i)), IntStream.range(0, newSpreadCurve.ParameterCount).mapToObj(i => newSpreadCurve.getParameterMetadata(i))).collect(toImmutableList());

            return(CombinedCurve.of(newBaseCurve, newSpreadCurve, metadata.withParameterMetadata(newParamMeta)));
        }
        public MarketDataBox <R> mapWithIndex <R>(int scenarioCount, ObjIntFunction <T, R> fn)
        {
            if (scenarioCount != ScenarioCount)
            {
                throw new System.ArgumentException(Messages.format("Scenario count {} does not equal the scenario count of the value {}", scenarioCount, ScenarioCount));
            }
            IList <R> perturbedValues = IntStream.range(0, scenarioCount).mapToObj(idx => fn.apply(getValue(idx), idx)).collect(toImmutableList());

            return(MarketDataBox.ofScenarioValues(perturbedValues));
        }
예제 #20
0
        public virtual void test_loadAllDates()
        {
            LocalDate sampleDate = ALL_DATES[3];     // 2017-04-21
            ImmutableList <LocalDate> expDates  = ImmutableList.of(LocalDate.of(2017, 0x7, 21), LocalDate.of(2017, 10, 0x7), LocalDate.of(2018, 4, 13), LocalDate.of(2019, 4, 12), LocalDate.of(2020, 3, 20), LocalDate.of(2021, 3, 19), LocalDate.of(2022, 3, 19), LocalDate.of(2023, 3, 17), LocalDate.of(2024, 6, 17), LocalDate.of(2025, 3, 18), LocalDate.of(2026, 3, 20), LocalDate.of(2027, 3, 20), LocalDate.of(2031, 12, 19), LocalDate.of(2037, 3, 17), LocalDate.of(2047, 3, 17), LocalDate.of(2056, 3, 17));
            ImmutableList <string>    expTenors = ImmutableList.of("3M", "6M", "1Y", "2Y", "3Y", "4Y", "5Y", "6Y", "7Y", "8Y", "9Y", "10Y", "15Y", "20Y", "30Y", "40Y");
            RepoGroup   repoGroup      = RepoGroup.of("JP-REPO");
            DoubleArray expRepoXValues = DoubleArray.of(3, n => ACT_365F.relativeYearFraction(sampleDate, expDates.get(n)));
            DoubleArray expRepoYValues = DoubleArray.of(-0.0019521, -0.0016021, -0.0022521);
            ImmutableList <LabelDateParameterMetadata> expRepoMetadata = IntStream.range(0, 3).mapToObj(n => LabelDateParameterMetadata.of(expDates.get(n), expTenors.get(n))).collect(Guavate.toImmutableList());
            LegalEntityGroup legalEntityGroup = LegalEntityGroup.of("JP-GOVT");
            DoubleArray      expIssuerXValues = DoubleArray.of(expDates.size(), n => ACT_365F.relativeYearFraction(sampleDate, expDates.get(n)));
            DoubleArray      expIssuerYValues = DoubleArray.of(-0.0019511690511744527, -0.001497422302092893, -0.0021798583657932176, -0.002215700360912938, -0.0021722324679574866, -0.001922059591219172, -0.0015461646763548528, -0.0014835851245462084, -0.001118669580570464, -5.476767138782941E-4, -2.2155596172855965E-4, 2.0333291172821893E-5, 0.00284500423293463, 0.005876533417933958, 0.007957581583531789, 0.009134630405512047);
            ImmutableList <LabelDateParameterMetadata> expIssuerMetadata = IntStream.range(0, expDates.size()).mapToObj(n => LabelDateParameterMetadata.of(expDates.get(n), expTenors.get(n))).collect(Guavate.toImmutableList());

            ImmutableListMultimap <LocalDate, LegalEntityCurveGroup> allCurves = LegalEntityRatesCurvesCsvLoader.loadAllDates(ResourceLocator.of(GROUPS), ResourceLocator.of(SETTINGS), ImmutableList.of(ResourceLocator.of(CURVES_1), ResourceLocator.of(CURVES_2)));

//JAVA TO C# CONVERTER TODO TASK: There is no .NET equivalent to the java.util.Collection 'containsAll' method:
            assertTrue(allCurves.Keys.containsAll(ALL_DATES));
            ImmutableList <LegalEntityCurveGroup> groups = allCurves.get(sampleDate);

            assertEquals(groups.size(), 2);
            // group 0
            LegalEntityCurveGroup group0 = groups.get(0);

            assertEquals(group0.Name, CurveGroupName.of("Default1"));
            // repo
            assertEquals(group0.RepoCurves.size(), 1);
            Curve repoCurve = group0.RepoCurves.get(Pair.of(repoGroup, JPY));
            InterpolatedNodalCurve expectedRepoCurve = InterpolatedNodalCurve.of(Curves.zeroRates(CurveName.of("JP-REPO-1"), ACT_365F, expRepoMetadata), expRepoXValues, expRepoYValues, CurveInterpolators.LINEAR, CurveExtrapolators.FLAT, CurveExtrapolators.FLAT);

            assertEquals(repoCurve, expectedRepoCurve);
            // issuer
            assertEquals(group0.IssuerCurves.size(), 2);
            Curve issuerCurve = group0.IssuerCurves.get(Pair.of(legalEntityGroup, JPY));
            InterpolatedNodalCurve expectedIssuerCurve = InterpolatedNodalCurve.of(Curves.zeroRates(CurveName.of("JP-GOVT-1"), ACT_365F, expIssuerMetadata), expIssuerXValues, expIssuerYValues, CurveInterpolators.LINEAR, CurveExtrapolators.FLAT, CurveExtrapolators.FLAT);

            assertEquals(issuerCurve, expectedIssuerCurve);
            Curve usIssuerCurve = group0.IssuerCurves.get(Pair.of(LegalEntityGroup.of("US-GOVT"), USD));

            expectedIssuerCurve = InterpolatedNodalCurve.of(Curves.zeroRates(CurveName.of("US-GOVT"), ACT_360, expIssuerMetadata), DoubleArray.of(expDates.size(), n => ACT_360.relativeYearFraction(sampleDate, expDates.get(n))), expIssuerYValues, CurveInterpolators.NATURAL_SPLINE, CurveExtrapolators.FLAT, CurveExtrapolators.FLAT);
            assertEquals(usIssuerCurve, expectedIssuerCurve);
            // group 1
            LegalEntityCurveGroup group1 = groups.get(1);

            assertEquals(group1.Name, CurveGroupName.of("Default2"));
            // repo
            repoCurve         = group1.RepoCurves.get(Pair.of(repoGroup, JPY));
            expectedRepoCurve = InterpolatedNodalCurve.of(Curves.zeroRates(CurveName.of("JP-REPO-2"), ACT_365F, expRepoMetadata), expRepoXValues, expRepoYValues, CurveInterpolators.DOUBLE_QUADRATIC, CurveExtrapolators.LINEAR, CurveExtrapolators.LINEAR);
            assertEquals(repoCurve, expectedRepoCurve);
            // issuer
            assertEquals(group1.IssuerCurves.size(), 1);
            issuerCurve         = group1.IssuerCurves.get(Pair.of(legalEntityGroup, JPY));
            expectedIssuerCurve = InterpolatedNodalCurve.of(Curves.zeroRates(CurveName.of("JP-GOVT-2"), ACT_365F, expIssuerMetadata), expIssuerXValues, expIssuerYValues, CurveInterpolators.DOUBLE_QUADRATIC, CurveExtrapolators.LINEAR, CurveExtrapolators.LINEAR);
            assertEquals(issuerCurve, expectedIssuerCurve);
        }
        /// <summary>
        /// Outputs the report as an ASCII table.
        /// </summary>
        /// <param name="report">  the report </param>
        /// <param name="out">  the output stream to write to </param>
        public virtual void writeAsciiTable(R report, Stream @out)
        {
            IList <Type> columnTypes = getColumnTypes(report);
            IList <AsciiTableAlignment> alignments = IntStream.range(0, columnTypes.Count).mapToObj(i => calculateAlignment(columnTypes[i])).collect(toImmutableList());
            IList <string> headers = report.ColumnHeaders;
            ImmutableList <ImmutableList <string> > cells = formatAsciiTable(report);
            string      asciiTable = AsciiTable.generate(headers, alignments, cells);
            PrintWriter pw         = new PrintWriter(new StreamWriter(@out, Encoding.UTF8));

            pw.println(asciiTable);
            pw.flush();
        }
예제 #22
0
        /// <summary>
        /// Creates zoned date time.
        /// <para>
        /// If the scenario size of {@code dates} is greater than the size of {@code localTimes},
        /// {@code defaultLocalTime} is used.
        /// If {@code dates} is single value, {@code defaultLocalTime} is used.
        ///
        /// </para>
        /// </summary>
        /// <param name="dates">  the local date </param>
        /// <returns> the zoned date time </returns>
        public MarketDataBox <ZonedDateTime> toZonedDateTime(MarketDataBox <LocalDate> dates)
        {
            if (dates.ScenarioValue)
            {
                int nScenarios = dates.ScenarioCount;
                int nTimes     = localTimes.size();
                IList <ZonedDateTime> zonedDateTimes = IntStream.range(0, nScenarios).mapToObj(scenarioIndex => zonedDateTime(dates.getValue(scenarioIndex), nTimes, scenarioIndex)).collect(Collectors.toList());
                return(MarketDataBox.ofScenarioValues(zonedDateTimes));
            }
            ZonedDateTime zonedDateTime = dates.SingleValue.atTime(defaultLocalTime).atZone(zoneId);

            return(MarketDataBox.ofSingleValue(zonedDateTime));
        }
        /// <summary>
        /// Evaluates a value path against a set of results, returning the resolved result for each trade.
        /// </summary>
        /// <param name="valuePath">  the value path </param>
        /// <param name="results">  the calculation results </param>
        /// <returns> the list of resolved results for each trade </returns>
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: public static java.util.List<com.opengamma.strata.collect.result.Result<?>> evaluate(String valuePath, com.opengamma.strata.report.ReportCalculationResults results)
        public static IList <Result <object> > evaluate(string valuePath, ReportCalculationResults results)
        {
            IList <string> tokens = tokenize(valuePath);

            if (tokens.Count < 1)
            {
                return(Collections.nCopies(results.Targets.Count, Result.failure(FailureReason.INVALID, "Column expressions must not be empty")));
            }
            CalculationFunctions functions = results.CalculationFunctions;
            int rowCount = results.CalculationResults.RowCount;

            return(IntStream.range(0, rowCount).mapToObj(rowIndex => evaluate(functions, tokens, RootEvaluator.INSTANCE, new ResultsRow(results, rowIndex))).collect(toImmutableList()));
        }
        // restricted constructor
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @ImmutableConstructor private ParameterizedFunctionalCurve(CurveMetadata metadata, com.opengamma.strata.collect.array.DoubleArray parameters, System.Func<com.opengamma.strata.collect.array.DoubleArray, double, double> valueFunction, System.Func<com.opengamma.strata.collect.array.DoubleArray, double, double> derivativeFunction, System.Func<com.opengamma.strata.collect.array.DoubleArray, double, com.opengamma.strata.collect.array.DoubleArray> sensitivityFunction)
        private ParameterizedFunctionalCurve(CurveMetadata metadata, DoubleArray parameters, System.Func <DoubleArray, double, double> valueFunction, System.Func <DoubleArray, double, double> derivativeFunction, System.Func <DoubleArray, double, DoubleArray> sensitivityFunction)
        {
            JodaBeanUtils.notNull(metadata, "metadata");
            JodaBeanUtils.notNull(parameters, "parameters");
            JodaBeanUtils.notNull(valueFunction, "valueFunction");
            JodaBeanUtils.notNull(derivativeFunction, "derivativeFunction");
            JodaBeanUtils.notNull(sensitivityFunction, "sensitivityFunction");
            this.metadata            = metadata;
            this.parameters          = parameters;
            this.valueFunction       = valueFunction;
            this.derivativeFunction  = derivativeFunction;
            this.sensitivityFunction = sensitivityFunction;
            this.parameterMetadata   = IntStream.range(0, ParameterCount).mapToObj(i => getParameterMetadata(i)).collect(toImmutableList());
        }
예제 #25
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void storeAndLoad_Big_CompositeMultiTokenSchemaRule() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void StoreAndLoadBigCompositeMultiTokenSchemaRule()
        {
            // GIVEN
            StoreIndexDescriptor indexRule = forSchema(multiToken(IntStream.range(1, 200).toArray(), EntityType.RELATIONSHIP, IntStream.range(1, 200).toArray()), PROVIDER_DESCRIPTOR).withId(_store.nextId());

            // WHEN
            StoreIndexDescriptor readIndexRule = ( StoreIndexDescriptor )SchemaRuleSerialization.deserialize(indexRule.Id, wrap(SchemaRuleSerialization.serialize(indexRule)));

            // THEN
            assertEquals(indexRule.Id, readIndexRule.Id);
            assertEquals(indexRule.Schema(), readIndexRule.Schema());
            assertEquals(indexRule, readIndexRule);
            assertEquals(indexRule.ProviderDescriptor(), readIndexRule.ProviderDescriptor());
        }
예제 #26
0
        public virtual MarketDataBox <FxOptionVolatilities> build(FxOptionVolatilitiesId id, MarketDataConfig marketDataConfig, ScenarioMarketData marketData, ReferenceData refData)
        {
            FxOptionVolatilitiesDefinition volatilitiesDefinition = marketDataConfig.get(typeof(FxOptionVolatilitiesDefinition), id.Name.Name);
            ValuationZoneTimeDefinition    zoneTimeDefinition     = marketDataConfig.get(typeof(ValuationZoneTimeDefinition));
            int nScenarios = marketData.ScenarioCount;
            MarketDataBox <LocalDate>     valuationDates     = marketData.ValuationDate;
            MarketDataBox <ZonedDateTime> valuationDateTimes = zoneTimeDefinition.toZonedDateTime(valuationDates);

            int nParameters = volatilitiesDefinition.ParameterCount;
//JAVA TO C# CONVERTER TODO TASK: Most Java stream collectors are not converted by Java to C# Converter:
            ImmutableList <MarketDataBox <double> > inputs = volatilitiesDefinition.volatilitiesInputs().Select(q => marketData.getValue(q)).collect(toImmutableList());
            ImmutableList <FxOptionVolatilities>    vols   = IntStream.range(0, nScenarios).mapToObj(scenarioIndex => volatilitiesDefinition.volatilities(valuationDateTimes.getValue(scenarioIndex), DoubleArray.of(nParameters, paramIndex => inputs.get(paramIndex).getValue(scenarioIndex)), refData)).collect(toImmutableList());

            return(nScenarios > 1 ? MarketDataBox.ofScenarioValues(vols) : MarketDataBox.ofSingleValue(vols.get(0)));
        }
        // computes the sensitivity of baseDeltaSingle to Curve
        internal CrossGammaParameterSensitivity computeGammaForCurve(CurrencyParameterSensitivity baseDeltaSingle, Curve curve, System.Func <Curve, ImmutableRatesProvider> ratesProviderFn, System.Func <ImmutableRatesProvider, CurrencyParameterSensitivities> sensitivitiesFn)
        {
            System.Func <DoubleArray, DoubleArray> function = (DoubleArray t) =>
            {
                Curve newCurve = replaceParameters(curve, t);
                ImmutableRatesProvider         newRates   = ratesProviderFn(newCurve);
                CurrencyParameterSensitivities sensiMulti = sensitivitiesFn(newRates);
                return(sensiMulti.getSensitivity(baseDeltaSingle.MarketDataName, baseDeltaSingle.Currency).Sensitivity);
            };
            int          nParams = curve.ParameterCount;
            DoubleMatrix sensi   = fd.differentiate(function).apply(DoubleArray.of(nParams, n => curve.getParameter(n)));
            IList <ParameterMetadata> metadata = IntStream.range(0, nParams).mapToObj(i => curve.getParameterMetadata(i)).collect(toImmutableList());

            return(CrossGammaParameterSensitivity.of(baseDeltaSingle.MarketDataName, baseDeltaSingle.ParameterMetadata, curve.Name, metadata, baseDeltaSingle.Currency, sensi));
        }
        private CrossGammaParameterSensitivity computeGammaForCurve(CurveName curveName, Curve curve, Currency sensitivityCurrency, System.Func <Curve, ImmutableLegalEntityDiscountingProvider> ratesProviderFn, System.Func <ImmutableLegalEntityDiscountingProvider, CurrencyParameterSensitivities> sensitivitiesFn)
        {
            System.Func <DoubleArray, DoubleArray> function = (DoubleArray t) =>
            {
                Curve newCurve = curve.withPerturbation((i, v, m) => t.get(i));
                ImmutableLegalEntityDiscountingProvider newRates   = ratesProviderFn(newCurve);
                CurrencyParameterSensitivities          sensiMulti = sensitivitiesFn(newRates);
                return(sensiMulti.getSensitivity(curveName, sensitivityCurrency).Sensitivity);
            };
            int          nParams = curve.ParameterCount;
            DoubleMatrix sensi   = fd.differentiate(function).apply(DoubleArray.of(nParams, n => curve.getParameter(n)));
            IList <ParameterMetadata> metadata = IntStream.range(0, nParams).mapToObj(i => curve.getParameterMetadata(i)).collect(toImmutableList());

            return(CrossGammaParameterSensitivity.of(curveName, metadata, sensitivityCurrency, sensi));
        }
예제 #29
0
        private SortedDictionary <int, Configuration> CreateConfigurations()
        {
            SortedDictionary <int, Configuration> configurations = new SortedDictionary <int, Configuration>();

            IntStream.range(0, 3).forEach(serverId =>
            {
                int clusterPort = PortAuthority.allocatePort();
                int haPort      = PortAuthority.allocatePort();
                File directory  = TestDirectory.databaseDir(Convert.ToString(serverId)).AbsoluteFile;

                configurations[serverId] = new Configuration(this, serverId, clusterPort, haPort, directory);
            });

            return(configurations);
        }
예제 #30
0
    static void Main()
    {
        int              i;
        PrimeStream      ps    = new PrimeStream();
        IntStream        ins   = new IntStream();
        RandomStream     rnd   = new RandomStream();
        RandomWordStream rndws = new RandomWordStream();

        Console.WriteLine(rnd.next());
        Console.WriteLine(rnd.next());
        Console.WriteLine(rnd.next());
        Console.WriteLine(ins.next());
        Console.WriteLine(ps.next());
        Console.WriteLine(ps.next());
        Console.WriteLine(ps.next());

        Console.WriteLine(rndws.next());
        Console.WriteLine(rndws.next());
        Console.WriteLine(rndws.next());

        rnd.reset();
        ins.reset();
        ins.next();
        for (i = 0; i < 10; i++)
        {
            Console.WriteLine("{0} losowa liczba: {1}", ins.next(), rnd.next());
        }

        rndws.reset();
        ps.reset();
        for (i = 0; i < 15; i++)
        {
            Console.WriteLine("slowo o dl = {0}: {1}", ps.next(), rndws.next());
        }
        ps.reset();
        for (i = 0; i < 30; i++)
        {
            Console.WriteLine("{0} liczba pierwsza = {1}", i + 1, ps.next());
        }
        ins.reset();
        int p = 0;

        while (!ins.eos())
        {
            p = ins.next();
        }
        Console.WriteLine("najwieksza liczba typu int = {0}", p);
    }