auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected ViewModel doGet(HttpServletRequest request, HttpServletResponse response) throws Exception { String sptoken = Strings.clean(request.getParameter("sptoken")); if (isJsonPreferred(request, response)) { Map<String, Object> model = new HashMap<String, Object>(1); if (sptoken == null) { model.put("status", "400"); model.put("message", i18n(request, "stormpath.web.changePassword.form.errors.no_token")); } else { try { Application application = (Application) request.getAttribute(Application.class.getName()); application.verifyPasswordResetToken(sptoken); <START> model.put("status", "200"); <END> model.put("message", "OK"); } catch (ResourceException re) { model = errorMap.toErrorMap(re.getStormpathError()); } } return new DefaultViewModel("stormpathJsonView", model); } if (sptoken == null) { return new DefaultViewModel(forgotPasswordUri).setRedirect(true); } else { try { Application application = (Application) request.getAttribute(Application.class.getName()); application.verifyPasswordResetToken(sptoken); } catch (ResourceException re) { return new DefaultViewModel(errorUri).setRedirect(true); } return super.doGet(request, response); } }</code><technical_language>spec specifies actual body status code 200, body empty</technical_language>

Target:
protected ViewModel doGet(HttpServletRequest request, HttpServletResponse response) throws Exception { String sptoken = Strings.clean(request.getParameter("sptoken")); if (isJsonPreferred(request, response)) { Map<String, Object> model = new HashMap<String, Object>(1); if (sptoken == null) { model.put("status", HttpServletResponse.SC_BAD_REQUEST); model.put("message", i18n(request, "stormpath.web.changePassword.form.errors.no_token")); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } else { try { Application application = (Application) request.getAttribute(Application.class.getName()); application.verifyPasswordResetToken(sptoken); response.setContentType(MediaType.APPLICATION_JSON_VALUE); return null; } catch (Exception e) { model = errorModelFactory.toError(request, e).toMap(); response.setStatus(errorModelFactory.toError(request, e).getStatus()); } } return new DefaultViewModel("stormpathJsonView", model); } if (sptoken == null) { return new DefaultViewModel(forgotPasswordUri).setRedirect(true); } else { try { Application application = (Application) request.getAttribute(Application.class.getName()); application.verifyPasswordResetToken(sptoken); } catch (ResourceException re) { return new DefaultViewModel(errorUri).setRedirect(true); } return super.doGet(request, response); } }
Source:
<code>private void setTargetToNearbyBoundaryBlock(Actor oreon, TaskComponent taskComponent) { MinionMoveComponent moveComponent = oreon.getComponent(MinionMoveComponent.class); LocationComponent locationComponent = oreon.getComponent(LocationComponent.class); Vector3f worldPosition = locationComponent.getWorldPosition(new Vector3f()); int maxX = taskComponent.taskRegion.maxX(); int maxZ = taskComponent.taskRegion.maxZ(); int minX = taskComponent.taskRegion.minX(); int minZ = taskComponent.taskRegion.minZ(); int y = taskComponent.taskRegion.minY(); if (Math.round(worldPosition.x) == maxX) { if (Math.round(worldPosition.z) != maxZ) { <START> moveComponent.target = JomlUtil.from(new Vector3f(maxX + 1, y, maxZ + 1)); <END> } else { moveComponent.target = JomlUtil.from(new Vector3f(minX - 1, y, maxZ + 1)); } } else if (Math.round(worldPosition.z) == maxZ) { if (Math.round(worldPosition.x) != minX) { moveComponent.target = JomlUtil.from(new Vector3f(minX - 1, y, maxZ + 1)); } else { moveComponent.target = JomlUtil.from(new Vector3f(minX - 1, y, minZ - 1)); } } else if (Math.round(worldPosition.x) == minX) { if (Math.round(worldPosition.z) != minZ) { moveComponent.target = JomlUtil.from(new Vector3f(minX - 1, y, minZ - 1)); } else { moveComponent.target = JomlUtil.from(new Vector3f(maxX + 1, y, minZ - 1)); } } else { moveComponent.target = JomlUtil.from(new Vector3f(maxX + 1, y, maxZ + 1)); } oreon.save(moveComponent); }</code><technical_language>this replaced moveComponent.target.set(...) everywhere, a single check field is null</technical_language>

Target:
private void setTargetToNearbyBoundaryBlock(Actor oreon, TaskComponent taskComponent) { MinionMoveComponent moveComponent = oreon.getComponent(MinionMoveComponent.class); LocationComponent locationComponent = oreon.getComponent(LocationComponent.class); Vector3f worldPosition = locationComponent.getWorldPosition(new Vector3f()); int maxX = taskComponent.taskRegion.maxX(); int maxZ = taskComponent.taskRegion.maxZ(); int minX = taskComponent.taskRegion.minX(); int minZ = taskComponent.taskRegion.minZ(); int y = taskComponent.taskRegion.minY(); if (moveComponent.target == null) { moveComponent.target = JomlUtil.from(new Vector3f()); } if (Math.round(worldPosition.x) == maxX) { if (Math.round(worldPosition.z) != maxZ) { moveComponent.target.set(maxX + 1, y, maxZ + 1); } else { moveComponent.target.set(minX - 1, y, maxZ + 1); } } else if (Math.round(worldPosition.z) == maxZ) { if (Math.round(worldPosition.x) != minX) { moveComponent.target.set(minX - 1, y, maxZ + 1); } else { moveComponent.target.set(minX - 1, y, minZ - 1); } } else if (Math.round(worldPosition.x) == minX) { if (Math.round(worldPosition.z) != minZ) { moveComponent.target.set(minX - 1, y, minZ - 1); } else { moveComponent.target.set(maxX + 1, y, minZ - 1); } } else { moveComponent.target.set(maxX + 1, y, maxZ + 1); } oreon.save(moveComponent); }
Source:
<code>public PulsarContainer(String pulsarVersion) { super(TestcontainersConfiguration.getInstance().getPulsarImage() + ":" + pulsarVersion); withNetwork(Network.newNetwork()); String networkAlias = "pulsar-" + Base58.randomString(6); withNetworkAliases(networkAlias); <START> withExposedPorts(PULSAR_PORT); <END> }</code><technical_language>network is needed (was needed for Kafka), withExposedPorts</technical_language>

