auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected GarbageFreeScheduledReporter(MetricRegistry registry, String name, MetricFilter filter, TimeUnit rateUnit, TimeUnit durationUnit, ScheduledExecutorService executor, boolean shutdownExecutorOnStop, Set<MetricAttribute> disabledMetricAttributes) { super(registry, name, filter, rateUnit, durationUnit, executor, shutdownExecutorOnStop, disabledMetricAttributes); init(registry, filter); }

Target:
protected GarbageFreeScheduledReporter(MetricRegistry registry, String name, MetricFilter filter, TimeUnit rateUnit, TimeUnit durationUnit, ScheduledExecutorService executor, boolean shutdownExecutorOnStop, Set<MetricAttribute> disabledMetricAttributes) { super(registry, name, filter, rateUnit, durationUnit, executor, shutdownExecutorOnStop, disabledMetricAttributes); this.registry = registry; this.mirror = new RegistryMirror(filter); registry.addListener(mirror); }
Source:
protected static URI buildCriteriaURI(ResourceContextImpl resourceContext, RecordTemplate criteria, String batchParameterName, URI uri) throws CloneNotSupportedException { DataList criteriaList = new DataList(1); criteriaList.add(criteria.data()); DataMap queryParams = extractQueryParamsFromResourceContext(resourceContext); return URIParamUtils.replaceQueryParam(uri, batchParameterName, criteriaList, queryParams, resourceContext.getRestliProtocolVersion()); }

Target:
static URI buildCriteriaURI(ResourceContextImpl resourceContext, RecordTemplate criteria, String batchParameterName, URI uri) { DataList criteriaList = new DataList(1); criteriaList.add(criteria.data()); return URIParamUtils.replaceQueryParam(uri, batchParameterName, criteriaList, resourceContext.getParameters(), resourceContext.getRestliProtocolVersion()); }
Source:
private ArrayList<Chunk> findChunksToMove(long startBlock, long moveSize) { ArrayList<Chunk> move = new ArrayList<>(); for (Chunk c : chunks.values()) { if (c.block > startBlock) { move.add(c); } } Collections.sort(move, new Comparator<Chunk>() { @Override public int compare(Chunk o1, Chunk o2) { int res = Long.signum(o1.block - o2.block); assert res == Long.compare(o1.block, o2.block); return res; } }); int count = 0; long size = 0; for (Chunk c : move) { long chunkSize = c.len * (long) BLOCK_SIZE; size += chunkSize; if (size > moveSize) { break; } count++; } while (move.size() > count && move.size() > 1) { move.remove(1); } return move; }

Target:
private ArrayList<Chunk> findChunksToMove(long startBlock, long moveSize) { ArrayList<Chunk> move = new ArrayList<>(); for (Chunk c : chunks.values()) { if (c.block > startBlock) { move.add(c); } } Collections.sort(move, new Comparator<Chunk>() { @Override public int compare(Chunk o1, Chunk o2) { return Long.signum(o1.block - o2.block); } }); int count = 0; long size = 0; for (Chunk c : move) { long chunkSize = c.len * (long) BLOCK_SIZE; size += chunkSize; if (size > moveSize) { break; } count++; } while (move.size() > count && move.size() > 1) { move.remove(1); } return move; }
Source:
private String extractJsonStringFromRequest(HttpServletRequest request) throws FileUploadException { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(4096); factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(1000000); List<?> fileItems = upload.parseRequest(request); Iterator<?> iterator = fileItems.iterator(); String jsonContent = ""; while (iterator.hasNext()) { FileItem fi = (FileItem) iterator.next(); if (fi.isFormField()) { String name = fi.getFieldName(); String value = fi.getString(); if (name.equalsIgnoreCase(MAIN_FORM_ITEM_NAME)) { jsonContent = value; } } fi.delete(); } return jsonContent; }

Target:
private String extractJsonStringFromRequest(HttpServletRequest request) throws FileUploadException { String jsonContent = ""; for (FileItem requestItem : new ServletRequestTransformer().getFormItems(request)) { if (requestItem.isFormField()) { String name = requestItem.getFieldName(); String value = requestItem.getString(); if (name.equalsIgnoreCase(MAIN_FORM_ITEM_NAME)) { jsonContent = value; } } requestItem.delete(); } return jsonContent; }
Source:
public Collection<T> getPropertiesList() { return subProperties; }

Target:
public Collection<T> getPropertiesList() { return Collections.unmodifiableCollection(subProperties); }
Source:
private String nodeSensorPrefix(final String threadId, final String taskId, final String processorNodeName) { return taskSensorPrefix(threadId, taskId) + SENSOR_PREFIX_DELIMITER + "node" + SENSOR_PREFIX_DELIMITER + processorNodeName; }

Target:
private String nodeSensorPrefix(final String threadId, final String taskId, final String processorNodeName) { return taskSensorPrefix(threadId, taskId) + SENSOR_PREFIX_DELIMITER + SENSOR_NODE_LABEL + SENSOR_PREFIX_DELIMITER + processorNodeName; }
Source:
public List<Route> routes() { return Collections.singletonList( new Route(DELETE, MachineLearning.BASE_PATH + "_delete_expired_data/{" + Fields.JOB_ID.getPreferredName() + "}")); }

Target:
public List<Route> routes() { return Collections.singletonList( new Route(DELETE, MachineLearning.BASE_PATH + "_delete_expired_data/{" + Job.ID.getPreferredName() + "}")); }
Source:
public <T> T injectedInstance(Class<? extends T> clazz, HttpRequest request, HttpResponse response) { Constructor<?> constructor = PickConstructor.pickSingletonConstructor(clazz); Object obj = null; if (isSingletonResource(clazz)) { SingletonResource factory = singletonResourceFactories.get(clazz); obj = factory.createResource(request, response, this); } else { if (constructor == null) { if (false) { constructor = clazz.getDeclaredConstructors()[0]; constructor.setAccessible(true); if (!Modifier.isStatic(clazz.getModifiers())) { Object[] args = {null}; try { obj = constructor.newInstance(args); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } } else { try { obj = constructor.newInstance(); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } } } else { throw new IllegalArgumentException(Messages.MESSAGES.unableToFindPublicConstructorForClass(clazz.getName())); } } else { ConstructorInjector constructorInjector = getInjectorFactory().createConstructor(constructor, this); obj = constructorInjector.construct(request, response); } } PropertyInjector propertyInjector = getInjectorFactory().createPropertyInjector(clazz, this); propertyInjector.inject(request, response, obj); return (T) obj; }

