auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testRemoveAll(){ <START> ObservableArrayList<String> list = new ObservableArrayList<>(); <END> list.onChanged(new ListChangeListener<String>() { @Override public void listChanged(ListChangeEvent<? extends String> evt) { System.out.println(evt.getChanges().get(0).getFrom()+" - "+evt.getChanges().get(0).getFrom()); } }); Assert.assertTrue(list.isEmpty()); Assert.assertEquals(list.size(), 0); list.addAll("1", "2", "3", "4", "5", "6", "7" ,"8" , "9", "10"); Assert.assertFalse(list.isEmpty()); Assert.assertEquals(list.size(), 10); list.removeAll(Arrays.asList("1", "2", "3", "4", "5")); Assert.assertFalse(list.isEmpty()); Assert.assertEquals(list.size(), 5); assertSameContent(list, Arrays.asList("6", "7" ,"8" , "9", "10")); list.clear(); }</code><technical_language>final</technical_language>

Target:
public void testRemoveAll(){ final ObservableArrayList<String> list = new ObservableArrayList<>(); Assert.assertTrue(list.isEmpty()); Assert.assertEquals(list.size(), 0); list.addAll("1", "2", "3", "4", "5", "6", "7" ,"8" , "9", "10"); Assert.assertFalse(list.isEmpty()); Assert.assertEquals(list.size(), 10); list.removeAll(Arrays.asList("1", "2", "3", "4", "5")); Assert.assertFalse(list.isEmpty()); Assert.assertEquals(list.size(), 5); assertSameContent(list, Arrays.asList("6", "7" ,"8" , "9", "10")); list.clear(); }
Source:
<code>public static DevicePropertiesUtils getInstance() { <START> if (devicePropertiesUtils == null) { <END> synchronized (DevicePropertiesUtils.class) { if (devicePropertiesUtils == null) { devicePropertiesUtils = new DevicePropertiesUtils(); } } } return devicePropertiesUtils; }</code><technical_language>I prefer static initialization, this double check. getInstance() for time InitBackendServiceOnStartup bean</technical_language>

Target:
public static DevicePropertiesUtils getInstance() { return devicePropertiesUtils; }
Source:
<code>public void shouldSendPasswordResetReminder() throws Exception { when(templateParser.mergeTemplateIntoString(matches(PASSWORD_CHANGE_REMINDER_TEMPLATE), eq(params))) .thenReturn(EMAIL_MESSAGE); emailSender.sendPasswordResetReminder(user, expirationDate); <START> verify(templateParser, times(1)) <END> .mergeTemplateIntoString(matches(PASSWORD_CHANGE_REMINDER_TEMPLATE), eq(params)); verify(eventRelay, times(1)).sendEventMessage(eq(event)); }</code><technical_language>drop times(1) , default</technical_language>

Target:
public void shouldSendPasswordResetReminder() throws Exception { when(templateParser.mergeTemplateIntoString(matches(PASSWORD_CHANGE_REMINDER_TEMPLATE), eq(params))) .thenReturn(EMAIL_MESSAGE); emailSender.sendPasswordResetReminder(params); verify(templateParser).mergeTemplateIntoString(matches(PASSWORD_CHANGE_REMINDER_TEMPLATE), eq(params)); verify(eventRelay).sendEventMessage(eq(event)); }
Source:
<code>public void testCompleteTransactionRejected(boolean isCommit) { final Rejected outcome = new Rejected(); final AmqpTransaction transaction = new AmqpTransaction(ByteBuffer.wrap("1".getBytes())); TransactionCoordinator transactionCoordinator = new TransactionCoordinator(sendLink, messageSerializer); <START> doReturn(Mono.just(outcome)).when(sendLink).send(any(byte[].class), anyInt(), anyInt(), isNull()); <END> StepVerifier.create(transactionCoordinator.completeTransaction(transaction, isCommit)) .verifyError(IllegalArgumentException.class); verify(sendLink, times(1)).send(any(byte[].class), anyInt(), eq(DeliveryImpl.DEFAULT_MESSAGE_FORMAT), isNull()); }</code><technical_language>Scope returns for mocks</technical_language>

Target:
public void testCompleteTransactionRejected(boolean isCommit) { final Rejected outcome = new Rejected(); final AmqpTransaction transaction = new AmqpTransaction(ByteBuffer.wrap("1".getBytes())); TransactionCoordinator transactionCoordinator = new TransactionCoordinator(sendLink, messageSerializer); doReturn(Mono.just(outcome)).when(sendLink).send(any(byte[].class), anyInt(), eq(DeliveryImpl.DEFAULT_MESSAGE_FORMAT), isNull()); StepVerifier.create(transactionCoordinator.completeTransaction(transaction, isCommit)) .verifyError(IllegalArgumentException.class); verify(sendLink, times(1)).send(any(byte[].class), anyInt(), eq(DeliveryImpl.DEFAULT_MESSAGE_FORMAT), isNull()); }
Source:
<code>public Stream(int column, StreamKind streamKind, int length, boolean useVInts, int sequence, Optional<Long> offset) { this.column = column; this.streamKind = requireNonNull(streamKind, "streamKind is null"); this.length = length; this.useVInts = useVInts; this.sequence = sequence; <START> this.offset = offset; <END> }</code><technical_language>requireNonNull</technical_language>

Target:
public Stream(int column, StreamKind streamKind, int length, boolean useVInts, int sequence, Optional<Long> offset) { this.column = column; this.streamKind = requireNonNull(streamKind, "streamKind is null"); this.length = length; this.useVInts = useVInts; this.sequence = sequence; this.offset = requireNonNull(offset, "offset is null"); }
Source:
<code>public boolean merge(DBObject oldDoc,DBObject newDoc) { boolean ret=false; try { LOGGER.debug("Merge start"); DocComparator.Difference<Object> diff=compareNodes(oldDoc,newDoc); LOGGER.debug("Diff:{}"+diff); for(DocComparator.Delta<Object> delta:diff.getDelta()) { if(delta instanceof DocComparator.Removal) { DocComparator.Removal<Object> removal=(DocComparator.Removal<Object>)delta; Path removedField=removal.getField1(); boolean hidden=true; int numSegments=removedField.numSegments(); if(numSegments>1&&removedField.isIndex(numSegments-1)) { hidden=false; } if(hidden) { try { <START> if (!removedField.equals(Translator.HIDDEN_SUB_PATH)) { <END> md.resolve(removedField); hidden=false; } else { hidden = true; } } catch (Exception e) { hidden=true; } if(hidden) { LOGGER.debug("Field is hidden but removed, adding it back",removedField); addField(newDoc,diff.getDelta(),removal); ret=true; } } } } } catch (Exception e) { throw new RuntimeException(e); } return ret; }</code><technical_language>removedField is a path, check if HIDDEN_SUB_PATH is of segments, equals work</technical_language>