Target:
public PulsarContainer(String pulsarVersion) { super(TestcontainersConfiguration.getInstance().getPulsarImage() + ":" + pulsarVersion); withExposedPorts(PULSAR_PORT); withCommand("/bin/bash", "-c", "" + "servicePort=6850 webServicePort=8280 webServicePortTls=8643 bin/apply-config-from-env.py conf/proxy.conf && " + "bin/pulsar standalone & " + "bin/pulsar proxy --zookeeper-servers localhost:2181 --global-zookeeper-servers localhost:2181" ); waitingFor(Wait.forLogMessage(".*messaging service is ready.*\\s", 1)); }
Source:
<code>protected Order cloneForRevisionHelper(Order target) { if (getAction() == Action.DISCONTINUE) { target.setAction(Action.DISCONTINUE); target.setPreviousOrder(getPreviousOrder()); target.setDateActivated(getDateActivated()); } else { target.setAction(Action.REVISE); target.setPreviousOrder(this); target.setAutoExpireDate(getAutoExpireDate()); } target.setCareSetting(getCareSetting()); target.setConcept(getConcept()); target.setPatient(getPatient()); target.setOrderType(getOrderType()); target.setScheduledDate(getScheduledDate()); target.setInstructions(getInstructions()); target.setUrgency(getUrgency()); target.setCommentToFulfiller(getCommentToFulfiller()); target.setOrderReason(getOrderReason()); target.setOrderReasonNonCoded(getOrderReasonNonCoded()); <START> target.setOrderReasonNonCoded(getOrderReasonNonCoded()); <END> target.setOrderGroup(getOrderGroup()); target.setSortWeight(getSortWeight()); target.setFulfillerStatus(getFulfillerStatus()); target.setFulfillerComment(getFulfillerComment()); return target; }</code><technical_language>Is this a duplicate/unnecessary call</technical_language>

Target:
protected Order cloneForRevisionHelper(Order target) { if (getAction() == Action.DISCONTINUE) { target.setAction(Action.DISCONTINUE); target.setPreviousOrder(getPreviousOrder()); target.setDateActivated(getDateActivated()); } else { target.setAction(Action.REVISE); target.setPreviousOrder(this); target.setAutoExpireDate(getAutoExpireDate()); } target.setCareSetting(getCareSetting()); target.setConcept(getConcept()); target.setPatient(getPatient()); target.setOrderType(getOrderType()); target.setScheduledDate(getScheduledDate()); target.setInstructions(getInstructions()); target.setUrgency(getUrgency()); target.setCommentToFulfiller(getCommentToFulfiller()); target.setOrderReason(getOrderReason()); target.setOrderReasonNonCoded(getOrderReasonNonCoded()); target.setOrderGroup(getOrderGroup()); target.setSortWeight(getSortWeight()); target.setFulfillerStatus(getFulfillerStatus()); target.setFulfillerComment(getFulfillerComment()); return target; }
Source:
<code>private void pollDataFromKafka() { if (eventConsumer == null) { <START> TracingService.logErrorInSpan(getContext().getCurrentSpan(), <END> "Illegal state: kafkaConsumer should not be null when calling pollDataFromKafka method"); throw new IllegalStateException("kafkaConsumer should not be null when calling pollDataFromKafka method"); } if (!isConnectionReady()) { shutdownGracefully("Hila connection closed via crutch"); return; } if (isSubscriptionConsumptionBlocked()) { final String message = "Consumption is blocked"; sendMetadata(message); shutdownGracefully(message); return; } if (eventConsumer.getAssignment().isEmpty() || pollPaused) { scheduleTask(this::pollDataFromKafka, getKafkaPollTimeout(), TimeUnit.MILLISECONDS); return; } final List<ConsumedEvent> events = eventConsumer.readEvents(); events.forEach(this::rememberEvent); if (!events.isEmpty()) { addTask(this::streamToOutput); } addTask(this::pollDataFromKafka); }</code><technical_language>user need it, is internal exception, track in logs</technical_language>

Target:
private void pollDataFromKafka() { if (eventConsumer == null) { throw new IllegalStateException("kafkaConsumer should not be null when calling pollDataFromKafka method"); } if (!isConnectionReady()) { shutdownGracefully("Hila connection closed via crutch"); return; } if (isSubscriptionConsumptionBlocked()) { final String message = "Consumption is blocked"; sendMetadata(message); shutdownGracefully(message); return; } if (eventConsumer.getAssignment().isEmpty() || pollPaused) { scheduleTask(this::pollDataFromKafka, getKafkaPollTimeout(), TimeUnit.MILLISECONDS); return; } final List<ConsumedEvent> events = eventConsumer.readEvents(); events.forEach(this::rememberEvent); if (!events.isEmpty()) { addTask(this::streamToOutput); } addTask(this::pollDataFromKafka); }
Source:
<code>public List getExtensions() { return ImmutableList.of( PropertyDefinition.builder(XmlPlugin.FILE_SUFFIXES_KEY) .name("File suffixes") .description("Comma-separated list of suffixes for files to analyze.") .defaultValue(".xml") .category("XML") .onQualifiers(Qualifiers.PROJECT) .build(), Xml.class, XmlRulesDefinition.class, XmlSonarWayProfile.class, XmlSensor.class, <START> LineCounter.class, <END> XmlCodeColorizerFormat.class); }</code><technical_language>@lindamartin I get works if LineCounter extend interface (e.g. sensor)</technical_language>

Target:
public List getExtensions() { return ImmutableList.of( PropertyDefinition.builder(XmlPlugin.FILE_SUFFIXES_KEY) .name("File suffixes") .description("Comma-separated list of suffixes for files to analyze.") .defaultValue(".xml") .category("XML") .onQualifiers(Qualifiers.PROJECT) .build(), Xml.class, XmlRulesDefinition.class, XmlSonarWayProfile.class, XmlSensor.class); }
Source:
<code>public boolean hasNext() { <START> if (queue == null) { <END> advance(); } return !(queue == null); }</code><technical_language>If values null stored in int Integer</technical_language>