Target:
public <T> T injectedInstance(Class<? extends T> clazz, HttpRequest request, HttpResponse response) { Object obj = null; if (isSingletonResource(clazz)) { SingletonResource factory = singletonResourceFactories.get(clazz); obj = factory.createResource(request, response, this).toCompletableFuture().getNow(null); } else { Constructor<?> constructor = PickConstructor.pickSingletonConstructor(clazz); if (constructor == null) { if (false) { constructor = clazz.getDeclaredConstructors()[0]; constructor.setAccessible(true); if (!Modifier.isStatic(clazz.getModifiers())) { Object[] args = {null}; try { obj = constructor.newInstance(args); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } } else { try { obj = constructor.newInstance(); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } } } else { throw new IllegalArgumentException(Messages.MESSAGES.unableToFindPublicConstructorForClass(clazz.getName())); } } else { ConstructorInjector constructorInjector = getInjectorFactory().createConstructor(constructor, this); obj = constructorInjector.construct(request, response, false).toCompletableFuture().getNow(null); } } PropertyInjector propertyInjector = getInjectorFactory().createPropertyInjector(clazz, this); propertyInjector.inject(request, response, obj, false).toCompletableFuture().getNow(null); return (T)obj; }
Source:
public Object call(ApiCaller ac, Deserializer parms) throws PerunException { ac.stateChangingCheck(); List<Integer> memberInts = parms.readList("members", Integer.class); Group group = ac.getGroupById(parms.readInt("group")); List<Member> members = new ArrayList<>(); for (Integer memberInt : memberInts) { members.add(ac.getGroupsManager().getGroupMemberById(ac.getSession(), group, memberInt)); } ac.getGroupsManager().removeMembers(ac.getSession(), group, members); return null; }

Target:
public Group call(ApiCaller ac, Deserializer parms) throws PerunException { ac.stateChangingCheck(); if (parms.contains("group")) { if (parms.contains("parentGroup")) { return ac.getGroupsManager().createGroup(ac.getSession(), ac.getGroupById(parms.readInt("parentGroup")), parms.read("group", Group.class)); } else if (parms.contains("vo")) { Group group = parms.read("group", Group.class); if (group.getParentGroupId() == null) { return ac.getGroupsManager().createGroup(ac.getSession(), ac.getVoById(parms.readInt("vo")), group); } else { throw new RpcException(RpcException.Type.WRONG_PARAMETER, "Top-level groups can't have parentGroupId set!"); } } else { throw new RpcException(RpcException.Type.MISSING_VALUE, "vo or parentGroup"); } } else if (parms.contains("name") && parms.contains("description")) { if (parms.contains("parentGroup")) { String name = parms.readString("name"); String description = parms.readString("description"); Group group = new Group(name, description); return ac.getGroupsManager().createGroup(ac.getSession(), ac.getGroupById(parms.readInt("parentGroup")), group); } else if (parms.contains("vo")) { String name = parms.readString("name"); String description = parms.readString("description"); Group group = new Group(name, description); return ac.getGroupsManager().createGroup(ac.getSession(), ac.getVoById(parms.readInt("vo")), group); } else { throw new RpcException(RpcException.Type.MISSING_VALUE, "vo or parentGroup"); } } else { throw new RpcException(RpcException.Type.MISSING_VALUE, "group or (name and description)"); } }
Source:
public void onClick(View view) { if (adapter == null) { return; } if (adapter.getActionMode() != BrickAdapter.ActionModeEnum.NO_ACTION) { return; } if (((BrickAdapter) adapter).isDragging) { return; } showFormulaEditorToEditFormula(view); }

Target:
public void onClick(View view) { if (adapter == null) { return; } if (adapter.getActionMode() != BrickAdapter.ActionModeEnum.NO_ACTION) { return; } if (adapter instanceof BrickAdapter && ((BrickAdapter) adapter).isDragging) { return; } showFormulaEditorToEditFormula(view); }
Source:
private String getSpatialPartitioning(Rectangle extent, List<OGCGeometry> geometries, int partitionCount) { ImmutableList.Builder<Rectangle> rectangles = ImmutableList.builder(); for (OGCGeometry geometry : geometries) { Envelope envelope = new Envelope(); geometry.getEsriGeometry().queryEnvelope(envelope); rectangles.add(new Rectangle(envelope.getXMin(), envelope.getYMin(), envelope.getXMax(), envelope.getYMax())); } return KDB_TREE_CODEC.toJson(buildKDBTree((int) (Math.ceil(geometries.size() * 1.0 / partitionCount)), partitionCount, extent, rectangles.build())); }

Target:
private String getSpatialPartitioning(Rectangle extent, List<OGCGeometry> geometries, int partitionCount) { ImmutableList.Builder<Rectangle> rectangles = ImmutableList.builder(); for (OGCGeometry geometry : geometries) { Envelope envelope = new Envelope(); geometry.getEsriGeometry().queryEnvelope(envelope); rectangles.add(new Rectangle(envelope.getXMin(), envelope.getYMin(), envelope.getXMax(), envelope.getYMax())); } return KdbTreeUtils.toJson(buildKdbTree(roundToInt(geometries.size() * 1.0 / partitionCount, CEILING), extent, rectangles.build())); }
Source:
private VdsNetworkInterface getVlanDevice(final VdsNetworkInterface baseNic, final Integer vlanId) { if (vlanId == null) { return null; } return LinqUtils.firstOrNull(getNics(), new Predicate<VdsNetworkInterface>() { @Override public boolean eval(VdsNetworkInterface t) { return (baseNic.getName().equals(t.getBaseInterface()) && ObjectUtils.objectsEqual(t.getVlanId(), vlanId)); } }); }

Target:
private VdsNetworkInterface getVlanDevice(final VdsNetworkInterface baseNic, final Integer vlanId) { if (vlanId == null) { return null; } return LinqUtils.firstOrNull(getNics(), new Predicate<VdsNetworkInterface>() { @Override public boolean eval(VdsNetworkInterface t) { return (baseNic.getName().equals(t.getBaseInterface()) && Objects.equals(t.getVlanId(), vlanId)); } }); }
Source:
public static X509TrustManager createX509TrustManager(SslConfiguration config) { TrustManager trustManager = createTrustManagers(config)[0]; if (trustManager instanceof X509TrustManager) { return (X509TrustManager) trustManager; } else { throw new RuntimeException( "First TrustManager associated with SslConfiguration was not a X509TrustManager: " + config.trustStorePath()); } }