Target:
public boolean merge(DBObject oldDoc,DBObject newDoc) { boolean ret=false; try { LOGGER.debug("Merge start"); DocComparator.Difference<Object> diff=compareNodes(oldDoc,newDoc); LOGGER.debug("Diff:{}"+diff); for(DocComparator.Delta<Object> delta:diff.getDelta()) { if(delta instanceof DocComparator.Removal) { DocComparator.Removal<Object> removal=(DocComparator.Removal<Object>)delta; Path removedField=removal.getField1(); boolean hidden=true; int numSegments=removedField.numSegments(); if(numSegments>1&&removedField.isIndex(numSegments-1)) { hidden=false; } if(hidden) { try { if (!hasHiddenField(removedField)) { md.resolve(removedField); hidden=false; } else { hidden = true; } } catch (Exception e) { hidden=true; } if(hidden) { LOGGER.debug("Field is hidden but removed, adding it back",removedField); addField(newDoc,diff.getDelta(),removal); ret=true; } } } } } catch (Exception e) { throw new RuntimeException(e); } return ret; }
Source:
<code>public void start(long checkpointId, CheckpointOptions checkpointOptions) { results.keySet().forEach(oldCheckpointId -> abort(oldCheckpointId, new Exception("Starting new checkpoint " + checkpointId))); LOG.debug("{} starting checkpoint ({})", taskName, checkpointId, checkpointOptions); ChannelStateWriteResult result = new ChannelStateWriteResult(); ChannelStateWriteResult put = results.computeIfAbsent(checkpointId, id -> { <START> Preconditions.checkState(results.size() < maxCheckpoints, String.format("can't start %d, results.size() > maxCheckpoints: %d, %d, %s", checkpointId, results.size(), maxCheckpoints, taskName)); <END> enqueue(new CheckpointStartRequest(checkpointId, result, checkpointOptions.getTargetLocation()), false); return result; }); Preconditions.checkArgument(put == result, "result future already present for checkpoint " + checkpointId + ", " + taskName); }</code><technical_language>nit: add task name front, nice %d > %d for comparison values</technical_language>

Target:
public void start(long checkpointId, CheckpointOptions checkpointOptions) { LOG.debug("{} starting checkpoint ({})", taskName, checkpointId, checkpointOptions); ChannelStateWriteResult result = new ChannelStateWriteResult(); ChannelStateWriteResult put = results.computeIfAbsent(checkpointId, id -> { Preconditions.checkState(results.size() < maxCheckpoints, String.format("%s can't start %d, results.size() > maxCheckpoints: %d > %d", taskName, checkpointId, results.size(), maxCheckpoints)); enqueue(new CheckpointStartRequest(checkpointId, result, checkpointOptions.getTargetLocation()), false); return result; }); Preconditions.checkArgument(put == result, taskName + " result future already present for checkpoint " + checkpointId); }
Source:
<code>private static String unescape(String s) throws URISyntaxException { if (s == null) return null; if (s.indexOf('%') < 0) return s; byte[] bytes; try { bytes = s.getBytes(Constants.CHARACTER_ENCODING); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } byte[] os = new byte[bytes.length]; int j = 0; for (int i = 0; i < bytes.length; ++i) { byte c = bytes[i]; if (c == '%') { <START> if (i + 2 > bytes.length) <END> throw new URISyntaxException(s, JGitText.get().cannotParseGitURIish); int val = (RawParseUtils.parseHexInt4(bytes[i + 1]) << 4) | RawParseUtils.parseHexInt4(bytes[i + 2]); os[j++] = (byte) val; i += 2; } else os[j++] = c; } return RawParseUtils.decode(os, 0, j); }</code><technical_language>=</technical_language>

Target:
private static String unescape(String s) throws URISyntaxException { if (s == null) return null; if (s.indexOf('%') < 0) return s; byte[] bytes; try { bytes = s.getBytes(Constants.CHARACTER_ENCODING); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } byte[] os = new byte[bytes.length]; int j = 0; for (int i = 0; i < bytes.length; ++i) { byte c = bytes[i]; if (c == '%') { if (i + 2 >= bytes.length) throw new URISyntaxException(s, JGitText.get().cannotParseGitURIish); int val = (RawParseUtils.parseHexInt4(bytes[i + 1]) << 4) | RawParseUtils.parseHexInt4(bytes[i + 2]); os[j++] = (byte) val; i += 2; } else os[j++] = c; } return RawParseUtils.decode(os, 0, j); }
Source:
<code>public Map<String, String> getSortedRecipientList(String feedbackQuestionId) { List<Map.Entry<String, String>> sortedList = new ArrayList<>(this.recipientList <START> .get(feedbackQuestionId).entrySet()); <END> Collections.sort(sortedList, new Comparator<Map.Entry<String, String>>() { @Override public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) { int compare = o1.getValue().compareTo(o2.getValue()); return compare == 0 ? o1.getKey().compareTo(o2.getKey()) : compare; } }); Map<String, String> result = new LinkedHashMap<>(); for (Map.Entry<String, String> entry : sortedList) { result.put(entry.getKey(), entry.getValue()); } return result; }</code><technical_language>This collapsed a single line</technical_language>