Target:
public boolean hasNext() { if (queue == null) { advance(); } return queue != null; }
Source:
<code>public <T extends Document> DocumentSearchResponse<T> search(final Query query, final Integer start, final Integer size, final Class<T> documentClass) { <START> return search(query, start, size, documentClass, null); <END> }</code><technical_language>Instead of "null" a public constant in SortOrder class define "default" SortOrder</technical_language>

Target:
public <T extends Document> DocumentSearchResponse<T> search(final Query query, final Integer start, final Integer size, final Class<T> documentClass) { return search(query, start, size, documentClass, SortOrder.DEFAULT); }
Source:
<code>public JsonRpcResult getComputedStyleForNode(JsonRpcPeer peer, JSONObject params) { final GetComputedStyleForNodeRequest request = mObjectMapper.convertValue( params, GetComputedStyleForNodeRequest.class); final GetComputedStyleForNodeResult result = new GetComputedStyleForNodeResult(); result.computedStyle = new ArrayList<>(); mDocument.postAndWait(new Runnable() { @Override public void run() { mDocument.getElementStyles( <START> mDocument.getElementForNodeId(request.nodeId), <END> new StyleAccumulator() { @Override public void store(String name, String value, boolean isDefault) { if (!isDefault) { CSSComputedStyleProperty property = new CSSComputedStyleProperty(); property.name = name; property.value = value; result.computedStyle.add(property); } } }); } }); return result; }</code><technical_language>call getElementForNodeId check return passing getElementStyles</technical_language>

Target:
public JsonRpcResult getComputedStyleForNode(JsonRpcPeer peer, JSONObject params) { final GetComputedStyleForNodeRequest request = mObjectMapper.convertValue( params, GetComputedStyleForNodeRequest.class); final GetComputedStyleForNodeResult result = new GetComputedStyleForNodeResult(); result.computedStyle = new ArrayList<>(); mDocument.postAndWait(new Runnable() { @Override public void run() { Object element = mDocument.getElementForNodeId(request.nodeId); if (element == null) { LogUtil.e("Tried to get the style of an element that does not exist, using nodeid=" + request.nodeId); return; } mDocument.getElementStyles( element, new StyleAccumulator() { @Override public void store(String name, String value, boolean isDefault) { if (!isDefault) { CSSComputedStyleProperty property = new CSSComputedStyleProperty(); property.name = name; property.value = value; result.computedStyle.add(property); } } }); } }); return result; }
Source:
<code><START> public static ServiceAccountJwtAccessCredentials fromPkcs8( <END> String clientId, String clientEmail, String privateKeyPkcs8, String privateKeyId, URI defaultAudience, String quotaProjectId) throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(privateKeyPkcs8); return new ServiceAccountJwtAccessCredentials( clientId, clientEmail, privateKey, privateKeyId, defaultAudience, quotaProjectId); }</code><technical_language>This is unnecessary</technical_language>

Target:
static ServiceAccountJwtAccessCredentials fromPkcs8( String clientId, String clientEmail, String privateKeyPkcs8, String privateKeyId, URI defaultAudience, String quotaProjectId) throws IOException { PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(privateKeyPkcs8); return new ServiceAccountJwtAccessCredentials( clientId, clientEmail, privateKey, privateKeyId, defaultAudience, quotaProjectId); }
Source:
<code>@Override public SingleEnvironment bindSingle(Run<?,?> build, FilePath workspace, Launcher launcher, TaskListener listener) throws IOException, InterruptedException { if(workspace==null) <START> return new SingleEnvironment(""); <END> FileCredentials credentials = getCredentials(build); FilePath secrets = secretsDir(workspace); String dirName = UUID.randomUUID().toString(); final FilePath dir = secrets.child(dirName); dir.mkdirs(); secrets.chmod( 448); FilePath secret = dir.child(credentials.getFileName()); copy(secret, credentials); if (secret.isDirectory()) { secret.chmod(0700); } else { secret.chmod(0400); } return new SingleEnvironment(secret.getRemote(), new UnbinderImpl(dirName)); }</code><technical_language>bug: workspace parameter Binding.bindSingle marked @Nonnull (ditto MultiBinding.bind) this reverted</technical_language>

Target:
@Override public SingleEnvironment bindSingle(Run<?,?> build, FilePath workspace, Launcher launcher, TaskListener listener) throws IOException, InterruptedException { FileCredentials credentials = getCredentials(build); FilePath secrets = secretsDir(workspace); String dirName = UUID.randomUUID().toString(); final FilePath dir = secrets.child(dirName); dir.mkdirs(); secrets.chmod( 448); FilePath secret = dir.child(credentials.getFileName()); copy(secret, credentials); if (secret.isDirectory()) { secret.chmod(0700); } else { secret.chmod(0400); } return new SingleEnvironment(secret.getRemote(), new UnbinderImpl(dirName)); }
Source:
<code><START> public void testCreateDecoratedTwoRequestsToGetEquallyDecoratedSamePoolUseSameLock() { <END> DecoratedMacPoolFactory factory = new DecoratedMacPoolFactory(lockedObjectFactorySpy); MacPool decoratedPool1 = factory.createDecoratedPool(poolId, macPool, singletonList(macPoolDecoratorA)); MacPool decoratedPool2 = factory.createDecoratedPool(poolId, macPool, singletonList(macPoolDecoratorA)); assertThat(decoratedPool1, is(macPoolDecoratorA)); assertThat(decoratedPool2, is(macPoolDecoratorA)); verify(lockedObjectFactorySpy, times(2)).createLockingInstance(eq(macPool), eq(MacPool.class), any()); }</code><technical_language>Some picking (so feel free ignore) test name is absolutely puzzling for (I this is a legacy thing, modify it, fix that) test tests things: - 2 requests decorator result in decorator - locking instance is divide 2 tests, rename like: testRequestsWithSameDecoratorAreEqualyDecorated testRequestsWithSameDecoratorUseSameLock for other test: testRequestsWithDifferentDecoratorAreEDifferentlyDecorated testRequestsWithDifferentDecoratorUseSameLock</technical_language>