Target:
public static X509TrustManager createX509TrustManager(SslConfiguration config) { TrustManager trustManager = createTrustManagers(config)[0]; if (trustManager instanceof X509TrustManager) { return (X509TrustManager) trustManager; } else { throw new RuntimeException(String.format( "First TrustManager associated with SslConfiguration was expected to be a %s, but was a %s: %s", X509TrustManager.class.getSimpleName(), trustManager.getClass().getSimpleName(), config.trustStorePath())); } }
Source:
public List<CheckedFuture<?, IOException>> update( Project.NameKey project) throws IOException { try { return new ProjectUpdateTask(schemaFactory, project).call(); } catch (Exception e) { Throwables.propagateIfPossible(e); throw MAPPER.apply(e); } }

Target:
public void update(Project.NameKey project) throws IOException { try { for (CheckedFuture<?, IOException> f : new ProjectUpdateTask( schemaFactory, project, false).call()) { f.checkedGet(); } } catch (Exception e) { Throwables.propagateIfPossible(e); throw MAPPER.apply(e); } }
Source:
protected List<StorageServerConnections> filterConnectionsUsedByOthers( List<StorageServerConnections> connections, String vgId, Guid poolId) { List<StorageServerConnections> connsToClose = new ArrayList<>(); for (StorageServerConnections conn : connections) { List<LUNs> luns = DbFacade.getInstance().getLunDao().getAllForStorageServerConnection(conn.getid()); if (poolId != null && !activeSDsExist(luns, vgId, poolId) && !activePluggedDirectLunsExist(luns)) { connsToClose.add(conn); } } return connsToClose; }

Target:
protected List<StorageServerConnections> filterConnectionsUsedByOthers( List<StorageServerConnections> connections, String vgId, Guid poolId) { List<StorageServerConnections> connsToClose = new ArrayList<>(); for (StorageServerConnections conn : connections) { List<LUNs> luns = DbFacade.getInstance().getLunDao().getAllForStorageServerConnection(conn.getid()); if (!activeSDsExist(luns, vgId, poolId) && !activePluggedDirectLunsExist(poolId, luns)) { connsToClose.add(conn); } } return connsToClose; }
Source:
public C map(int i, ResultSet rs, StatementContext ctx) throws SQLException { C obj; logger.debug("map {}", clazz); try { Constructor<C> constructor = clazz.getDeclaredConstructor(); constructor.setAccessible(true); obj = constructor.newInstance(); for (int colIndex = rs.getMetaData().getColumnCount(); colIndex >= 1; colIndex--) { String columnLabel = rs.getMetaData().getColumnLabel(colIndex); JpaMember member = jpaClass.lookupMember(columnLabel); if (member != null) { Class<?> memberType = member.getType(); ResultColumnMapper<?> columnMapper = ctx.columnMapperFor(memberType); Object value = columnMapper.mapColumn(rs, columnLabel, ctx); member.write(obj, value); } } } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } return obj; }

Target:
public C map(int i, ResultSet rs, StatementContext ctx) throws SQLException { logger.debug("map {}", clazz); try { return tryMap(rs, ctx); } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) { throw new EntityMemberAccessException(String.format("Unable to map %s entity", clazz), e); } }
Source:
public static EncodeFormat checkedValueOf(String name) { try { return Enum.valueOf(EncodeFormat.class, name); } catch (Exception ex) { VoltDB.crashLocalVoltDB("Illegal encoding format " + name, true, ex); } return null; }

Target:
public static EncodeFormat checkedValueOf(String name) { try { return valueOf(EncodeFormat.class, name); } catch (Exception ex) { VoltDB.crashLocalVoltDB("Illegal encoding format " + name, true, ex); } return null; }
Source:
private boolean applyViolation(final H canvasHandler, final RuleViolation violation) { if (hasViolations(violation)) { final Canvas canvas = canvasHandler.getCanvas(); final Shape shape = getShape(canvasHandler, violation.getUUID()); if (null != shape) { shape.applyState(ShapeState.INVALID); } return true; } return false; }

Target:
private boolean applyViolation(final H canvasHandler, final RuleViolation violation) { if (hasViolations(violation)) { final Shape shape = getShape(canvasHandler, violation.getUUID()); if (null != shape) { shape.applyState(ShapeState.INVALID); } return true; } return false; }
Source:
public static int getFirstBinInLevel(final int levelNumber) { if (levelNumber >= getNumIndexLevels()) { throw new SAMException("Level number is too big (" + levelNumber + ")."); } return GenomicIndexUtil.LEVEL_STARTS[levelNumber]; }

Target:
public static int getFirstBinInLevel(final int levelNumber) { assertLevelIsValid(levelNumber); return GenomicIndexUtil.LEVEL_STARTS[levelNumber]; }
Source:
public void run(Session session, String keyspace, boolean resetDB, int replicationFactor, boolean updateVersion) { CassalogBuilder builder = new CassalogBuilder(); Cassalog cassalog = builder.withKeyspace(keyspace).withSession(session).build(); Map<String, ?> vars = ImmutableMap.of( "keyspace", keyspace, "reset", resetDB, "session", session, "replicationFactor", replicationFactor, "logger", logger ); List<String> tags = asList("0.15.x", "0.18.x", "0.19.x", "0.20.x", "0.21.x", "0.23.x", "0.26.x", "0.27.x"); URI script = getScript(); cassalog.execute(script, tags, vars); if (updateVersion) { try { updateVersion(session, keyspace, 0, 0); } catch (Exception e) { throw new VersionUpdateException("Failed to update version in system configuration", e); } } }

Target:
public void run(Session session, String keyspace, boolean resetDB, int replicationFactor, boolean updateVersion) { CassalogBuilder builder = new CassalogBuilder(); Cassalog cassalog = builder.withKeyspace(keyspace).withSession(session).build(); Map<String, ?> vars = ImmutableMap.of( "keyspace", keyspace, "reset", resetDB, "session", session, "replicationFactor", replicationFactor, "logger", logger ); List<String> tags = asList("0.15.x", "0.18.x", "0.19.x", "0.20.x", "0.21.x", "0.23.x", "0.26.x", "0.27.x"); URI script = getScript(); cassalog.execute(script, tags, vars); if (updateVersion) { updateVersion(session, keyspace, 0, 0); } }
Source:
public void serialize( final ActorRef value, final JsonGenerator gen, final SerializerProvider serializers) throws IOException { gen.writeString(value.path().toStringWithAddress(_system.provider().getDefaultAddress())); }