Target:
public Map<String, String> getSortedRecipientList(String feedbackQuestionId) { List<Map.Entry<String, String>> sortedList = new ArrayList<>(recipientList.get(feedbackQuestionId).entrySet()); Collections.sort(sortedList, new Comparator<Map.Entry<String, String>>() { @Override public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) { int compare = o1.getValue().compareTo(o2.getValue()); return compare == 0 ? o1.getKey().compareTo(o2.getKey()) : compare; } }); Map<String, String> result = new LinkedHashMap<>(); for (Map.Entry<String, String> entry : sortedList) { result.put(entry.getKey(), entry.getValue()); } return result; }
Source:
<code>public void testOpenLedgerNoRecovery() throws Exception { LedgerMetadata ledgerMetadata = generateLedgerMetadata(ensembleSize, writeQuorumSize, ackQuorumSize, password, customMetadata); registerMockLedgerMetadata(ledgerId, ledgerMetadata); ledgerMetadata.getEnsembles().values().forEach(bookieAddressList -> { bookieAddressList.forEach(bookieAddress -> { try { <START> registerMockEntryForRead(ledgerId, BookieProtocol.LAST_ADD_CONFIRMED, bookieAddress, entryData, -1); <END> registerMockEntryForRead(ledgerId, 0, bookieAddress, entryData, -1); } catch (BKException bke) { fail("Add entry fail for in testOpenLedgerNoRecovery"); } }); }); result(newOpenLedgerOp() .withPassword(ledgerMetadata.getPassword()) .withDigestType(DigestType.CRC32) .withLedgerId(ledgerId) .withRecovery(false) .execute()); }</code><technical_language>thing: registerMockEntryForRead throw a BKException? throw a cchecked exception? resort ise @SneakyThrows</technical_language>

Target:
public void testOpenLedgerNoRecovery() throws Exception { LedgerMetadata ledgerMetadata = generateLedgerMetadata(ensembleSize, writeQuorumSize, ackQuorumSize, password, customMetadata); registerMockLedgerMetadata(ledgerId, ledgerMetadata); ledgerMetadata.getEnsembles().values().forEach(bookieAddressList -> { bookieAddressList.forEach(bookieAddress -> { registerMockEntryForRead(ledgerId, BookieProtocol.LAST_ADD_CONFIRMED, bookieAddress, entryData, -1); registerMockEntryForRead(ledgerId, 0, bookieAddress, entryData, -1); }); }); result(newOpenLedgerOp() .withPassword(ledgerMetadata.getPassword()) .withDigestType(DigestType.CRC32) .withLedgerId(ledgerId) .withRecovery(false) .execute()); }
Source:
<code>public void shouldFetchModificationsWithMaterial() { MaterialRevisions materialRevisions = new MaterialRevisions(); SvnMaterial material = MaterialsMother.svnMaterial("http://username:password@localhost"); <START> List<Modification> modificationList = getModifications(1); <END> materialRevisions.addRevision(material, modificationList); dbHelper.saveRevs(materialRevisions); Modification expectedModification = modificationList.get(0); List<Modification> modifications = repo.getModificationWithMaterial(); assertThat(modifications.size(), is(1)); Modification modification = modifications.get(0); assertModificationEqual(expectedModification, modification); MaterialInstance instance = modification.getMaterialInstance(); assertThat(instance, instanceOf(SvnMaterialInstance.class)); assertThat(instance.getFingerprint(), is(material.getFingerprint())); assertThat(instance.getUrl(), is(material.getUrl())); assertThat(instance.getUsername(), is(material.getUserName())); assertThat(instance.getBranch(), isEmptyOrNullString()); assertThat(instance.getCheckExternals(), is(material.isCheckExternals())); }</code><technical_language>testing behavior of fetching latest modification, setup ensure more 1 modification for a material</technical_language>