Target:
public void testCreateDecoratedTwoRequestsToGetEquallyDecoratedSamePoolUseSameLock() { multipleDecoratorsUsesSameLock(macPoolDecoratorA, macPoolDecoratorA); }
Source:
<code>public void testDefaultOptions() { Map<String, String> options = getAllOptions(); CanalJsonDeserializationSchema expectedDeser = CanalJsonDeserializationSchema <START> .builder(ROW_TYPE, InternalTypeInfo.of(ROW_TYPE)) <END> .setIgnoreParseErrors(false) .setTimestampFormat(TimestampFormat.SQL) .build(); DeserializationSchema<RowData> actualDeser = createDeserializationSchema(options); assertEquals(expectedDeser, actualDeser); CanalJsonSerializationSchema expectedSer = new CanalJsonSerializationSchema( ROW_TYPE, TimestampFormat.SQL); SerializationSchema<RowData> actualSer = createSerializationSchema(options); assertEquals(expectedSer, actualSer); }</code><technical_language>This reused declaring static member</technical_language>

Target:
public void testDefaultOptions() { Map<String, String> options = getAllOptions(); CanalJsonDeserializationSchema expectedDeser = CanalJsonDeserializationSchema .builder(ROW_TYPE, ROW_TYPE_INFO) .setIgnoreParseErrors(false) .setTimestampFormat(TimestampFormat.SQL) .build(); DeserializationSchema<RowData> actualDeser = createDeserializationSchema(options); assertEquals(expectedDeser, actualDeser); CanalJsonSerializationSchema expectedSer = new CanalJsonSerializationSchema( ROW_TYPE, TimestampFormat.SQL); SerializationSchema<RowData> actualSer = createSerializationSchema(options); assertEquals(expectedSer, actualSer); }
Source:
<code>protected String getStackTraceString(Throwable throwable) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); try { throwable.printStackTrace(pw); return sw.toString().trim(); } finally { try { pw.close(); <START> sw.close(); <END> } catch (IOException e) { } } }</code><technical_language>technically if PrintWriter throws exception StringWriter closed :-)</technical_language>

Target:
protected String getStackTraceString(Throwable throwable) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); try { throwable.printStackTrace(pw); return sw.toString().trim(); } finally { pw.close(); } }
Source:
<code><START> public K keyToStorage(Object key) { <END> return (K) wrapper.wrapKey(encoder.keyToStorage(key)); }</code><technical_language>if do creation of List lazily in iterate keys create list find a key encoded. soon find reiterate (unless first) create list. This cases encoding (such ByteArrayWrapper). in other cases element wrapped incur additional processing</technical_language>

Target:
public K keyToStorage(Object key) { return (K) keyWrapper.wrap(keyEncoder.toStorage(key)); }
Source:
<code>public boolean equals(Object obj) { if (obj instanceof WindowAggNode) { WindowAggNode other = (WindowAggNode) obj; boolean eq = super.equals(other); eq = eq && TUtil.checkEquals(partitionKeys, other.partitionKeys); eq = eq && TUtil.checkEquals(windowFuncs, other.windowFuncs); <START> eq = eq && TUtil.checkEquals(targets, other.targets); <END> return eq; } else { return false; } }</code><technical_language>SortSpec hasDistinct flag compared</technical_language>

Target:
public boolean equals(Object obj) { if (obj instanceof WindowAggNode) { WindowAggNode other = (WindowAggNode) obj; boolean eq = super.equals(other); eq = eq && TUtil.checkEquals(partitionKeys, other.partitionKeys); eq = eq && TUtil.checkEquals(sortSpecs, other.sortSpecs); eq = eq && TUtil.checkEquals(windowFuncs, other.windowFuncs); eq = eq && TUtil.checkEquals(targets, other.targets); eq = eq && TUtil.checkEquals(hasDistinct, other.hasDistinct); return eq; } else { return false; } }
Source:
<code>public void testNetworks() throws Exception { requireDockerApiVersionAtLeast("1.21", "createNetwork and listNetworks"); assumeFalse(CIRCLECI); final String networkName = randomName(); final IpamConfig ipamConfig = IpamConfig.create("192.168.0.0/24", "192.168.0.0/24", "192.168.0.1"); <START> final Ipam ipam = Ipam.builder() <END> .config(singletonList(ipamConfig)) .build(); final NetworkConfig networkConfig = NetworkConfig.builder().name(networkName).driver("bridge").checkDuplicate(true).ipam(ipam) .internal(false).enableIPv6(false) .build(); final NetworkCreation networkCreation = sut.createNetwork(networkConfig); assertThat(networkCreation.id(), is(notNullValue())); assertThat(networkCreation.warnings(), is(nullValue())); final List<Network> networks = sut.listNetworks(); assertTrue(networks.size() > 0); Network network = null; for (final Network n : networks) { if (n.name().equals(networkName)) { network = n; } } assertThat(network, is(notNullValue())); assertThat(network.id(), is(notNullValue())); assertThat(sut.inspectNetwork(network.id()).name(), is(networkName)); assertThat(network.ipam(), equalTo(ipam)); if (dockerApiVersionAtLeast("1.23")) { assertThat(network.internal(), is(false)); assertThat(network.enableIPv6(), is(false)); } sut.removeNetwork(network.id()); exception.expect(NetworkNotFoundException.class); sut.inspectNetwork(network.id()); }</code><technical_language>This needed still</technical_language>

Target:
public void testNetworks() throws Exception { requireDockerApiVersionAtLeast("1.21", "createNetwork and listNetworks"); assumeFalse(CIRCLECI); final String networkName = randomName(); final IpamConfig ipamConfig = IpamConfig.create("192.168.0.0/24", "192.168.0.0/24", "192.168.0.1"); final Ipam ipam = Ipam.builder() .driver("default") .config(singletonList(ipamConfig)) .build(); final NetworkConfig networkConfig = NetworkConfig.builder().name(networkName).driver("bridge").checkDuplicate(true).ipam(ipam) .internal(false).enableIPv6(false) .build(); final NetworkCreation networkCreation = sut.createNetwork(networkConfig); assertThat(networkCreation.id(), is(notNullValue())); assertThat(networkCreation.warnings(), is(nullValue())); final List<Network> networks = sut.listNetworks(); assertTrue(networks.size() > 0); Network network = null; for (final Network n : networks) { if (n.name().equals(networkName)) { network = n; } } assertThat(network, is(notNullValue())); assertThat(network.id(), is(notNullValue())); assertThat(sut.inspectNetwork(network.id()).name(), is(networkName)); assertThat(network.ipam(), equalTo(ipam)); if (dockerApiVersionAtLeast("1.23")) { assertThat(network.internal(), is(false)); assertThat(network.enableIPv6(), is(false)); } sut.removeNetwork(network.id()); exception.expect(NetworkNotFoundException.class); sut.inspectNetwork(network.id()); }
Source:
<code>public void testBatch() throws Exception { <START> doTestBatch(basicConf()); <END> }</code><technical_language>This conf STORM-MESSAGING-NETTY-BUFFER-SIZE 1024000 test-batch defines, want define another method for new configuration</technical_language>