Target:
public void serialize( final ActorRef value, final JsonGenerator gen, final SerializerProvider serializers) throws IOException { gen.writeString(Serialization.serializedActorPath(value)); }
Source:
public SCIMSearchResult<User> searchUser(String query, Integer limit, Long offset, String orderBy, Boolean ascending, String attributes) { QueryBuilder qb = new QueryBuilder(); qb.filter(query); if (attributes != null) { qb.attributes(attributes); } if (limit != null) { qb.count(limit); } if (offset != null) { qb.startIndex(offset); } if (orderBy != null && ascending != null) { if (ascending) { qb.ascending(orderBy); } else { qb.descending(orderBy); } } return connector.searchUsers(qb.build(), sessionData.getAccesstoken()); }

Target:
public SCIMSearchResult<User> searchUser(String query, Integer limit, Long offset, String orderBy, Boolean ascending, String attributes) { QueryBuilder qb = new QueryBuilder(); qb.filter(query); qb.attributes(attributes); qb.count(limit); qb.startIndex(offset); if (ascending) { qb.ascending(orderBy); } else { qb.descending(orderBy); } return connector.searchUsers(qb.build(), sessionData.getAccesstoken()); }
Source:
protected int processLineContent(String line, int offset) { String text = line.substring(offset); String content; Matcher itemStartMatcher = itemStartPattern.matcher(text); if (itemStartMatcher.matches()) { if (blockLineCount == 0) { BlockType blockType = itemStartMatcher.group(1) != null ? BlockType.BULLETED_LIST : BlockType.NUMERIC_LIST; builder.beginBlock(blockType, new Attributes()); builder.characters("\n"); } else { builder.endBlock(); builder.characters("\n"); } builder.beginBlock(BlockType.LIST_ITEM, new Attributes()); content = itemStartMatcher.group(3); } else if (!text.trim().isEmpty()) { builder.characters("\n"); content = text; } else { setClosed(true); return offset; } int textStart = 0; markupLanguage.emitMarkupLine(getParser(), state, content, textStart); blockLineCount++; return -1; }

Target:
protected int processLineContent(String line, int offset) { String text = line.substring(offset); String content; Matcher itemStartMatcher = itemStartPattern.matcher(text); if (itemStartMatcher.matches()) { if (blockLineCount == 0) { BlockType blockType = itemStartMatcher.group(1) != null ? BlockType.BULLETED_LIST : BlockType.NUMERIC_LIST; builder.beginBlock(blockType, new Attributes()); } else { builder.endBlock(); } builder.beginBlock(BlockType.LIST_ITEM, new Attributes()); content = itemStartMatcher.group(3); } else if (!text.trim().isEmpty()) { builder.characters("\n"); content = text; } else { setClosed(true); return offset; } int textStart = 0; markupLanguage.emitMarkupLine(getParser(), state, content, textStart); blockLineCount++; return -1; }
Source:
public void compile() throws DbException { Preconditions.checkArgument(needsCompiling(), "This expression does not need to be compiled."); String javaExpression = getJavaExpression(); IScriptEvaluator se; try { se = CompilerFactoryFactory.getDefaultCompilerFactory().newExpressionEvaluator(); } catch (Exception e) { LOGGER.error("Could not create expression evaluator", e); throw new DbException("Could not create expression evaluator", e); } try { evaluator = (EvalInterface) se.createFastEvaluator(javaExpression, EvalInterface.class, new String[] { Expression.TB, Expression.ROW, Expression.RESULT, Expression.STATE }); } catch (CompileException e) { LOGGER.error("Error when compiling expression: {}", javaExpression); throw new DbException("Error when compiling expression: " + javaExpression, e); } }

Target:
public void compile() throws DbException { Preconditions.checkArgument(needsCompiling(), "This expression does not need to be compiled."); String javaExpression = getJavaExpression(); IScriptEvaluator se; try { se = CompilerFactoryFactory.getDefaultCompilerFactory().newExpressionEvaluator(); } catch (Exception e) { LOGGER.error("Could not create expression evaluator", e); throw new DbException("Could not create expression evaluator", e); } try { evaluator = (EvalInterface) se.createFastEvaluator(javaExpression, EvalInterface.class, new String[] { Expression.TB, Expression.ROW, Expression.RESULT, Expression.STATE }); } catch (CompileException e) { LOGGER.error("Error when compiling expression {}: {}", javaExpression, e); throw new DbException("Error when compiling expression: " + javaExpression, e); } }
Source:
public MissingColumnError(String file, String field) { super(file, 0, field); }

Target:
public MissingColumnError(String file, String field) { super(file, 1, field); }
Source:
public void onTestStart(ITestResult iTestResult) { Object[] parameters = iTestResult.getParameters(); ITestNGMethod method = iTestResult.getMethod(); ConstructorOrMethod constructorOrMethod = method.getConstructorOrMethod(); if (constructorOrMethod != null) { Method nativeMethod = constructorOrMethod.getMethod(); boolean atLeastJava8 = isAtLeastJava8(); String[] parameterNames = null; if (atLeastJava8) { parameterNames = getParameterNames(nativeMethod); } for (int i = 0; i < parameters.length; i++) { String name = "arg" + i; if (parameterNames != null) { name = parameterNames[i]; } String value = parameters[i].toString(); getLifecycle().fire(new AddParameterEvent(name, value, ParameterKind.ARGUMENT)); } } String suitePrefix = getCurrentSuitePrefix(iTestResult); String testName = getName(iTestResult); startedTestNames.add(testName); testName = testName.replace(suitePrefix, ""); Description description = new Description().withValue(method.getDescription()); TestCaseStartedEvent event = new TestCaseStartedEvent(getSuiteUid(iTestResult.getTestContext()), testName); if (description.getValue() != null) { event.setDescription(description); } AnnotationManager am = new AnnotationManager(getMethodAnnotations(iTestResult)); am.setDefaults(getClassAnnotations(iTestResult)); am.update(event); getLifecycle().fire(event); }

