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()); }
//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)); }
//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); }
// 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); } }
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); }
//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]); }
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)); }
//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()); }
//------------------------------------------------------------------------- /// <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); }
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)); }
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 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(); }
/// <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())); }
/// <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)); }
//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()); }
// 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()); }
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))); }
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); }
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)); }
// 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)); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void rulesCreatedWithNameMustRetainGivenNameAfterDeserialisation() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void RulesCreatedWithNameMustRetainGivenNameAfterDeserialisation() { string name = "custom_rule"; assertThat(SerialiseAndDeserialise(NamedForLabel(name, LABEL_ID, PROPERTY_ID_1).withId(RULE_ID)).Name, @is(name)); assertThat(SerialiseAndDeserialise(NamedUniqueForLabel(name, LABEL_ID, PROPERTY_ID_1).withIds(RULE_ID_2, RULE_ID)).Name, @is(name)); assertThat(SerialiseAndDeserialise(NamedForLabel(name, LABEL_ID, PROPERTY_ID_1, PROPERTY_ID_2).withId(RULE_ID)).Name, @is(name)); assertThat(SerialiseAndDeserialise(NamedUniqueForLabel(name, LABEL_ID, PROPERTY_ID_1, PROPERTY_ID_2).withIds(RULE_ID_2, RULE_ID)).Name, @is(name)); assertThat(SerialiseAndDeserialise(NamedForLabel(name, LABEL_ID, IntStream.range(1, 200).toArray()).withId(RULE_ID)).Name, @is(name)); assertThat(SerialiseAndDeserialise(ConstraintRule.constraintRule(RULE_ID, ConstraintDescriptorFactory.existsForLabel(LABEL_ID, PROPERTY_ID_1), name)).Name, @is(name)); assertThat(SerialiseAndDeserialise(ConstraintRule.ConstraintRuleConflict(RULE_ID_2, ConstraintDescriptorFactory.uniqueForLabel(LABEL_ID, PROPERTY_ID_1), RULE_ID, name)).Name, @is(name)); assertThat(SerialiseAndDeserialise(ConstraintRule.ConstraintRuleConflict(RULE_ID_2, ConstraintDescriptorFactory.nodeKeyForLabel(LABEL_ID, PROPERTY_ID_1), RULE_ID, name)).Name, @is(name)); assertThat(SerialiseAndDeserialise(ConstraintRule.constraintRule(RULE_ID_2, ConstraintDescriptorFactory.existsForRelType(REL_TYPE_ID, PROPERTY_ID_1), name)).Name, @is(name)); assertThat(SerialiseAndDeserialise(ConstraintRule.constraintRule(RULE_ID, ConstraintDescriptorFactory.existsForLabel(LABEL_ID, PROPERTY_ID_1, PROPERTY_ID_2), name)).Name, @is(name)); assertThat(SerialiseAndDeserialise(ConstraintRule.constraintRule(RULE_ID_2, ConstraintDescriptorFactory.existsForRelType(REL_TYPE_ID, PROPERTY_ID_1, PROPERTY_ID_2), name)).Name, @is(name)); }
internal virtual IDictionary <int, string> DistributeHostsBetweenDatabases(int nHosts, IList <string> databases) { //Max number of hosts per database is (nHosts / nDatabases) or (nHosts / nDatabases) + 1 int nDatabases = databases.Count; int maxCapacity = (nHosts % nDatabases == 0) ? (nHosts / nDatabases) : (nHosts / nDatabases) + 1; IList <string> repeated = databases.stream().flatMap(db => IntStream.range(0, maxCapacity).mapToObj(ignored => db)).collect(Collectors.toList()); IDictionary <int, string> mapping = new Dictionary <int, string>(nHosts); for (int hostId = 0; hostId < nHosts; hostId++) { mapping[hostId] = repeated[hostId]; } return(mapping); }
/// <summary> /// Creates a curve as the sum of a base curve and a spread curve. /// <para> /// The metadata of the combined curve will be created form the base curve and spread curve. /// /// </para> /// </summary> /// <param name="baseCurve"> the base curve </param> /// <param name="spreadCurve"> the spread curve </param> /// <returns> the combined curve </returns> public static CombinedCurve of(Curve baseCurve, Curve spreadCurve) { CurveMetadata baseMetadata = baseCurve.Metadata; CurveMetadata spreadMetadata = spreadCurve.Metadata; IList <ParameterMetadata> paramMeta = Stream.concat(IntStream.range(0, baseCurve.ParameterCount).mapToObj(i => baseCurve.getParameterMetadata(i)), IntStream.range(0, spreadCurve.ParameterCount).mapToObj(i => spreadCurve.getParameterMetadata(i))).collect(toImmutableList()); DefaultCurveMetadataBuilder metadataBuilder = DefaultCurveMetadata.builder().curveName(baseCurve.Name.Name + "+" + spreadMetadata.CurveName.Name).xValueType(baseMetadata.XValueType).yValueType(baseMetadata.YValueType).parameterMetadata(paramMeta); if (baseMetadata.findInfo(CurveInfoType.DAY_COUNT).Present) { metadataBuilder.addInfo(CurveInfoType.DAY_COUNT, baseMetadata.getInfo(CurveInfoType.DAY_COUNT)); } return(of(baseCurve, spreadCurve, metadataBuilder.build())); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void rulesCreatedWithNullNameMustRetainComputedNameAfterDeserialisation() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void RulesCreatedWithNullNameMustRetainComputedNameAfterDeserialisation() { assertThat(SerialiseAndDeserialise(ForLabel(LABEL_ID, PROPERTY_ID_1).withId(RULE_ID)).Name, @is("index_1")); assertThat(SerialiseAndDeserialise(UniqueForLabel(LABEL_ID, PROPERTY_ID_1).withIds(RULE_ID_2, RULE_ID)).Name, @is("index_2")); assertThat(SerialiseAndDeserialise(ForLabel(LABEL_ID, PROPERTY_ID_1, PROPERTY_ID_2).withId(RULE_ID)).Name, @is("index_1")); assertThat(SerialiseAndDeserialise(UniqueForLabel(LABEL_ID, PROPERTY_ID_1, PROPERTY_ID_2).withIds(RULE_ID_2, RULE_ID)).Name, @is("index_2")); assertThat(SerialiseAndDeserialise(ForLabel(LABEL_ID, IntStream.range(1, 200).toArray()).withId(RULE_ID)).Name, @is("index_1")); string name = null; assertThat(SerialiseAndDeserialise(ConstraintRule.constraintRule(RULE_ID, ConstraintDescriptorFactory.existsForLabel(LABEL_ID, PROPERTY_ID_1), name)).Name, @is("constraint_1")); assertThat(SerialiseAndDeserialise(ConstraintRule.ConstraintRuleConflict(RULE_ID_2, ConstraintDescriptorFactory.uniqueForLabel(LABEL_ID, PROPERTY_ID_1), RULE_ID, name)).Name, @is("constraint_2")); assertThat(SerialiseAndDeserialise(ConstraintRule.ConstraintRuleConflict(RULE_ID_2, ConstraintDescriptorFactory.nodeKeyForLabel(LABEL_ID, PROPERTY_ID_1), RULE_ID, name)).Name, @is("constraint_2")); assertThat(SerialiseAndDeserialise(ConstraintRule.constraintRule(RULE_ID_2, ConstraintDescriptorFactory.existsForRelType(REL_TYPE_ID, PROPERTY_ID_1), name)).Name, @is("constraint_2")); assertThat(SerialiseAndDeserialise(ConstraintRule.constraintRule(RULE_ID, ConstraintDescriptorFactory.existsForLabel(LABEL_ID, PROPERTY_ID_1, PROPERTY_ID_2), name)).Name, @is("constraint_1")); assertThat(SerialiseAndDeserialise(ConstraintRule.constraintRule(RULE_ID_2, ConstraintDescriptorFactory.existsForRelType(REL_TYPE_ID, PROPERTY_ID_1, PROPERTY_ID_2), name)).Name, @is("constraint_2")); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test(expected = java.util.concurrent.TimeoutException.class) public void shouldTimeoutIfPublishContinuallyFailsWithTransientErrors() throws Throwable //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldTimeoutIfPublishContinuallyFailsWithTransientErrors() { // 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.SetClusterId(any(), anyString())).thenThrow(typeof(OperationTimeoutException)); // Causes a retry when(topologyService.LocalCoreServers()).thenReturn(bootstrappableTopology); ClusterBinder binder = ClusterBinder(new StubSimpleStorage <ClusterId>(this), topologyService); // when binder.BindToCluster(); }
public MarketDataBox <RatesCurveInputs> build(RatesCurveInputsId id, MarketDataConfig marketDataConfig, ScenarioMarketData marketData, ReferenceData refData) { CurveGroupName groupName = id.CurveGroupName; CurveName curveName = id.CurveName; RatesCurveGroupDefinition groupDefn = marketDataConfig.get(typeof(RatesCurveGroupDefinition), groupName); Optional <CurveDefinition> optionalDefinition = groupDefn.findCurveDefinition(id.CurveName); if (!optionalDefinition.Present) { throw new System.ArgumentException(Messages.format("No curve named '{}' found in group '{}'", curveName, groupName)); } CurveDefinition configuredDefn = optionalDefinition.get(); // determine market data needs MarketDataBox <LocalDate> valuationDates = marketData.ValuationDate; bool multipleValuationDates = valuationDates.ScenarioValue; // curve definition can vary for each valuation date if (multipleValuationDates) { IList <CurveDefinition> curveDefns = IntStream.range(0, valuationDates.ScenarioCount).mapToObj(valuationDates.getValue).map((LocalDate valDate) => configuredDefn.filtered(valDate, refData)).collect(toImmutableList()); //JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET: //ORIGINAL LINE: java.util.Set<com.opengamma.strata.data.MarketDataId<?>> requirements = nodeRequirements(curveDefns); ISet <MarketDataId <object> > requirements = nodeRequirements(curveDefns); //JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET: //ORIGINAL LINE: java.util.Map<com.opengamma.strata.data.MarketDataId<?>, com.opengamma.strata.data.scenario.MarketDataBox<?>> marketDataValues = requirements.stream().collect(toImmutableMap(k -> k, k -> marketData.getValue(k))); //JAVA TO C# CONVERTER TODO TASK: Most Java stream collectors are not converted by Java to C# Converter: IDictionary <MarketDataId <object>, MarketDataBox <object> > marketDataValues = requirements.collect(toImmutableMap(k => k, k => marketData.getValue(k))); return(buildMultipleCurveInputs(MarketDataBox.ofScenarioValues(curveDefns), marketDataValues, valuationDates, refData)); } // only one valuation date LocalDate valuationDate = valuationDates.getValue(0); CurveDefinition filteredDefn = configuredDefn.filtered(valuationDate, refData); //JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET: //ORIGINAL LINE: java.util.Set<com.opengamma.strata.data.MarketDataId<?>> requirements = nodeRequirements(com.google.common.collect.ImmutableList.of(filteredDefn)); ISet <MarketDataId <object> > requirements = nodeRequirements(ImmutableList.of(filteredDefn)); //JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET: //ORIGINAL LINE: java.util.Map<com.opengamma.strata.data.MarketDataId<?>, com.opengamma.strata.data.scenario.MarketDataBox<?>> marketDataValues = requirements.stream().collect(toImmutableMap(k -> k, k -> marketData.getValue(k))); //JAVA TO C# CONVERTER TODO TASK: Most Java stream collectors are not converted by Java to C# Converter: IDictionary <MarketDataId <object>, MarketDataBox <object> > marketDataValues = requirements.collect(toImmutableMap(k => k, k => marketData.getValue(k))); // Do any of the inputs contain values for multiple scenarios, or do they contain 1 value each? bool multipleInputValues = marketDataValues.Values.Any(MarketDataBox.isScenarioValue); return(multipleInputValues || multipleValuationDates?buildMultipleCurveInputs(MarketDataBox.ofSingleValue(filteredDefn), marketDataValues, valuationDates, refData) : buildSingleCurveInputs(filteredDefn, marketDataValues, valuationDate, refData)); }
//------------------------------------------------------------------------- //JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET: //ORIGINAL LINE: @Override public ScenarioArray<?> convertedTo(com.opengamma.strata.basics.currency.Currency reportingCurrency, ScenarioFxRateProvider fxRateProvider) public ScenarioArray <object> convertedTo(Currency reportingCurrency, ScenarioFxRateProvider fxRateProvider) { //JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET: //ORIGINAL LINE: if (value instanceof com.opengamma.strata.basics.currency.FxConvertible<?>) if (value is FxConvertible <object> ) { //JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET: //ORIGINAL LINE: com.opengamma.strata.basics.currency.FxConvertible<?> convertible = (com.opengamma.strata.basics.currency.FxConvertible<?>) value; FxConvertible <object> convertible = (FxConvertible <object>)value; if (fxRateProvider.ScenarioCount != scenarioCount) { throw new System.ArgumentException(Messages.format("Expected {} FX rates but received {}", scenarioCount, fxRateProvider.ScenarioCount)); } ImmutableList <object> converted = IntStream.range(0, scenarioCount).mapToObj(i => convertible.convertedTo(reportingCurrency, fxRateProvider.fxRateProvider(i))).collect(toImmutableList()); return(DefaultScenarioArray.of(converted)); } return(this); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldDetectRemovedMembers() public virtual void ShouldDetectRemovedMembers() { IDictionary <MemberId, ReadReplicaInfo> initialMembers = RandomMembers(3); IDictionary <MemberId, ReadReplicaInfo> newMembers = new Dictionary <MemberId, ReadReplicaInfo>(initialMembers); int removedMemberQuantity = 2; IntStream.range(0, removedMemberQuantity).forEach(ignored => removeArbitraryMember(newMembers)); TestTopology topology = new TestTopology(initialMembers); // when TopologyDifference diff = topology.difference(new TestTopology(newMembers)); // then assertThat(diff.Added(), hasSize(0)); assertThat(diff.Removed(), hasSize(removedMemberQuantity)); }
// constructor that sorts (artificial boolean flag) private InterpolatedNodalSurface(SurfaceMetadata metadata, DoubleArray xValues, DoubleArray yValues, DoubleArray zValues, SurfaceInterpolator interpolator, bool sort) { validateInputs(metadata, xValues, yValues, zValues, interpolator); // sort inputs IDictionary <DoublesPair, ObjDoublePair <ParameterMetadata> > sorted = new SortedDictionary <DoublesPair, ObjDoublePair <ParameterMetadata> >(); for (int i = 0; i < xValues.size(); i++) { ParameterMetadata pm = metadata.getParameterMetadata(i); sorted[DoublesPair.of(xValues.get(i), yValues.get(i))] = ObjDoublePair.of(pm, zValues.get(i)); } double[] sortedX = new double[sorted.Count]; double[] sortedY = new double[sorted.Count]; double[] sortedZ = new double[sorted.Count]; ParameterMetadata[] sortedPm = new ParameterMetadata[sorted.Count]; int pos = 0; foreach (KeyValuePair <DoublesPair, ObjDoublePair <ParameterMetadata> > entry in sorted.SetOfKeyValuePairs()) { sortedX[pos] = entry.Key.First; sortedY[pos] = entry.Key.Second; sortedZ[pos] = entry.Value.Second; sortedPm[pos] = entry.Value.First; pos++; } // assign SurfaceMetadata sortedMetadata = metadata.withParameterMetadata(Arrays.asList(sortedPm)); this.metadata = sortedMetadata; this.xValues = DoubleArray.ofUnsafe(sortedX); this.yValues = DoubleArray.ofUnsafe(sortedY); this.zValues = DoubleArray.ofUnsafe(sortedZ); IDictionary <DoublesPair, double> pairs = new Dictionary <DoublesPair, double>(); for (int i = 0; i < xValues.size(); i++) { pairs[DoublesPair.of(xValues.get(i), yValues.get(i))] = zValues.get(i); } this.interpolator = interpolator; this.boundInterpolator = interpolator.bind(this.xValues, this.yValues, this.zValues); this.parameterMetadata = IntStream.range(0, ParameterCount).mapToObj(i => sortedMetadata.getParameterMetadata(i)).collect(toImmutableList()); }