Target:
public void shouldFetchModificationsWithMaterial() { MaterialRevisions materialRevisions = new MaterialRevisions(); SvnMaterial material = MaterialsMother.svnMaterial("http://username:password@localhost"); List<Modification> modificationList = getModifications(2); materialRevisions.addRevision(material, modificationList); dbHelper.saveRevs(materialRevisions); Modification expectedModification = modificationList.get(0); List<Modification> modifications = repo.getLatestModificationForEachMaterial(); assertThat(modifications.size(), is(1)); Modification modification = modifications.get(0); assertModificationEqual(expectedModification, modification); MaterialInstance instance = modification.getMaterialInstance(); assertThat(instance, instanceOf(SvnMaterialInstance.class)); assertThat(instance.getFingerprint(), is(material.getFingerprint())); assertThat(instance.getUrl(), is(material.getUrl())); assertThat(instance.getUsername(), is(material.getUserName())); assertThat(instance.getBranch(), isEmptyOrNullString()); assertThat(instance.getCheckExternals(), is(material.isCheckExternals())); }
Source:
<code>private <T> QueryRunner<T> buildAndDecorateQueryRunner( final QueryRunnerFactory<T, Query<T>> factory, final QueryToolChest<T, Query<T>> toolChest, final ReferenceCountingSegment adapter, final QuerySegmentSpec segmentSpec ) { <START> adapter.increment(); <END> return new SpecificSegmentQueryRunner<T>( new MetricsEmittingQueryRunner<T>( emitter, new Function<Query<T>, ServiceMetricEvent.Builder>() { @Override public ServiceMetricEvent.Builder apply(@Nullable final Query<T> input) { return toolChest.makeMetricBuilder(input); } }, new BySegmentQueryRunner<T>( adapter.getIdentifier(), adapter.getDataInterval().getStart(), new QueryRunner<T>() { @Override public Sequence<T> run(final Query<T> query) { return new ReferenceCountingSequence<T>(factory.createRunner(adapter).run(query), adapter); } } ) ).withWaitMeasuredFromNow(), segmentSpec ); }</code><technical_language>So, technically, is for a Sequence get more once. Meaning this setup, get multiple decrement()s for a single increment(). multiple times right now, I safe. In order safe, though, do increment Sequence.toYielder() call instead of here. This ends introducing a delay in actual incremental happens, is unfortunate, I end of world. I move increment toYielder() method of ReferenceCountingSequence<>, need ReferenceCountingSegment thread-safe aware of closed. is closed, reject increment() calls (let's return a boolean set false is closed, meaning is safe instance) return null for of other methods rely underlying buffers</technical_language>

Target:
private <T> QueryRunner<T> buildAndDecorateQueryRunner( final QueryRunnerFactory<T, Query<T>> factory, final QueryToolChest<T, Query<T>> toolChest, final ReferenceCountingSegment adapter, final QuerySegmentSpec segmentSpec ) { return new SpecificSegmentQueryRunner<T>( new MetricsEmittingQueryRunner<T>( emitter, new Function<Query<T>, ServiceMetricEvent.Builder>() { @Override public ServiceMetricEvent.Builder apply(@Nullable final Query<T> input) { return toolChest.makeMetricBuilder(input); } }, new BySegmentQueryRunner<T>( adapter.getIdentifier(), adapter.getDataInterval().getStart(), new QueryRunner<T>() { @Override public Sequence<T> run(final Query<T> query) { return new ReferenceCountingSequence<T>(factory.createRunner(adapter).run(query), adapter); } } ) ).withWaitMeasuredFromNow(), segmentSpec ); }
Source:
<code>public LogSource getLogSourceFromVmArgs() { int agentPathStart = vmArgs.indexOf("-agentpath") + "-agentpath".length(); int agentPathEnd = vmArgs.indexOf(' ', agentPathStart); String agentPath = vmArgs.substring(agentPathStart, agentPathEnd); int logPathStart = agentPath.indexOf("logPath=") + "logPath=".length(); int commaPos = agentPath.indexOf(",", logPathStart); int spacePos = agentPath.indexOf(' ', logPathStart); int logPathEnd = commaPos > 0 ? commaPos : (spacePos > 0 ? spacePos : agentPath.length()); return new FileLogSource(new File(agentPath.substring(logPathStart, logPathEnd))); <START> } <END></code><technical_language>I this part problem hp-gui attach a running jvm correctly. - jvm -agentpath vmArgs ArrayIndexOutOfBoundsException java -agentpath:/Users/han-pc/IdeaProjects/honest-profiler/build/liblagent.dylib=interval=100 -cp classes InfiniteExample - jvm defined custom logPath java -agentpath:/Users/han-pc/IdeaProjects/honest-profiler/build/liblagent.dylib=interval=100 -cp classes -Dwhatever=Y InfiniteExample - jvm define logPath relativePath, running folder hp-gui java -agentpath:/Users/han-pc/IdeaProjects/honest-profiler/build/liblagent.dylib=interval=100,logPath=tmp.hpl -cp classes -Dwhatever=Y InfiniteExample</technical_language>

Target:
public LogSource getLogSourceFromVmArgs() throws CantReadFromSourceException { if (vmArgs.indexOf(OPT_AGENT) < 0) { return getLogSource(); } int agentPathStart = vmArgs.indexOf(OPT_AGENT) + OPT_AGENT.length(); int agentPathEnd = vmArgs.indexOf(' ', agentPathStart); agentPathEnd = (agentPathEnd < 0) ? vmArgs.length() : agentPathEnd; String agentPath = vmArgs.substring(agentPathStart, agentPathEnd); if (agentPath.indexOf(OPT_LOG) < 0) { return getLogSource(); } int logPathStart = agentPath.indexOf(OPT_LOG) + OPT_LOG.length(); int commaPos = agentPath.indexOf(",", logPathStart); int spacePos = agentPath.indexOf(' ', logPathStart); int logPathEnd = commaPos > 0 ? commaPos : (spacePos > 0 ? spacePos : agentPath.length()); File result = new File(agentPath.substring(logPathStart, logPathEnd)); return result.exists() ? new FileLogSource(result) : getLogSource(); }
Source:
<code>public Map<String, Map<String, String>> getCatalogSessionProperties() { ImmutableMap.Builder<String, Map<String, String>> catalogSessionProperties = ImmutableMap.builder(); <START> session.getConnectorProperties().forEach((key, value) -> catalogSessionProperties.put(key.getCatalogName(), value)); <END> return catalogSessionProperties.build(); }</code><technical_language>This special (such transform) calling forEach, write a normal for-each loop</technical_language>

Target:
public Map<String, Map<String, String>> getCatalogSessionProperties() { ImmutableMap.Builder<String, Map<String, String>> catalogSessionProperties = ImmutableMap.builder(); for (Entry<ConnectorId, Map<String, String>> entry : session.getConnectorProperties().entrySet()) { catalogSessionProperties.put(entry.getKey().getCatalogName(), entry.getValue()); } return catalogSessionProperties.build(); }
Source:
<code>private void waitUntilReady(String vmName) { boolean ready = retry(new Predicate<String>() { @Override public boolean apply(String name) { return !api().get(name).properties().provisioningState().equals(VirtualMachineProperties.ProvisioningState.CREATING); } }, 60 * 20 * 1000).apply(vmName); <START> assertTrue(ready, "createOrUpdateVault operation did not complete in the configured timeout"); <END> VirtualMachineProperties.ProvisioningState status = api().get(vmName).properties().provisioningState(); assertThat(status).isNotEqualTo(VirtualMachineProperties.ProvisioningState.CREATING); assertThat(status).isNotEqualTo(VirtualMachineProperties.ProvisioningState.FAILED); }</code><technical_language>I createOrUpdate more approriate</technical_language>

Target:
private void waitUntilReady(String vmName) { boolean ready = retry(new Predicate<String>() { @Override public boolean apply(String name) { return !api().get(name).properties().provisioningState().equals(VirtualMachineProperties.ProvisioningState.CREATING); } }, 60 * 20 * 1000).apply(vmName); assertTrue(ready, "createOrUpdate operation did not complete in the configured timeout"); VirtualMachineProperties.ProvisioningState status = api().get(vmName).properties().provisioningState(); assertThat(status).isNotEqualTo(VirtualMachineProperties.ProvisioningState.CREATING); assertThat(status).isNotEqualTo(VirtualMachineProperties.ProvisioningState.FAILED); }
Source:
<code>public Date getStartDate() { if (null == dataFile) { return null; } LocalDateTime date = dataFile.getStartDate(); if (null == date) { return null; } return Date.from(date.atZone(ZoneId.of("UTC")).toInstant()); <START> } <END></code><technical_language>return statement</technical_language>

Target:
public Date getStartDate() { Date date = null; if (null != dataFile) { LocalDateTime localDate = dataFile.getStartDate(); if (null != localDate) { date = Date.from(localDate.atZone(ZoneId.of("UTC")).toInstant()); } } return date; }
Source:
<code>public void testCancel() { Capture<Request> capturedRequest = EasyMock.newCapture(); ListenableFuture<Object> cancelledFuture = Futures.immediateCancelledFuture(); SettableFuture<Object> cancellationFuture = SettableFuture.create(); EasyMock.expect( httpClient.go( EasyMock.capture(capturedRequest), EasyMock.<HttpResponseHandler>anyObject(), EasyMock.anyObject(Duration.class) ) ) .andReturn(cancelledFuture) .once(); <START> <END> EasyMock.replay(httpClient); TimeBoundaryQuery query = Druids.newTimeBoundaryQueryBuilder().dataSource("test").build(); query = query.withOverriddenContext(ImmutableMap.of(DirectDruidClient.QUERY_FAIL_TIME, Long.MAX_VALUE)); cancellationFuture.set(new StatusResponseHolder(HttpResponseStatus.OK, new StringBuilder("cancelled"))); Sequence results = client.run(QueryPlus.wrap(query)); Assert.assertEquals(HttpMethod.POST, capturedRequest.getValue().getMethod()); Assert.assertEquals(1, client.getNumOpenConnections()); QueryInterruptedException exception = null; try { results.toList(); } catch (QueryInterruptedException e) { exception = e; } Assert.assertNotNull(exception); EasyMock.verify(httpClient); }</code><technical_language>this removed</technical_language>

Target:
public void testCancel() { Capture<Request> capturedRequest = EasyMock.newCapture(); ListenableFuture<Object> cancelledFuture = Futures.immediateCancelledFuture(); SettableFuture<Object> cancellationFuture = SettableFuture.create(); EasyMock.expect( httpClient.go( EasyMock.capture(capturedRequest), EasyMock.<HttpResponseHandler>anyObject(), EasyMock.anyObject(Duration.class) ) ) .andReturn(cancelledFuture) .once(); EasyMock.expect( httpClient.go( EasyMock.capture(capturedRequest), EasyMock.<HttpResponseHandler>anyObject(), EasyMock.anyObject(Duration.class) ) ) .andReturn(cancellationFuture) .anyTimes(); EasyMock.replay(httpClient); TimeBoundaryQuery query = Druids.newTimeBoundaryQueryBuilder().dataSource("test").build(); query = query.withOverriddenContext(ImmutableMap.of(DirectDruidClient.QUERY_FAIL_TIME, Long.MAX_VALUE)); cancellationFuture.set(new StatusResponseHolder(HttpResponseStatus.OK, new StringBuilder("cancelled"))); Sequence results = client.run(QueryPlus.wrap(query)); Assert.assertEquals(HttpMethod.POST, capturedRequest.getValue().getMethod()); Assert.assertEquals(0, client.getNumOpenConnections()); QueryInterruptedException exception = null; try { results.toList(); } catch (QueryInterruptedException e) { exception = e; } Assert.assertNotNull(exception); EasyMock.verify(httpClient); }
Source:
<code>public List<AttributeStatement> createEvidenceStatements(final List accessConstentValues, final List evidenceInstanceAccessConsentValues, final String namespace) { List<AttributeStatement> statements = new ArrayList<>(); final List<Attribute> attributes = new ArrayList<>(); if (accessConstentValues != null) { <START> attributes.add(createAttribute(null, "AccessConsentPolicy", namespace, accessConstentValues)); <END> } if (evidenceInstanceAccessConsentValues != null) { attributes.add(createAttribute(null, "InstanceAccessConsentPolicy", namespace, evidenceInstanceAccessConsentValues)); } if (!attributes.isEmpty()) { statements = createAttributeStatement(attributes); } return statements; }</code><technical_language>Consider move constant variable SAMLConstant</technical_language>

Target:
public List<AttributeStatement> createEvidenceStatements(final List accessConstentValues, final List evidenceInstanceAccessConsentValues, final String namespace) { List<AttributeStatement> statements = new ArrayList<>(); final List<Attribute> attributes = new ArrayList<>(); if (accessConstentValues != null) { attributes.add(createAttribute(null, NhincConstants.ACCESS_CONSENT_ATTR, namespace, accessConstentValues)); } if (evidenceInstanceAccessConsentValues != null) { attributes.add(createAttribute(null, NhincConstants.INST_ACCESS_CONSENT_ATTR, namespace, evidenceInstanceAccessConsentValues)); } if (!attributes.isEmpty()) { statements = createAttributeStatement(attributes); } return statements; }
Source:
<code>private static SerializationDelegate getSerializationDelegate(Map<String, Object> topoConf) { String delegateClassName = (String) topoConf.get(Config.STORM_META_SERIALIZATION_DELEGATE); SerializationDelegate delegate; try { Class delegateClass = Class.forName(delegateClassName); delegate = (SerializationDelegate) delegateClass.newInstance(); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { <START> LOG.error("Failed to construct serialization delegate, falling back to default", e); <END> delegate = new GzipThriftSerializationDelegate(); } delegate.prepare(topoConf); return delegate; }</code><technical_language>+1 I OK failing crash users set class incorrectly</technical_language>

Target:
private static SerializationDelegate getSerializationDelegate(Map<String, Object> topoConf) { String delegateClassName = (String) topoConf.get(Config.STORM_META_SERIALIZATION_DELEGATE); SerializationDelegate delegate; try { Class delegateClass = Class.forName(delegateClassName); delegate = (SerializationDelegate) delegateClass.newInstance(); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { throw new RuntimeException("Failed to construct serialization delegate class " + delegateClassName, e); } delegate.prepare(topoConf); return delegate; }
Source:
<code>public void setBusyNode(final String nodeUrl, Client owner) throws NotConnectedException { final RMNode rmNode = this.allNodes.get(nodeUrl); if (rmNode == null) { logger.error("Unknown node " + nodeUrl); return; } <START> if ((!clients.containsKey(owner.getId()) && owner != localClient)) { <END> logger.warn(nodeUrl + " cannot set busy as the client disconnected " + owner); throw new NotConnectedException("Client " + owner + " is not connected to the resource manager"); } if (rmNode.isBusy()) { return; } final NodeState previousNodeState = rmNode.getState(); rmNode.setBusy(owner); this.eligibleNodes.remove(rmNode); persistUpdatedRMNodeIfRecoveryEnabled(rmNode); this.registerAndEmitNodeEvent(rmNode.createNodeEvent(RMEventType.NODE_STATE_CHANGED, previousNodeState, owner.getName())); }</code><technical_language>is extra parenthesis nest. I agree for adding this condition</technical_language>

Target:
public void setBusyNode(final String nodeUrl, Client owner) throws NotConnectedException { final RMNode rmNode = this.allNodes.get(nodeUrl); if (rmNode == null) { logger.error("Unknown node " + nodeUrl); return; } if (!clients.containsKey(owner.getId()) && owner != localClient) { logger.warn(nodeUrl + " cannot set busy as the client disconnected " + owner); throw new NotConnectedException("Client " + owner + " is not connected to the resource manager"); } if (rmNode.isBusy()) { return; } final NodeState previousNodeState = rmNode.getState(); rmNode.setBusy(owner); this.eligibleNodes.remove(rmNode); persistUpdatedRMNodeIfRecoveryEnabled(rmNode); this.registerAndEmitNodeEvent(rmNode.createNodeEvent(RMEventType.NODE_STATE_CHANGED, previousNodeState, owner.getName())); }
Source:
<code>protected ProjectState(final AnonymousUser anonymousUser, final ProjectCache projectCache, @WildProjectName final Project.NameKey wildProject, final ProjectControl.AssistedFactory projectControlFactory, @Assisted final Project project, @Assisted Collection<RefRight> rights) { this.anonymousUser = anonymousUser; this.projectCache = projectCache; this.wildProject = wildProject; this.projectControlFactory = projectControlFactory; if (wildProject.equals(project.getNameKey())) { rights = new ArrayList<RefRight>(rights); for (Iterator<RefRight> itr = rights.iterator(); itr.hasNext();) { if (!itr.next().getApprovalCategoryId().canBeOnWildProject()) { itr.remove(); } } rights = Collections.unmodifiableCollection(rights); } this.project = project; this.localRights = rights; final HashSet<AccountGroup.Id> groups = new HashSet<AccountGroup.Id>(); for (final RefRight right : rights) { if (ApprovalCategory.OWN.equals(right.getApprovalCategoryId()) <START> && right.getMaxValue() > 0) { <END> groups.add(right.getAccountGroupId()); } } localOwners = Collections.unmodifiableSet(groups); }</code><technical_language>below, I if this filtering pattern for refs/*</technical_language>

Target:
protected ProjectState(final AnonymousUser anonymousUser, final ProjectCache projectCache, @WildProjectName final Project.NameKey wildProject, final ProjectControl.AssistedFactory projectControlFactory, @Assisted final Project project, @Assisted Collection<RefRight> rights) { this.anonymousUser = anonymousUser; this.projectCache = projectCache; this.wildProject = wildProject; this.projectControlFactory = projectControlFactory; if (wildProject.equals(project.getNameKey())) { rights = new ArrayList<RefRight>(rights); for (Iterator<RefRight> itr = rights.iterator(); itr.hasNext();) { if (!itr.next().getApprovalCategoryId().canBeOnWildProject()) { itr.remove(); } } rights = Collections.unmodifiableCollection(rights); } this.project = project; this.localRights = rights; final HashSet<AccountGroup.Id> groups = new HashSet<AccountGroup.Id>(); for (final RefRight right : rights) { if (ApprovalCategory.OWN.equals(right.getApprovalCategoryId()) && right.getMaxValue() > 0 && right.getRefPattern().equals(RefRight.ALL)) { groups.add(right.getAccountGroupId()); } } localOwners = Collections.unmodifiableSet(groups); }
Source:
<code>public void createServiceDuplicate() throws Exception { final CommonTestUtilities.TestingPostgres testingPostgres = getTestingPostgres(); CommonTestUtilities.cleanStatePrivate2(SUPPORT, false); final ApiClient webClient = getWebClient("admin@admin.com"); WorkflowsApi client = new WorkflowsApi(webClient); String serviceRepo = "DockstoreTestUser2/test-service"; String installationId = "1179416"; io.swagger.client.model.Workflow service = client.addService(serviceRepo, "admin@admin.com", installationId); assertNotNull(service); try { client.addService(serviceRepo, "admin@admin.com", installationId); } catch (ApiException ex) { <START> assertEquals("Should have error code 418", 418, ex.getCode()); <END> } final long count = testingPostgres .runSelectStatement("select count(*) from service where sourcecontrol = 'github.com' and organization = 'DockstoreTestUser2' and repository = 'test-service'", new ScalarHandler<>()); Assert.assertEquals("there should be one matching service", 1, count); }</code><technical_language>a constant in common akin <LINK_0> track this custom http code</technical_language>

Target:
public void createServiceDuplicate() throws Exception { final CommonTestUtilities.TestingPostgres testingPostgres = getTestingPostgres(); CommonTestUtilities.cleanStatePrivate2(SUPPORT, false); final ApiClient webClient = getWebClient("admin@admin.com"); WorkflowsApi client = new WorkflowsApi(webClient); String serviceRepo = "DockstoreTestUser2/test-service"; String installationId = "1179416"; io.swagger.client.model.Workflow service = client.addService(serviceRepo, "admin@admin.com", installationId); assertNotNull(service); try { client.addService(serviceRepo, "admin@admin.com", installationId); } catch (ApiException ex) { assertEquals("Should have error code 418", LAMBDA_FAILURE, ex.getCode()); } final long count = testingPostgres .runSelectStatement("select count(*) from service where sourcecontrol = 'github.com' and organization = 'DockstoreTestUser2' and repository = 'test-service'", new ScalarHandler<>()); Assert.assertEquals("there should be one matching service", 1, count); }
Source:
<code>public BackendRequest<?> visitFlushWork(FlushLuceneWork work, IndexingMonitor monitor) { Flush flush = new Flush.Builder().addIndex( indexName ).refresh( true ).build(); return new BackendRequest<>( flush, work, indexName, monitor, NoopBackendRequestSuccessHandler.INSTANCE, <START> refreshAfterWrite <END> ); }</code><technical_language>If force a refresh flushing (.refresh( true ) above), refreshAfterWrite simply false. refreshes: performing flush, other in org.hibernate.search.elasticsearch.client.impl.BackendRequestProcessor.RequestProcessingRunnable.processAsyncWork()</technical_language>

Target:
public BackendRequest<?> visitFlushWork(FlushLuceneWork work, IndexingMonitor monitor) { Flush flush = new Flush.Builder().setParameter( "wait_if_ongoing", "true" ) .addIndex( indexName ) .refresh( true ) .build(); return new BackendRequest<>( flush, work, indexName, monitor, NoopBackendRequestSuccessHandler.INSTANCE, false ); }
Source:
<code>public RoomInfoPage doubleClickOverRoomName(String displayName) { <START> UI.doubleClick(driver.findElement(By.xpath(" END> return new RoomInfoPage(); }</code><technical_language>please apply java conventions (spaces +) total amount of characters line</technical_language>

Target:
public RoomInfoPage doubleClickOverRoomName(String displayName) { UI.doubleClick(driver.findElement(By.xpath(" + displayName + "')and@class='ng-binding']"))); return new RoomInfoPage(); }
Source:
<code>public ParamertizedString(final String pattern) { final StringBuilder raw = new StringBuilder(); final List<Parameter> prs = new ArrayList<Parameter>(4); final List<Format> ops = new ArrayList<Format>(4); final List<Function> functions = new ArrayList<Function>(); int i = 0; while (i < pattern.length()) { final int b = pattern.indexOf("${", i); if (b < 0) { break; } final int e = pattern.indexOf("}", b + 2); if (e < 0) { break; } raw.append(pattern.substring(i, b)); ops.add(new Constant(pattern.substring(i, b))); String expr = pattern.substring(b + 2, e); int lastDot = expr.lastIndexOf('.'); <START> while (lastDot > 0) { <END> Function function; function = FUNCTIONS.get(expr.substring(lastDot + 1)); if (function == null) { function = NOOP; } functions.add(function); expr = expr.substring(0, lastDot); lastDot = expr.lastIndexOf('.'); } functions.add(NOOP); final Parameter p = new Parameter(expr, Collections.unmodifiableList(functions)); raw.append("{" + prs.size() + "}"); prs.add(p); ops.add(p); i = e + 1; } if (i < pattern.length()) { raw.append(pattern.substring(i)); ops.add(new Constant(pattern.substring(i))); } this.pattern = pattern; this.rawPattern = raw.toString(); this.patternOps = Collections.unmodifiableList(ops); this.parameters = Collections.unmodifiableList(prs); }</code><technical_language>I this loop if split()</technical_language>

Target:
public ParamertizedString(final String pattern) { final StringBuilder raw = new StringBuilder(); final List<Parameter> prs = new ArrayList<Parameter>(4); final List<Format> ops = new ArrayList<Format>(4); final List<Function> functions = new ArrayList<Function>(); int i = 0; while (i < pattern.length()) { final int b = pattern.indexOf("${", i); if (b < 0) { break; } final int e = pattern.indexOf("}", b + 2); if (e < 0) { break; } raw.append(pattern.substring(i, b)); ops.add(new Constant(pattern.substring(i, b))); String expr = pattern.substring(b + 2, e); String parameterName = ""; if (!expr.contains(".")) { parameterName = expr; } else { int firstDot = expr.indexOf('.'); parameterName = expr.substring(0, firstDot); String actionsStr = expr.substring(firstDot + 1); String[] actions = actionsStr.split("\\."); for (String action : actions) { Function function = FUNCTIONS.get(action); if (function == null) { function = NOOP; } functions.add(function); } } functions.add(NOOP); final Parameter p = new Parameter(parameterName, Collections.unmodifiableList(functions)); raw.append("{" + prs.size() + "}"); prs.add(p); ops.add(p); i = e + 1; } if (i < pattern.length()) { raw.append(pattern.substring(i)); ops.add(new Constant(pattern.substring(i))); } this.pattern = pattern; this.rawPattern = raw.toString(); this.patternOps = Collections.unmodifiableList(ops); this.parameters = Collections.unmodifiableList(prs); }
Source:
<code>public String acquireLease(int leaseTimeInSec, String leaseId) { try { String id = leaseBlob.acquireLease(leaseTimeInSec, leaseId); LOG.info("Acquired lease with lease id = " + id); return id; } catch (StorageException storageException) { int httpStatusCode = storageException.getHttpStatusCode(); if (httpStatusCode == HttpStatus.CONFLICT_409) { <START> LOG.info("The blob you're trying to acquire is leased already."); <END> } else if (httpStatusCode == HttpStatus.NOT_FOUND_404) { LOG.error("The blob you're trying to lease does not exist.", storageException); throw new AzureException(storageException); } else { LOG.error("Error acquiring lease!", storageException); throw new AzureException(storageException); } } return null; }</code><technical_language>expcetion stacktrace in log statement? least, storageException.getMessage()</technical_language>

Target:
public String acquireLease(int leaseTimeInSec, String leaseId) { try { String id = leaseBlob.acquireLease(leaseTimeInSec, leaseId); LOG.info("Acquired lease with lease id = " + id); return id; } catch (StorageException storageException) { int httpStatusCode = storageException.getHttpStatusCode(); if (httpStatusCode == HttpStatus.CONFLICT_409) { LOG.info("The blob you're trying to acquire is leased already.", storageException.getMessage()); } else if (httpStatusCode == HttpStatus.NOT_FOUND_404) { LOG.error("The blob you're trying to lease does not exist.", storageException); throw new AzureException(storageException); } else { LOG.error("Error acquiring lease!", storageException); throw new AzureException(storageException); } } return null; }
Source:
<code>public static <T> MessageBuilder<T> fromMessage(Message<T> message) { Assert.notNull(message, "message must not be null"); if (message instanceof CloneableMessage) { return ((CloneableMessage<T>) message).cloneMessage(); } else { return new MessageBuilder<T>(message.getPayload(), message); <START> } <END> }</code><technical_language>this logic in DefaultMessageBuilderFactory instead</technical_language>

Target:
public static <T> MessageBuilder<T> fromMessage(Message<T> message) { Assert.notNull(message, "message must not be null"); return new MessageBuilder<T>(message.getPayload(), message); }
Source:
<code>public IgniteEx start() throws Exception { IgniteConfiguration cfg = getConfiguration(gridName); cfg.setConsistentId(gridName); DataStorageConfiguration storageCfg = new DataStorageConfiguration(); <START> storageCfg.setDataRegionConfigurations(regions.toArray(new DataRegionConfiguration[] {})); <END> cfg.setDataStorageConfiguration(storageCfg); if (dfltRegionConfiguration != null) storageCfg.setDefaultDataRegionConfiguration(dfltRegionConfiguration); cfg.setCacheConfiguration(caches.toArray(new CacheConfiguration[] {})); return startGrid(cfg); }</code><technical_language>suspicious. this way? v suggestion storageCfg.setDataRegionConfigurations(regions.toArray(newDataRegionConfiguration[regions.size()]));</technical_language>

Target:
public IgniteEx start() throws Exception { IgniteConfiguration cfg = getConfiguration(gridName); cfg.setConsistentId(gridName); DataStorageConfiguration storageCfg = new DataStorageConfiguration(); storageCfg.setDataRegionConfigurations(regions.toArray(new DataRegionConfiguration[regions.size()])); cfg.setDataStorageConfiguration(storageCfg); if (dfltRegionConfiguration != null) storageCfg.setDefaultDataRegionConfiguration(dfltRegionConfiguration); cfg.setCacheConfiguration(caches.toArray(new CacheConfiguration[caches.size()])); return startGrid(cfg); }
Source:
<code>private static void writeFromInputToOutputNewInner(InputStream is, OutputStream os, @Nullable StreamReadObserver observer) throws InputIOException, OutputIOException { byte[] buffer = new byte[8192]; long counter = 0; try { int count = readIntoBuffer(is, buffer); while (count != -1) { counter += count; if (observer != null) { observer.notifyCurrentCount(counter); } try { <START> os.write(buffer, 0, count); <END> } catch (IOException e) { throw new StreamsUtil().new OutputIOException(e); } count = readIntoBuffer(is, buffer); } } finally { closeStream(is); closeStream(os); } }</code><technical_language>Nit: this line line 143 structure, patterns handle (one externalized, internalized) odd me</technical_language>

Target:
private static void writeFromInputToOutputNewInner(InputStream is, OutputStream os, @Nullable StreamReadObserver observer) throws InputIOException, OutputIOException { byte[] buffer = new byte[8192]; long counter = 0; try { int count = readIntoBuffer(is, buffer); while (count != -1) { counter += count; if (observer != null) { observer.notifyCurrentCount(counter); } writeFromBuffer(os, buffer, count); count = readIntoBuffer(is, buffer); } } finally { closeStream(is); closeStream(os); } }
Source:
<code>public static void checkDatasetName(String namespace, String name) { Preconditions.checkNotNull(namespace, "Namespace cannot be null"); Preconditions.checkNotNull(name, "Dataset name cannot be null"); <START> Preconditions.checkArgument(Compatibility.isCompatibleName(name), <END> "Hive incompatible: Namespace %s is not alphanumeric (plus '_')", namespace); Preconditions.checkArgument(Compatibility.isCompatibleName(name), "Hive incompatible: Dataset name %s is not alphanumeric (plus '_')", name); }</code><technical_language>namespace, name</technical_language>

Target:
public static void checkDatasetName(String namespace, String name) { Preconditions.checkNotNull(namespace, "Namespace cannot be null"); Preconditions.checkNotNull(name, "Dataset name cannot be null"); Preconditions.checkArgument(Compatibility.isCompatibleName(namespace), "Hive incompatible: Namespace %s is not alphanumeric (plus '_')", namespace); Preconditions.checkArgument(Compatibility.isCompatibleName(name), "Hive incompatible: Dataset name %s is not alphanumeric (plus '_')", name); }
Source:
<code>private void fillInRepository() { <START> for (int i = 0; i < CACHE_SIZE; i++) <END> repo.save(i, new Person("person" + Integer.toHexString(i), "lastName" + Integer.toHexString((i + 16) % 256))); }</code><technical_language>Need bracers for multistring for statement</technical_language>

Target:
private void fillInRepository() { for (int i = 0; i < CACHE_SIZE; i++) { repo.save(i, new Person("person" + Integer.toHexString(i), "lastName" + Integer.toHexString((i + 16) % 256))); } }
Source:
<code>private void writeObject(ObjectOutputStream out) throws IOException { out.writeObject(myProjectSystemId); out.writeObject(myModuleName); out.writeObject(myRootDirPath); synchronized (myProxyDelegateLock) { if (myProxyDelegate == null) { myProxyDelegate = reproxy(AndroidProject.class, <START> myDelegate);; <END> } } out.writeObject(myProxyDelegate); out.writeObject(mySelectedVariantName); out.writeObject(mySelectedTestArtifactName); }</code><technical_language>double semicolon</technical_language>

Target:
private void writeObject(ObjectOutputStream out) throws IOException { out.writeObject(myProjectSystemId); out.writeObject(myModuleName); out.writeObject(myRootDirPath); synchronized (myProxyDelegateLock) { if (myProxyDelegate == null) { myProxyDelegate = reproxy(AndroidProject.class, myDelegate); } } out.writeObject(myProxyDelegate); out.writeObject(mySelectedVariantName); out.writeObject(mySelectedTestArtifactName); }
Source:
<code>public IncompleteInformationException(Variant variant) { <START> super("The variant " + variant + " has no samples data, AC and AF INFO tags"); <END> }</code><technical_language>I "nor" is more clear "and"</technical_language>

Target:
public IncompleteInformationException(Variant variant) { super("The variant " + variant + " has no allele frequencies or counts in its INFO column"); }
Source:
<code>private void encodeChainedFeatures(String attributeName, List<Feature> chainedFeatures) { key(attributeName); <START> if (!isInsideArrayAttributeName(attributeName)) jsonWriter.array(); <END> for (Feature feature : chainedFeatures) { if (feature.getType().getGeometryDescriptor() != null) { encodeFeature(feature, false); } else { jsonWriter.object(); encodeProperties(null, feature.getType(), feature.getProperties()); jsonWriter.endObject(); } } if (!isInsideArrayAttributeName(attributeName)) jsonWriter.endArray(); }</code><technical_language>I if brackets put a proper explaining means branch passed</technical_language>

Target:
private void encodeChainedFeatures(String attributeName, List<Feature> chainedFeatures) { key(attributeName); if (!isInsideArrayAttributeName(attributeName)) { jsonWriter.array(); } for (Feature feature : chainedFeatures) { if (feature.getType().getGeometryDescriptor() != null) { encodeFeature(feature, false); } else { jsonWriter.object(); encodeProperties(null, feature.getType(), feature.getProperties()); jsonWriter.endObject(); } } if (!isInsideArrayAttributeName(attributeName)) { jsonWriter.endArray(); } }