Target:
public void onTestStart(ITestResult iTestResult) { ITestNGMethod method = iTestResult.getMethod(); String suitePrefix = getCurrentSuitePrefix(iTestResult); String testName = getName(iTestResult); startedTestNames.add(testName); testName = testName.replace(suitePrefix, ""); Description description = new Description().withValue(method.getDescription()); TestCaseStartedEvent event = new TestCaseStartedEvent(getSuiteUid(iTestResult.getTestContext()), testName); if (description.getValue() != null) { event.setDescription(description); } AnnotationManager am = new AnnotationManager(getMethodAnnotations(iTestResult)); am.setDefaults(getClassAnnotations(iTestResult)); am.update(event); getLifecycle().fire(event); fireAddParameterEvents(iTestResult); }
Source:
private CqlSessionBuilder buildCluster(int port) { String host = resolveHost(); return CqlSession.builder().addContactPoint(InetSocketAddress.createUnresolved(host, port)) .withLocalDatacenter("datacenter1").withConfigLoader( DriverConfigLoader.programmaticBuilder().withString(DefaultDriverOption.PROTOCOL_VERSION, "V5").build()); }

Target:
private CqlSessionBuilder buildCluster(int port) { String host = resolveHost(); CqlSessionBuilder builder = CqlSession.builder().addContactPoint(InetSocketAddress.createUnresolved(host, port)) .withLocalDatacenter("datacenter1"); CqlSession cqlSession = builder.build(); if (cassandraVersionGreaterThanOrEqualTo4(cqlSession)) { return builder.withConfigLoader( DriverConfigLoader.programmaticBuilder().withString(DefaultDriverOption.PROTOCOL_VERSION, "V5").build()); } else { return builder; } }
Source:
public Pair<Vertex, Edge> nextMinimum() { Edge nextMinimum = new Edge(Integer.MAX_VALUE); Vertex nextVertex = this; Iterator it = edges.entrySet() .iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); if (!((Vertex) pair.getKey()).isVisited()) { if (!((Edge) pair.getValue()).isIncluded()) { if (((Edge) pair.getValue()).getWeight() < nextMinimum.getWeight()) { nextMinimum = (Edge) pair.getValue(); nextVertex = (Vertex) pair.getKey(); } } } } return new Pair<>(nextVertex, nextMinimum); }

Target:
public Pair<Vertex, Edge> nextMinimum(){ Edge nextMinimum = new Edge(Integer.MAX_VALUE); Vertex nextVertex = this; Iterator<Map.Entry<Vertex,Edge>> it = edges.entrySet().iterator(); while (it.hasNext()) { Map.Entry<Vertex,Edge> pair = it.next(); if (!pair.getKey().isVisited()){ if (!pair.getValue().isIncluded()) { if (pair.getValue().getWeight() < nextMinimum.getWeight()) { nextMinimum = pair.getValue(); nextVertex = pair.getKey(); } } } } return new Pair<>(nextVertex, nextMinimum); }
Source:
public void testAggregates() throws Exception { AggregateDefinition aggDef = new AggregateDescriptor(); aggDef.setId("cardinal"); aggDef.setType(AGG_CARDINALITY); aggDef.setDocumentField("dc:title"); AggregateDefinition avggDef = new AggregateDescriptor(); avggDef.setId("average"); avggDef.setType(AGG_AVG); avggDef.setDocumentField("dc:created"); SingleValueMetricAggregate cardinality = (SingleValueMetricAggregate) AggregateFactory.create(aggDef, null); SingleValueMetricAggregate average = (SingleValueMetricAggregate) AggregateFactory.create(avggDef, null); NxQueryBuilder qb = new NxQueryBuilder(session).nxql("select * From Document") .limit(0) .addAggregate(cardinality) .addAggregate(average) .onlyElasticsearchResponse(); EsResult esRes = ess.queryAndAggregate(qb); Assert.assertNotNull(cardinality.getValue()); }

Target:
public void testAggregates() throws Exception { AggregateDefinition aggDef = new AggregateDescriptor(); aggDef.setId("cardinal"); aggDef.setType(AGG_CARDINALITY); aggDef.setDocumentField("dc:title"); AggregateDefinition avggDef = new AggregateDescriptor(); avggDef.setId("average"); avggDef.setType(AGG_AVG); avggDef.setDocumentField("dc:created"); SingleValueMetricAggregate cardinality = (SingleValueMetricAggregate) AggregateFactory.create(aggDef, null); SingleValueMetricAggregate average = (SingleValueMetricAggregate) AggregateFactory.create(avggDef, null); NxQueryBuilder qb = new NxQueryBuilder(session).nxql("SELECT * FROM Document") .limit(0) .addAggregate(cardinality) .addAggregate(average) .onlyElasticsearchResponse(); EsResult esRes = ess.queryAndAggregate(qb); Assert.assertNotNull(cardinality.getValue()); }
Source:
public static void deleteFile(Connection connection, int fid) throws ServiceException{ try { PreparedStatement deleteStatement = connection.prepareStatement(DELETE_FILE_QUERY); deleteStatement.setInt(1, fid); if (deleteStatement.executeUpdate() != -1) { deleteStatement.close(); throw new ServiceException(ServiceStatus.APP_FILE_NOT_EXIST); } } catch (SQLException ex){ throw new ServiceException(ServiceStatus.DATABASE_ERROR, ex); } }

Target:
public static void deleteFile(Connection connection, int fid) throws ServiceException { try { PreparedStatement deleteStatement = connection.prepareStatement(DELETE_FILE_QUERY); deleteStatement.setInt(1, fid); if (deleteStatement.executeUpdate() != 1) { deleteStatement.close(); throw new ServiceException(ServiceStatus.APP_FILE_NOT_EXIST); } deleteStatement.close(); } catch (SQLException ex){ throw new ServiceException(ServiceStatus.DATABASE_ERROR, ex); } }
Source:
public HiveSplitManager( HiveClientConfig hiveClientConfig, Function<HiveTransactionHandle, SemiTransactionalHiveMetastore> metastoreProvider, NamenodeStats namenodeStats, HdfsEnvironment hdfsEnvironment, DirectoryLister directoryLister, @ForHiveClient ExecutorService executorService, CoercionPolicy coercionPolicy) { this( metastoreProvider, namenodeStats, hdfsEnvironment, directoryLister, new BoundedExecutor(executorService, hiveClientConfig.getMaxSplitIteratorThreads()), coercionPolicy, new CounterStat(), hiveClientConfig.getMaxOutstandingSplits(), hiveClientConfig.getMaxOutstandingSplitsSize(), hiveClientConfig.getMinPartitionBatchSize(), hiveClientConfig.getMaxPartitionBatchSize(), hiveClientConfig.getMaxInitialSplits(), hiveClientConfig.getSplitLoaderConcurrency(), hiveClientConfig.getRecursiveDirWalkerEnabled(), new S3SelectPushdown(hiveClientConfig)); }