Target:
public void testBatch() throws Exception { doTestBatch(batchConf()); }
Source:
<code><START> protected static String truncateValueToMaxLength(String inputValue, int maxLength) { <END> if (StringUtils.length(inputValue) <= maxLength) { return inputValue; } else { return inputValue.substring(0, maxLength); } }</code><technical_language>StringUtils.truncate instead</technical_language>

Target:
protected String truncateValueToMaxLength(String inputValue, int maxLength) { return StringUtils.substring(inputValue, 0, maxLength); }
Source:
<code>public DocumentModel run(DocumentModel document) { if (!rule.hasFacet(RetentionConstants.RETENTION_RULE_FACET)) { <START> throw new NuxeoException(String.format("Document is not a rule")); <END> } RetentionRule rr = rule.getAdapter(RetentionRule.class); if (!rr.isManual()) { throw new IllegalArgumentException("Only manual rule can be manually attached"); } document = retentionManager.attachRule(document, rr, session); return document; }</code><technical_language>String.format(... is needed here, need passe rule process in</technical_language>

Target:
public DocumentModel run(DocumentModel document) { if (!rule.hasFacet(RetentionConstants.RETENTION_RULE_FACET)) { throw new NuxeoException("Document is not a rule: " + document); } RetentionRule rr = rule.getAdapter(RetentionRule.class); if (!rr.isManual()) { throw new IllegalArgumentException("Only manual rule can be manually attached"); } document = retentionManager.attachRule(document, rr, session); return document; }
Source:
<code>public void parameterizedRebuild(Run currentBuild, StaplerResponse response) throws IOException { Job project = getProject(); if (project == null) { return; } <START> System.out.println("rbx: " + (currentBuild == build)); <END> project.checkPermission(Item.BUILD); if (isRebuildAvailable()) { List<Action> actions = constructRebuildActions(build, currentBuild.getAction(ParametersAction.class)); Hudson.getInstance().getQueue().schedule((Queue.Task) build.getParent(), 0, actions); response.sendRedirect("../../"); } }</code><technical_language>Please avoid System.out. logging if text output necessary (but is?)</technical_language>

Target:
public void parameterizedRebuild(Run currentBuild, StaplerResponse response) throws IOException { Job project = getProject(); if (project == null) { return; } project.checkPermission(Item.BUILD); if (isRebuildAvailable()) { List<Action> actions = constructRebuildActions(build, currentBuild.getAction(ParametersAction.class)); Hudson.getInstance().getQueue().schedule((Queue.Task) build.getParent(), 0, actions); response.sendRedirect("../../"); } }
Source:
<code>private boolean isEquivalentOutboundRelationship(final Multimap<Concept, Concept> equivalentConcepts, Relationship relationshipToRemove, Relationship relationshipToKeep) { Concept destinationToKeep = relationshipToKeep.getDestination(); Concept destinationToRemove = relationshipToRemove.getDestination(); <START> equivalentConcepts.get(destinationToKeep); <END> return relationshipToRemove.getType().equals(relationshipToKeep.getType()) && (destinationToRemove.equals(destinationToKeep) || equivalentConcepts.get(destinationToKeep).contains(destinationToRemove)) && relationshipToRemove.getCharacteristicType().equals(relationshipToKeep.getCharacteristicType()) && relationshipToRemove.getModifier().equals(relationshipToKeep.getModifier()); }</code><technical_language>here; please remove statements if effect</technical_language>

Target:
private boolean isEquivalentOutboundRelationship(final Multimap<Concept, Concept> equivalentConcepts, Relationship relationshipToRemove, Relationship relationshipToKeep) { Concept destinationToKeep = relationshipToKeep.getDestination(); Concept destinationToRemove = relationshipToRemove.getDestination(); return relationshipToRemove.getType().equals(relationshipToKeep.getType()) && (destinationToRemove.equals(destinationToKeep) || equivalentConcepts.get(destinationToKeep).contains(destinationToRemove)) && relationshipToRemove.getCharacteristicType().equals(relationshipToKeep.getCharacteristicType()) && relationshipToRemove.getModifier().equals(relationshipToKeep.getModifier()); }
Source:
<code>public String fetchApiVersionFromServer(String baseUrl, ApacheHttpClientDelegate delegate) throws IOException { <START> HttpGet get = new HttpGet(baseUrl + "/version"); <END> get.addHeader(HttpHeaders.ACCEPT, "*/*"); get.addHeader(HttpHeaders.CONTENT_TYPE, "application/json"); CloseableHttpResponse response = delegate.getHttpClient().execute(get); return response.getFirstHeader("Api-Version") != null ? response.getFirstHeader("Api-Version").getValue() : null; }</code><technical_language>java baseUrl + (baseUrl.endsWith("/") ? "" : "/") + "version"</technical_language>

Target:
public String fetchApiVersionFromServer(String baseUrl, ApacheHttpClientDelegate delegate) throws IOException { HttpGet get = new HttpGet(baseUrl + (baseUrl.endsWith("/") ? "" : "/") + "version"); get.addHeader(HttpHeaders.ACCEPT, "*/*"); get.addHeader(HttpHeaders.CONTENT_TYPE, "application/json"); CloseableHttpResponse response = delegate.getHttpClient().execute(get); return response.getFirstHeader("Api-Version") != null ? response.getFirstHeader("Api-Version").getValue() : null; }
Source:
<code><START> Long countByCoordinatesAndAlleles(String chromosome, int start, String reference, String alternate) { <END> if (alternate != null) { return variantEntityRepository.countByChromosomeAndStartAndReferenceAndAlternate(chromosome, start, reference, alternate); } else { return variantEntityRepository.countByChromosomeAndStartAndReference(chromosome, start, reference); } }</code><technical_language>This method private</technical_language>

Target:
private Long countByCoordinatesAndAlleles(String chromosome, int start, String reference, String alternate) { if (alternate != null) { return variantEntityRepository.countByChromosomeAndStartAndReferenceAndAlternate(chromosome, start, reference, alternate); } else { return variantEntityRepository.countByChromosomeAndStartAndReference(chromosome, start, reference); } }
Source:
<code>public void onSelectionChanged(SelectionChangedEvent event) { final String isLinkedWithEditor = preferencesManager.getValue(LinkWithEditorAction.LINK_WITH_EDITOR); if (isNullOrEmpty(isLinkedWithEditor) || !Boolean.parseBoolean(isLinkedWithEditor)) { return; } final Selection<?> selection = event.getSelection(); if (selection instanceof Selection.NoSelectionProvided) { return; } Resource currentResource = null; if (selection == null || selection.getHeadElement() == null || selection.getAllElements().size() > 1) { return; } final Object headObject = selection.getHeadElement(); if (headObject instanceof HasDataObject) { Object data = ((HasDataObject)headObject).getData(); if (data instanceof Resource) { currentResource = (Resource)data; } } else if (headObject instanceof Resource) { currentResource = (Resource)headObject; } EditorPartStack activePartStack = editorMultiPartStack.getActivePartStack(); if (currentResource == null || activePartStack == null || activeEditor == null) { return; } if (!(activePart instanceof ProjectExplorerPresenter) && <START> currentResource.getLocation().equals(activeEditor.getEditorInput().getFile().getLocation())) { <END> return; } PartPresenter partPresenter = activePartStack.getPartByPath(currentResource.getLocation()); if (partPresenter != null) { workspaceAgent.setActivePart(partPresenter, EDITING); } }</code><technical_language>try simplify code</technical_language>

Target:
public void onSelectionChanged(SelectionChangedEvent event) { final String isLinkedWithEditor = preferencesManager.getValue(LinkWithEditorAction.LINK_WITH_EDITOR); if (!parseBoolean(isLinkedWithEditor)) { return; } final Selection<?> selection = event.getSelection(); if (selection instanceof Selection.NoSelectionProvided) { return; } Resource currentResource = null; if (selection == null || selection.getHeadElement() == null || selection.getAllElements().size() > 1) { return; } final Object headObject = selection.getHeadElement(); if (headObject instanceof HasDataObject) { Object data = ((HasDataObject)headObject).getData(); if (data instanceof Resource) { currentResource = (Resource)data; } } else if (headObject instanceof Resource) { currentResource = (Resource)headObject; } EditorPartStack activePartStack = editorMultiPartStack.getActivePartStack(); if (currentResource == null || activePartStack == null || activeEditor == null) { return; } final Path locationOfActiveOpenedFile = activeEditor.getEditorInput().getFile().getLocation(); final Path selectedResourceLocation = currentResource.getLocation(); if (!(activePart instanceof ProjectExplorerPresenter) && selectedResourceLocation.equals(locationOfActiveOpenedFile)) { return; } PartPresenter partPresenter = activePartStack.getPartByPath(selectedResourceLocation); if (partPresenter != null) { workspaceAgent.setActivePart(partPresenter, EDITING); } }
Source:
<code>private VDSExceptionBase createException() { VDSExceptionBase outEx; final String errorMessage = String.format("Failed to %1$s, error = %2$s", getCommandName(), getReturnStatus().mMessage); outEx = createDefaultConcreteException(errorMessage); <START> return outEx; <END> }</code><technical_language>inline return statement</technical_language>

Target:
private VDSExceptionBase createException() { final String errorMessage = String.format("Failed to %1$s, error = %2$s", getCommandName(), getReturnStatus().mMessage); return createDefaultConcreteException(errorMessage); }
Source:
<code>void processEvents(LockWatchEvents events, UUID versionId) { if (events.events().isEmpty()) { return; } <START> Preconditions.checkArgument(events.versionRange().isPresent(), <END> "Cannot have an empty range of versions with non-zero number of events"); events.events().forEach(event -> event.accept(visitor)); snapshotVersion = Optional.of( LockWatchVersion.of(versionId, events.versionRange().map(Range::upperEndpoint).get())); }</code><technical_language>Feels impossible? if possible, this live in LockWatchEvents</technical_language>

Target:
void processEvents(LockWatchEvents events, UUID versionId) { if (events.events().isEmpty()) { return; } events.events().forEach(event -> event.accept(visitor)); snapshotVersion = Optional.of( LockWatchVersion.of(versionId, events.versionRange().map(Range::upperEndpoint).get())); }
Source:
<code>private static Exception refineException(B2Error error, Exception exception) { if ("bad_json".equals(error.code())) { return new IllegalArgumentException(error.message(), exception); <START> } else { <END> return exception; } }</code><technical_language>try refine 404 errors a ResourceNotFoundException 404 fallbacks work</technical_language>

Target:
private static Exception refineException(B2Error error, Exception exception) { if ("bad_bucket_id".equals(error.code())) { return new ContainerNotFoundException(exception); } else if ("bad_json".equals(error.code())) { return new IllegalArgumentException(error.message(), exception); } else { return exception; } }
Source:
<code>protected Response performRemove(String id) { <START> throw new MethodNotAllowedException("No resource method found for DELETE quota element"); <END> }</code><technical_language>please throw UnsupportedOperationException isntead</technical_language>

Target:
protected Response performRemove(String id) { throw new UnsupportedOperationException(); }
Source:
<code>protected String generateVmConfiguration(VM vm) { ArrayList<DiskImage> allVmImages = new java.util.ArrayList<DiskImage>(); if (vm.getInterfaces() == null || vm.getInterfaces().isEmpty()) { <START> vm.setInterfaces(DbFacade.getInstance().getVmNetworkInterfaceDAO().getAllForVm(vm.getId())); <END> } for (DiskImage diskImage : getDiskImageDao().getAllForVm(vm.getId())) { allVmImages.addAll(ImagesHandler.getAllImageSnapshots(diskImage.getId(), diskImage.getit_guid())); } if (StringHelper.isNullOrEmpty(vm.getvmt_name())) { VmTemplate t = DbFacade.getInstance().getVmTemplateDAO().get(vm.getvmt_guid()); vm.setvmt_name(t.getname()); } RefObject<String> tempRefObject = new RefObject<String>(""); new OvfManager().ExportVm(tempRefObject, vm, allVmImages); return tempRefObject.argvalue; }</code><technical_language>For test purposes, if extract a private method calls: DbFacade.getInstance().getVmNetworkInterfaceDAO()</technical_language>

Target:
protected String generateVmConfiguration(VM vm) { ArrayList<DiskImage> allVmImages = new java.util.ArrayList<DiskImage>(); if (vm.getInterfaces() == null || vm.getInterfaces().isEmpty()) { vm.setInterfaces(getVmNetworkInterfaceDao().getAllForVm(vm.getId())); } for (DiskImage diskImage : getDiskImageDao().getAllForVm(vm.getId())) { allVmImages.addAll(ImagesHandler.getAllImageSnapshots(diskImage.getId(), diskImage.getit_guid())); } if (StringHelper.isNullOrEmpty(vm.getvmt_name())) { VmTemplate t = getVmTemplateDao().get(vm.getvmt_guid()); vm.setvmt_name(t.getname()); } RefObject<String> tempRefObject = new RefObject<String>(""); new OvfManager().ExportVm(tempRefObject, vm, allVmImages); return tempRefObject.argvalue; }
Source:
<code>public void doTest() throws URISyntaxException, IOException { for (File localeFile: getMessagesPropertiesFiles(".")) { Properties properties = loadProperties(localeFile); compareMethodsToProperties(messagesMethods, properties, localeFile); } <START> assertTrue(format(errors), errors.isEmpty()); <END> }</code><technical_language>+1 List aggregate errors test execution asserting List is empty end</technical_language>

Target:
public void doTest() throws URISyntaxException, IOException { File messageFileDir = new File( this.getClass().getResource(".").toURI().toASCIIString().replaceAll("file:", "")); List<String> errors = GwtMessagesValidator.validateClass(CommonApplicationMessages.class, messageFileDir); assertTrue(GwtMessagesValidator.format(errors), errors.isEmpty()); }
Source:
<code>public ByteBuffer toByteBuffer( final EntityWrapper wrapper ) { if ( wrapper == null ) { return null; } FieldBufferBuilder builder = new FieldBufferBuilder( 3 ); builder.addByte( VERSION ); builder.addUUID( wrapper.version ); if ( !wrapper.entity.isPresent() ) { builder.addByte( STATE_DELETED ); return FIELD_BUFFER_SERIALIZER.toByteBuffer( builder.build() ); } if ( wrapper.status != MvccEntity.Status.COMPLETE ) { throw new UnsupportedOperationException( "Only states " + MvccEntity.Status.DELETED + " and " + MvccEntity.Status.COMPLETE + " are supported" ); } builder.addByte( STATE_COMPLETE ); final Entity entity = wrapper.entity.get(); final EntityMap entityMap = EntityMap.fromEntity( entity ); final String entityString; try { <START> entityString = MAPPER.writeValueAsString( entityMap ); <END> } catch ( Exception e ) { throw new RuntimeException( "Unable to serialize entity", e ); } final int maxEntrySize = serializationFig.getMaxEntitySize(); if ( entityString.length() > maxEntrySize ) { throw new EntityTooLargeException( entity, maxEntrySize, entityString.length(), "Your entity cannot exceed " + maxEntrySize + " bytes. The entity you tried to save was " + entityString.length() + " bytes" ); } if( log.isDebugEnabled() ){ log.debug("Entity(" + entityString + ") Version("+wrapper.version+") State("+wrapper.status+")"); } builder.addString(entityString); return FIELD_BUFFER_SERIALIZER.toByteBuffer( builder.build() ); }</code><technical_language>This fieldbuffer byte buffer. remove this completely a nested JSON object</technical_language>

Target:
public ByteBuffer toByteBuffer( final EntityWrapper wrapper ) { if ( wrapper == null ) { return null; } wrapper.setSerailizationVersion(VERSION); if ( wrapper.getEntity() == null ) { try { return ByteBuffer.wrap(MAPPER.writeValueAsBytes(wrapper)); }catch (JsonProcessingException jpe){ throw new RuntimeException( "Unable to serialize entity", jpe ); } } if ( wrapper.getStatus() != MvccEntity.Status.COMPLETE ) { throw new UnsupportedOperationException( "Only states " + MvccEntity.Status.DELETED + " and " + MvccEntity.Status.COMPLETE + " are supported" ); } wrapper.setStatus(MvccEntity.Status.COMPLETE); final byte[] wrapperBytes; try { wrapperBytes = MAPPER.writeValueAsBytes(wrapper); final int maxEntrySize = serializationFig.getMaxEntitySize(); if (wrapperBytes.length > maxEntrySize) { throw new EntityTooLargeException(Entity.fromMap(wrapper.getEntity()), maxEntrySize, wrapperBytes.length, "Your entity cannot exceed " + maxEntrySize + " bytes. The entity you tried to save was " + wrapperBytes.length + " bytes"); } } catch ( JsonProcessingException jpe ) { throw new RuntimeException( "Unable to serialize entity", jpe ); } return ByteBuffer.wrap(wrapperBytes); }
Source:
<code>public void testArtifactUniqueness() throws Exception { JobExecution jobExecution = JsrTestUtils.runJob("jsrUniqueInstanceTests", new Properties(), 10000L); String exitStatus = jobExecution.getExitStatus(); <START> assertEquals("listener3listener2listener1listener0listener7listener6listener5listener4", exitStatus); <END> }</code><technical_language>listener execution order guaranteed, do want validate this this .contains() of values</technical_language>

Target:
public void testArtifactUniqueness() throws Exception { JobExecution jobExecution = JsrTestUtils.runJob("jsrUniqueInstanceTests", new Properties(), 10000L); String exitStatus = jobExecution.getExitStatus(); assertTrue("Exit status must contain listener3", exitStatus.contains("listener3")); exitStatus = exitStatus.replace("listener3", ""); assertTrue("Exit status must contain listener2", exitStatus.contains("listener2")); exitStatus = exitStatus.replace("listener2", ""); assertTrue("Exit status must contain listener1", exitStatus.contains("listener1")); exitStatus = exitStatus.replace("listener1", ""); assertTrue("Exit status must contain listener0", exitStatus.contains("listener0")); exitStatus = exitStatus.replace("listener0", ""); assertTrue("Exit status must contain listener7", exitStatus.contains("listener7")); exitStatus = exitStatus.replace("listener7", ""); assertTrue("Exit status must contain listener6", exitStatus.contains("listener6")); exitStatus = exitStatus.replace("listener6", ""); assertTrue("Exit status must contain listener5", exitStatus.contains("listener5")); exitStatus = exitStatus.replace("listener5", ""); assertTrue("Exit status must contain listener4", exitStatus.contains("listener4")); exitStatus = exitStatus.replace("listener4", ""); assertTrue("exitStatus must be empty", "".equals(exitStatus)); }
Source:
<code>public void checkMainFeaturesTypeScriptLS() { <START> String intitTypeScriptLanguageServerMessage = <END> format("Finished language servers initialization, file path '/%s'", PATH_TO_GREETER_FILE); consoles.waitExpectedTextIntoConsole(intitTypeScriptLanguageServerMessage); checkCodeValidation(); checkCodeAssistant(); checkGoToDefinition(); }</code><technical_language>intitTypeScriptLanguageServerMessage > initTypeScriptLanguageServerMessage</technical_language>

Target:
public void checkMainFeaturesTypeScriptLS() { String initTypeScriptLanguageServerMessage = format("Finished language servers initialization, file path '/%s'", PATH_TO_GREETER_FILE); consoles.waitExpectedTextIntoConsole(initTypeScriptLanguageServerMessage); checkCodeValidation(); checkCodeAssistant(); checkGoToDefinition(); }
Source:
<code>public Storage newStorage(Config config) { com.google.cloud.storage.Storage storage; <START> if (config.has("creadentials.json_key")) { <END> storage = getStorageFromJsonKey(config); } else { storage = StorageOptions.getDefaultInstance().getService(); } String bucket = config.get("bucket", String.class); return new GCSStorage(config, storage, bucket); }</code><technical_language>Fix typo. s/creadentials/credentials/</technical_language>

Target:
public Storage newStorage(Config config) { com.google.cloud.storage.Storage storage; if (config.has(PATH_KEY)) { storage = getStorageFromJsonKey(config, PATH_KEY); } else if (config.has(CONTENT_KEY)) { storage = getStorageFromJsonKey(config, CONTENT_KEY); } else { storage = StorageOptions.getDefaultInstance().getService(); } String bucket = config.get("bucket", String.class); return new GCSStorage(config, storage, bucket); }
Source:
<code>public FluentProtocol executeTasks() { Condition.Result result = condition.getResult(); <START> if (result.isValid) { <END> if (setup.getTimeoutSec() > 0) { tradeProtocol.startTimeout(setup.getTimeoutSec()); } NodeAddress peer = condition.getPeer(); if (peer != null) { tradeProtocol.processModel.setTempTradingPeerNodeAddress(peer); } TradeMessage message = condition.getMessage(); if (message != null) { tradeProtocol.processModel.setTradeMessage(message); } TradeTaskRunner taskRunner = setup.getTaskRunner(message, condition.getEvent()); taskRunner.addTasks(setup.getTasks()); taskRunner.run(); } else if (resultHandler != null) { resultHandler.accept(result); } return this; }</code><technical_language>want return early avoid large blocks</technical_language>

Target:
public FluentProtocol executeTasks() { Condition.Result result = condition.getResult(); if (!result.isValid) { if (resultHandler != null) { resultHandler.accept(result); } return this; } if (setup.getTimeoutSec() > 0) { tradeProtocol.startTimeout(setup.getTimeoutSec()); } NodeAddress peer = condition.getPeer(); if (peer != null) { tradeProtocol.processModel.setTempTradingPeerNodeAddress(peer); } TradeMessage message = condition.getMessage(); if (message != null) { tradeProtocol.processModel.setTradeMessage(message); } TradeTaskRunner taskRunner = setup.getTaskRunner(message, condition.getEvent()); taskRunner.addTasks(setup.getTasks()); taskRunner.run(); return this; }
Source:
<code>private boolean doDispatch(Message<?> message) { if (tryOptimizedDispatch(message)) { return true; } boolean success = false; Iterator<MessageHandler> handlerIterator = this.getHandlerIterator(message); if (!handlerIterator.hasNext()) { throw new MessageDispatchingException(message, "Dispatcher has no subscribers"); } List<RuntimeException> exceptions = new ArrayList<>(); while (!success && handlerIterator.hasNext()) { MessageHandler handler = handlerIterator.next(); try { handler.handleMessage(message); success = true; } catch (Exception ex) { RuntimeException runtimeException = IntegrationUtils.wrapInDeliveryExceptionIfNecessary(message, () -> "Dispatcher failed to deliver Message", ex); <START> exceptions.add(runtimeException); <END> boolean isLast = !handlerIterator.hasNext(); if (!isLast && this.failover && this.logger.isInfoEnabled()) { this.logger.info("An exception thrown from the '" + handler + "' for the '" + message + "'. " + "Will be in a failover for the next subscriber.", ex); } handleExceptions(exceptions, message, isLast); } } return success; }</code><technical_language>this line wrap? previously 112</technical_language>

Target:
private boolean doDispatch(Message<?> message) { if (tryOptimizedDispatch(message)) { return true; } boolean success = false; Iterator<MessageHandler> handlerIterator = getHandlerIterator(message); if (!handlerIterator.hasNext()) { throw new MessageDispatchingException(message, "Dispatcher has no subscribers"); } List<RuntimeException> exceptions = null; while (!success && handlerIterator.hasNext()) { MessageHandler handler = handlerIterator.next(); try { handler.handleMessage(message); success = true; } catch (Exception ex) { RuntimeException runtimeException = IntegrationUtils.wrapInDeliveryExceptionIfNecessary(message, () -> "Dispatcher failed to deliver Message", ex); if (exceptions == null) { exceptions = new ArrayList<>(); } exceptions.add(runtimeException); boolean isLast = !handlerIterator.hasNext(); if (!isLast && this.failover) { logExceptionBeforeFailOver(ex, handler, message); } handleExceptions(exceptions, message, isLast); } } return success; }