Target:
public HiveSplitManager( HiveClientConfig hiveClientConfig, Function<HiveTransactionHandle, SemiTransactionalHiveMetastore> metastoreProvider, NamenodeStats namenodeStats, HdfsEnvironment hdfsEnvironment, DirectoryLister directoryLister, @ForHiveClient ExecutorService executorService, CoercionPolicy coercionPolicy) { this( metastoreProvider, namenodeStats, hdfsEnvironment, directoryLister, new BoundedExecutor(executorService, hiveClientConfig.getMaxSplitIteratorThreads()), coercionPolicy, new CounterStat(), hiveClientConfig.getMaxOutstandingSplits(), hiveClientConfig.getMaxOutstandingSplitsSize(), hiveClientConfig.getMinPartitionBatchSize(), hiveClientConfig.getMaxPartitionBatchSize(), hiveClientConfig.getMaxInitialSplits(), hiveClientConfig.getSplitLoaderConcurrency(), hiveClientConfig.getRecursiveDirWalkerEnabled()); }
Source:
public List<NetworkMetaData> getNetworksMetaData(long accountId) { MultiRecordMapper<NetworkMetaData> mapper = new MultiRecordMapper<NetworkMetaData>() { @Override protected NetworkMetaData map(List<Object> input) { Network ntwk = (Network) input.get(0); Map<String, Object> meta = DataAccessor.fields(ntwk).withKey(ServiceConstants.FIELD_METADATA) .withDefault(Collections.EMPTY_MAP).as(Map.class); NetworkMetaData data = new NetworkMetaData(ntwk.getName(), ntwk.getUuid(), meta); return data; } }; NetworkTable ntwk = mapper.add(NETWORK); return create() .select(mapper.fields()) .from(ntwk) .where(ntwk.REMOVED.isNull()) .and(ntwk.ACCOUNT_ID.eq(accountId)) .fetch().map(mapper); }

Target:
public List<NetworkMetaData> getNetworksMetaData(long accountId) { MultiRecordMapper<NetworkMetaData> mapper = new MultiRecordMapper<NetworkMetaData>() { @Override protected NetworkMetaData map(List<Object> input) { Network ntwk = (Network) input.get(0); Map<String, Object> meta = DataAccessor.fieldMap(ntwk, ServiceConstants.FIELD_METADATA); NetworkMetaData data = new NetworkMetaData(ntwk.getName(), ntwk.getUuid(), meta); return data; } }; NetworkTable ntwk = mapper.add(NETWORK, NETWORK.NAME, NETWORK.UUID, NETWORK.DATA); return create() .select(mapper.fields()) .from(ntwk) .where(ntwk.REMOVED.isNull()) .and(ntwk.ACCOUNT_ID.eq(accountId)) .fetch().map(mapper); }
Source:
public static CompletedCheckpointStore createCompletedCheckpointStore( Configuration configuration, FlinkKubeClient kubeClient, Executor executor, String configMapName, String lockIdentity, int maxNumberOfCheckpointsToRetain) throws Exception { final RetrievableStateStorageHelper<CompletedCheckpoint> stateStorage = new FileSystemStateStorageHelper<>(HighAvailabilityServicesUtils .getClusterHighAvailableStoragePath(configuration), COMPLETED_CHECKPOINT_FILE_SUFFIX); final KubernetesStateHandleStore<CompletedCheckpoint> stateHandleStore = new KubernetesStateHandleStore<>( kubeClient, configMapName, stateStorage, k -> k.startsWith(CHECKPOINT_ID_KEY_PREFIX), lockIdentity); return new DefaultCompletedCheckpointStore( maxNumberOfCheckpointsToRetain, stateHandleStore, new KubernetesCheckpointStoreUtil(), executor); }

Target:
public static CompletedCheckpointStore createCompletedCheckpointStore( Configuration configuration, FlinkKubeClient kubeClient, Executor executor, String configMapName, String lockIdentity, int maxNumberOfCheckpointsToRetain) throws Exception { final RetrievableStateStorageHelper<CompletedCheckpoint> stateStorage = new FileSystemStateStorageHelper<>(HighAvailabilityServicesUtils .getClusterHighAvailableStoragePath(configuration), COMPLETED_CHECKPOINT_FILE_SUFFIX); final KubernetesStateHandleStore<CompletedCheckpoint> stateHandleStore = new KubernetesStateHandleStore<>( kubeClient, configMapName, stateStorage, k -> k.startsWith(CHECKPOINT_ID_KEY_PREFIX), lockIdentity); return new DefaultCompletedCheckpointStore<>( maxNumberOfCheckpointsToRetain, stateHandleStore, KubernetesCheckpointStoreUtil.INSTANCE, executor); }
Source:
public Object execute(ExecutionEvent aEvent) throws ExecutionException { GerritTask item = null; GerritTableView reviewTableView = GerritTableView .getActiveView(); TableViewer viewer = reviewTableView.getTableViewer(); ISelection tableSelection = viewer.getSelection(); if (tableSelection.isEmpty()) { GerritUi.Ftracer.traceInfo("Selected table selection is EMPTY " ); } else { if (tableSelection instanceof IStructuredSelection ) { Object obj = ((IStructuredSelection) tableSelection).getFirstElement(); if (obj instanceof GerritTask) { item = (GerritTask) obj; item.toggleStarred(GerritTask.IS_STARRED, Boolean.toString(!Boolean.valueOf(item.getAttribute(GerritTask.IS_STARRED)))); try { reviewTableView.setStarred(item.getTaskId(), item.getStarred()); } catch (CoreException e) { UIUtils.showErrorDialog(e.getMessage(), e.getStatus().getException().getMessage()); item.toggleStarred(GerritTask.IS_STARRED, Boolean.toString(!Boolean.valueOf(item.getAttribute(GerritTask.IS_STARRED)))); } viewer.update(item, null); } } } return item; }

Target:
public Object execute(ExecutionEvent aEvent) throws ExecutionException { GerritTask item = null; GerritTableView reviewTableView = GerritTableView .getActiveView(); TableViewer viewer = reviewTableView.getTableViewer(); ISelection tableSelection = viewer.getSelection(); if (tableSelection.isEmpty()) { GerritUi.Ftracer.traceInfo("Selected table selection is EMPTY " ); } else { if (tableSelection instanceof IStructuredSelection ) { Object obj = ((IStructuredSelection) tableSelection).getFirstElement(); if (obj instanceof GerritTask) { item = (GerritTask) obj; item.toggleStarred(GerritTask.IS_STARRED, Boolean.toString(!Boolean.valueOf(item.getAttribute(GerritTask.IS_STARRED)))); try { reviewTableView.setStarred(item.getTaskId(), item.getStarred(), new NullProgressMonitor() {}); } catch (CoreException e) { UIUtils.showErrorDialog(e.getMessage(), e.getStatus().getException().getMessage()); item.toggleStarred(GerritTask.IS_STARRED, Boolean.toString(!Boolean.valueOf(item.getAttribute(GerritTask.IS_STARRED)))); } viewer.update(item, null); } } } return item; }
Source:
public Integer saveLot(final LotGeneratorInputDto lotGeneratorInputDto) { final WorkbenchUser loggedInUser = this.securityService.getCurrentlyLoggedInUser(); lotGeneratorInputDto.setUserId(loggedInUser.getUserid()); lotInputValidator.validate(lotGeneratorInputDto); final String nextStockIDPrefix; if (lotGeneratorInputDto.getGenerateStock()) { if (lotGeneratorInputDto.getStockPrefix() == null || lotGeneratorInputDto.getStockPrefix().isEmpty()) { nextStockIDPrefix = this.stockService.calculateNextStockIDPrefix(DEFAULT_STOCKID_PREFIX, "-"); } else { nextStockIDPrefix = this.stockService.calculateNextStockIDPrefix(lotGeneratorInputDto.getStockPrefix(), "-"); } lotGeneratorInputDto.setStockId(nextStockIDPrefix + "1"); } return lotService.saveLot(lotGeneratorInputDto); }

Target:
public Integer saveLot( final LotGeneratorInputDto lotGeneratorInputDto) { final WorkbenchUser loggedInUser = this.securityService.getCurrentlyLoggedInUser(); lotGeneratorInputDto.setUserId(loggedInUser.getUserid()); lotInputValidator.validate(lotGeneratorInputDto); if (lotGeneratorInputDto.getGenerateStock()) { final String nextStockIDPrefix; if (lotGeneratorInputDto.getStockPrefix() == null || lotGeneratorInputDto.getStockPrefix().isEmpty()) { nextStockIDPrefix = this.stockService.calculateNextStockIDPrefix(DEFAULT_STOCKID_PREFIX, "-"); } else { nextStockIDPrefix = this.stockService.calculateNextStockIDPrefix(lotGeneratorInputDto.getStockPrefix(), "-"); } lotGeneratorInputDto.setStockId(nextStockIDPrefix + "1"); } return lotService.saveLot(lotGeneratorInputDto, this.contextUtil.getProjectInContext().getCropType()); }
Source:
private <R> CompletionStage<PublisherResult<R>> handleSpecificKeys(boolean parallelPublisher, Set<K> keysToInclude, Set<K> keysToExclude, DeliveryGuarantee deliveryGuarantee, Function<? super Publisher<K>, ? extends CompletionStage<R>> collator, Function<? super Publisher<R>, ? extends CompletionStage<R>> finalizer) { AdvancedCache<K, V> cache = deliveryGuarantee == DeliveryGuarantee.AT_MOST_ONCE ? this.cache : remoteCache; return handleSpecificObjects(parallelPublisher, keysToInclude, keysToExclude, keyFlowable -> keyFlowable.concatMapMaybe(key -> RxJavaInterop.completionStageToMaybe(cache.getAsync(key) .thenApply(value -> value == null ? null : key)) ) , collator, finalizer); }

Target:
private <R> CompletionStage<PublisherResult<R>> handleSpecificKeys(boolean parallelPublisher, Set<K> keysToInclude, Set<K> keysToExclude, DeliveryGuarantee deliveryGuarantee, Function<? super Publisher<K>, ? extends CompletionStage<R>> collator, Function<? super Publisher<R>, ? extends CompletionStage<R>> finalizer) { AdvancedCache<K, V> cache = deliveryGuarantee == DeliveryGuarantee.AT_MOST_ONCE ? this.cache : remoteCache; return handleSpecificObjects(parallelPublisher, keysToInclude, keysToExclude, keyFlowable -> keyFlowable.concatMapMaybe(key -> RxJavaInterop.completionStageToMaybe(cache.containsKeyAsync(key) .thenApply(contains -> contains ? key : null)) ) , collator, finalizer); }
Source:
public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(BUNDLE_LAST_SEARCH, mLastSearch); mSavedInstanceState = outState; saveState(outState); }

Target:
public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); saveState(outState); }
Source:
public static boolean evaluateNoexceptSpecifier(ICPPEvaluation noexceptSpecifier) { if (noexceptSpecifier != null) { IntegralValue v = (IntegralValue) noexceptSpecifier.getValue(); if (v.numberValue() != null) return v.numberValue().longValue() == 1; } return false; }

Target:
public static boolean evaluateNoexceptSpecifier(ICPPEvaluation noexceptSpecifier) { if (noexceptSpecifier != null && noexceptSpecifier.getValue() instanceof IntegralValue) { IntegralValue v = (IntegralValue) noexceptSpecifier.getValue(); if (v.numberValue() != null) return v.numberValue().longValue() == 1; } return false; }
Source:
public void testMergeOnRepo() throws Exception { Activator.getDefault().getRepositoryUtil().addConfiguredRepository( clonedRepositoryFile); SWTBotTree tree = getOrOpenView().bot().tree(); myRepoViewUtil.getRootItem(tree, clonedRepositoryFile).select(); ContextMenuHelper.clickContextMenu(tree, myUtil .getPluginLocalizedValue("RepoViewMerge.label")); String title = NLS.bind( UIText.MergeTargetSelectionDialog_TitleMergeWithBranch, new RepositoryBuilder().setGitDir(clonedRepositoryFile).build() .getBranch()); SWTBotShell mergeDialog = bot.shell(title); mergeDialog.close(); }

Target:
public void testMergeOnRepo() throws Exception { Activator.getDefault().getRepositoryUtil().addConfiguredRepository( clonedRepositoryFile); SWTBotTree tree = getOrOpenView().bot().tree(); myRepoViewUtil.getRootItem(tree, clonedRepositoryFile).select(); ContextMenuHelper.clickContextMenu(tree, myUtil .getPluginLocalizedValue("RepoViewMerge.label")); String title = NLS.bind( UIText.MergeTargetSelectionDialog_TitleMergeWithBranch, FileRepositoryBuilder.create(clonedRepositoryFile).getBranch()); SWTBotShell mergeDialog = bot.shell(title); mergeDialog.close(); }
Source:
void rollLog(LastLogMark lastMark) throws NoWritableLedgerDirException { byte buff[] = new byte[16]; ByteBuffer bb = ByteBuffer.wrap(buff); lastMark.getCurMark().writeLogMark(bb); LOG.info("RollLog to persist last marked log : {}", lastMark.getCurMark()); List<File> writableLedgerDirs = ledgerDirsManager .getWritableLedgerDirsForNewLog(); for (File dir : writableLedgerDirs) { File file = new File(dir, lastMarkFileName); FileOutputStream fos = null; try { fos = new FileOutputStream(file); fos.write(buff); fos.getChannel().force(true); fos.close(); fos = null; } catch (IOException e) { LOG.error("Problems writing to " + file, e); } finally { IOUtils.close(LOG, fos); } } }

Target:
void rollLog(LastLogMark lastMark) throws NoWritableLedgerDirException { byte buff[] = new byte[16]; ByteBuffer bb = ByteBuffer.wrap(buff); lastMark.getCurMark().writeLogMark(bb); if (LOG.isDebugEnabled()) { LOG.debug("RollLog to persist last marked log : {}", lastMark.getCurMark()); } List<File> writableLedgerDirs = ledgerDirsManager .getWritableLedgerDirsForNewLog(); for (File dir : writableLedgerDirs) { File file = new File(dir, lastMarkFileName); FileOutputStream fos = null; try { fos = new FileOutputStream(file); fos.write(buff); fos.getChannel().force(true); fos.close(); fos = null; } catch (IOException e) { LOG.error("Problems writing to " + file, e); } finally { IOUtils.close(LOG, fos); } } }
Source:
public void testWithInvalidAuthorizationCode(String host, String opHost, String redirectUrl, String userId, String userSecret) throws Exception { final ClientInterface client = Tester.newClient(host); final RegisterSiteResponse site = RegisterSiteTest.registerSite(client, opHost, redirectUrl); final String state = CoreUtils.secureRandomString(); final String authorizationStr = Tester.getAuthorization(); final String code = codeRequest(client, site.getOxdId(), userId, userSecret, state, CoreUtils.secureRandomString()); final String invalidCode = code.concat("blah"); final GetTokensByCodeParams params = new GetTokensByCodeParams(); params.setOxdId(site.getOxdId()); params.setCode(invalidCode); params.setState(state); try { client.getTokenByCode(authorizationStr, params); } catch (Exception e) { assertErrorResponse(400, INVALID_AUTHORIZATION_CODE_BAD_CODE, e); } }

Target:
public void testWithInvalidAuthorizationCode(String host, String opHost, String redirectUrl, String userId, String userSecret) throws Exception { final ClientInterface client = Tester.newClient(host); final RegisterSiteResponse site = RegisterSiteTest.registerSite(client, opHost, redirectUrl); final String state = CoreUtils.secureRandomString(); final String authorizationStr = Tester.getAuthorization(); final String code = codeRequest(client, site.getOxdId(), userId, userSecret, state, CoreUtils.secureRandomString()); final String invalidCode = code.concat("blah"); final GetTokensByCodeParams params = new GetTokensByCodeParams(); params.setOxdId(site.getOxdId()); params.setCode(invalidCode); params.setState(state); try { client.getTokenByCode(authorizationStr, params); fail("Test should throw an exception"); } catch (Exception e) { assertErrorResponse(400, INVALID_AUTHORIZATION_CODE_BAD_CODE, e); } }
Source:
public DiscreteVolatilityFunction from(final DoublesPair[] expiryStrikePoints) { ArgumentChecker.notNull(expiryStrikePoints, "strikeExpiryPoints"); final int n = expiryStrikePoints.length; return new DiscreteVolatilityFunction() { @Override public DoubleMatrix1D evaluate(final DoubleMatrix1D x) { final double[] res = new double[n]; final VolatilitySurface vs = _volatilitySurfacePro.getVolSurface(x); for (int i = 0; i < n; i++) { res[i] = vs.getVolatility(expiryStrikePoints[i]); } return new DoubleMatrix1D(res); } @Override public DoubleMatrix2D calculateJacobian(final DoubleMatrix1D x) { final Surface<Double, Double, DoubleMatrix1D> volSurfaceAdjoint = _volatilitySurfacePro.getParameterSensitivitySurface(x); final DoubleMatrix2D res = new DoubleMatrix2D(n, _volatilitySurfacePro.getNumModelParameters()); for (int i = 0; i < n; i++) { res.getData()[i] = volSurfaceAdjoint.getZValue(expiryStrikePoints[i]).getData(); } return res; } @Override public int getLengthOfDomain() { return _volatilitySurfacePro.getNumModelParameters(); } @Override public int getLengthOfRange() { return n; } }; }

Target:
public DiscreteVolatilityFunction from(final DoublesPair[] expiryStrikePoints) { ArgumentChecker.notNull(expiryStrikePoints, "strikeExpiryPoints"); final int n = expiryStrikePoints.length; return new DiscreteVolatilityFunction() { @Override public DoubleMatrix1D evaluate(final DoubleMatrix1D x) { ArgumentChecker.notNull(x, "x"); DoubleMatrix1D res = new DoubleMatrix1D(n); double[] data = res.getData(); final VolatilitySurface vs = _volatilitySurfacePro.getVolSurface(x); for (int i = 0; i < n; i++) { data[i] = vs.getVolatility(expiryStrikePoints[i]); } return res; } @Override public DoubleMatrix2D calculateJacobian(final DoubleMatrix1D x) { ArgumentChecker.notNull(x, "x"); final Surface<Double, Double, DoubleMatrix1D> volSurfaceAdjoint = _volatilitySurfacePro.getParameterSensitivitySurface(x); final DoubleMatrix2D res = new DoubleMatrix2D(n, _volatilitySurfacePro.getNumModelParameters()); for (int i = 0; i < n; i++) { res.getData()[i] = volSurfaceAdjoint.getZValue(expiryStrikePoints[i]).getData(); } return res; } @Override public int getLengthOfDomain() { return _volatilitySurfacePro.getNumModelParameters(); } @Override public int getLengthOfRange() { return n; } }; }