auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private static int roundKey(int point, int roundSeconds) { int d = point % roundSeconds; if (d > 0) { point += roundSeconds - d; <START> if (point == Cell.MAX_DELETION_TIME) <END> point = Cell.MAX_DELETION_TIME; else if (point < 0) return Cell.MAX_DELETION_TIME; return point; } else return point; }</code><technical_language>This ></technical_language>

Target:
private static int roundKey(int point, int roundSeconds) { int d = point % roundSeconds; if (d == 0) return point; point += roundSeconds - d; if (point > Cell.MAX_DELETION_TIME) return Cell.MAX_DELETION_TIME; else if (point < 0) return Cell.MAX_DELETION_TIME; return point; }
Source:
<code>default Multimap<CallStackDepth, ICalledFunction> queryCallStacks(Collection<CallStackDepth> collection, Collection<Long> times) { CallStackSeries callStackSeries = getCallStackSeries(); if (callStackSeries == null) <START> { return ArrayListMultimap.create(); <END> } return callStackSeries.queryCallStacks(collection, times); }</code><technical_language>nan</technical_language>

Target:
default Multimap<CallStackDepth, ISegment> queryCallStacks(Collection<CallStackDepth> collection, Collection<Long> times) { CallStackSeries callStackSeries = getCallStackSeries(); if (callStackSeries == null) { return Objects.requireNonNull(ArrayListMultimap.create()); } return callStackSeries.queryCallStacks(collection, times); }
Source:
<code>protected ToStringBuilder appendAttributes(ToStringBuilder tsb) { return super.appendAttributes(tsb) .append("url", url) .append("username", username); <START> } <END></code><technical_language>useful print it, no</technical_language>

Target:
protected ToStringBuilder appendAttributes(ToStringBuilder tsb) { return super.appendAttributes(tsb) .append("url", url) .append("username", username) .append("origintype", originType); }
Source:
<code>private List<ColumnMeta<T>> renameDomainSpecifColumns(ExtendedPagedTable<T> extendedPagedTable, Set<String> columns) { return (List<ColumnMeta<T>>) extendedPagedTable.getColumnMetaList().stream() .filter(cm -> !cm.isExtraColumn() && columns.contains(cm.getCaption())) <START> .map(colMet -> { <END> return newColumnMeta(colMet.getCaption(), true); }).collect(Collectors.toList()); }</code><technical_language>suggestion .map(colMet -> newColumnMeta(colMet.getCaption(), true))</technical_language>

Target:
private List<ColumnMeta<T>> renameDomainSpecifColumns(ExtendedPagedTable<T> extendedPagedTable, Set<String> columns) { return (List<ColumnMeta<T>>) extendedPagedTable.getColumnMetaList().stream() .filter(cm -> !cm.isExtraColumn() && columns.contains(cm.getCaption())) .map(colMet -> newColumnMeta(colMet.getCaption(), true, false) ).collect(Collectors.toList()); }
Source:
<code>public Map<String, Ref> getRefs(String prefix) throws IOException { Map<String, Ref> out; synchronized (cacheLock) { scanPackedRefs(); if (prefix.equals(ALL)) { scanLooseRefs(R_REFS, refsDir); scanRef(HEAD); } else if (prefix.startsWith(R_REFS)) { <START> String name = prefix.substring(R_REFS.length()); <END> scanLooseRefs(prefix, new File(refsDir, name)); } out = new HashMap<String, Ref>(Math.max(cache.size() * 2, 16)); for (RefHolder holder : cache.values()) { Ref ref = holder.currRef; if (ref.getName().startsWith(prefix)) { ref = resolve(ref, 0, prefix); if (ref != null && ref.getObjectId() != null) out.put(ref.getName().substring(prefix.length()), ref); } } } fireRefsChanged(); return out; }</code><technical_language>This condition is covered tests</technical_language>

Target:
public Map<String, Ref> getRefs(String prefix) throws IOException { final RefList<Ref> packed = getPackedRefs(); final RefList<LooseRef> oldLoose = looseRefs.get(); LooseScanner scan = new LooseScanner(oldLoose); scan.scan(prefix); RefList<LooseRef> loose; if (scan.newLoose != null) { loose = scan.newLoose.toRefList(); if (looseRefs.compareAndSet(oldLoose, loose)) modCnt.incrementAndGet(); } else loose = oldLoose; fireRefsChanged(); RefList.Builder<Ref> symbolic = scan.symbolic; for (int idx = 0; idx < symbolic.size();) { Ref ref = symbolic.get(idx); ref = resolve(ref, 0, prefix, loose, packed); if (ref != null && ref.getObjectId() != null) { symbolic.set(idx, ref); idx++; } else { loose = loose.remove(idx); symbolic.remove(idx); } } return new RefMap(prefix, packed, upcast(loose), symbolic.toRefList()); }
Source:
<code>protected void updateBlobTtl(final String blobIdStr, final String serviceId, long expiresAtMs, FutureResult<Void> futureResult, Callback<Void> callback) { Callback<GetBlobResultInternal> internalCallback = (GetBlobResultInternal result, Exception exception) -> { List<String> blobIdStrs = new ArrayList<>(); blobIdStrs.add(blobIdStr); if (exception != null) { completeOperation(futureResult, callback, null, exception, false); } else if (result.getBlobResult != null) { <START> exception = new RouterException("Unexpected result returned by GET operation before TTL update", <END> RouterErrorCode.UnexpectedInternalError); completeOperation(futureResult, callback, null, exception, false); } else if (result.storeKeys != null) { result.storeKeys.forEach(key -> blobIdStrs.add(key.getID())); } try { currentOperationsCount.addAndGet(blobIdStrs.size()); ttlUpdateManager.submitTtlUpdateOperation(blobIdStrs, serviceId, expiresAtMs, futureResult, callback); routerCallback.onPollReady(); } catch (RouterException e) { currentOperationsCount.addAndGet(1 - blobIdStrs.size()); completeUpdateBlobTtlOperation(e, futureResult, callback); } }; GetBlobOptionsInternal options = new GetBlobOptionsInternal(new GetBlobOptions(GetBlobOptions.OperationType.All, GetOption.None, null), true, routerMetrics.ageAtTtlUpdate); try { getBlob(blobIdStr, options, internalCallback); } catch (RouterException e) { completeUpdateBlobTtlOperation(e, futureResult, callback); } }</code><technical_language>change RouterException message a bit more descriptive? unexpected result is due getChunkIdsOnly here. add info exception message(optional)</technical_language>

Target:
protected void updateBlobTtl(final String blobIdStr, final String serviceId, long expiresAtMs, FutureResult<Void> futureResult, Callback<Void> callback) { Callback<GetBlobResultInternal> internalCallback = (GetBlobResultInternal result, Exception exception) -> { List<String> blobIdStrs = new ArrayList<>(); blobIdStrs.add(blobIdStr); if (exception != null) { completeOperation(futureResult, callback, null, exception, false); } else if (result.getBlobResult != null) { exception = new RouterException("GET blob call returned the blob instead of just the store keys (before TTL update)", RouterErrorCode.UnexpectedInternalError); completeOperation(futureResult, callback, null, exception, false); } else if (result.storeKeys != null) { result.storeKeys.forEach(key -> blobIdStrs.add(key.getID())); } try { currentOperationsCount.addAndGet(blobIdStrs.size()); ttlUpdateManager.submitTtlUpdateOperation(blobIdStrs, serviceId, expiresAtMs, futureResult, callback); routerCallback.onPollReady(); } catch (RouterException e) { currentOperationsCount.addAndGet(1 - blobIdStrs.size()); completeUpdateBlobTtlOperation(e, futureResult, callback); } }; GetBlobOptionsInternal options = new GetBlobOptionsInternal(new GetBlobOptions(GetBlobOptions.OperationType.All, GetOption.None, null), true, routerMetrics.ageAtTtlUpdate); try { getBlob(blobIdStr, options, internalCallback); } catch (RouterException e) { completeUpdateBlobTtlOperation(e, futureResult, callback); } }
Source:
<code>public String toString() { try { <START> return "LargeServerMessage[messageID=" + messageID + ",durable=" + isDurable() + ",userID=" + getUserID() + ",priority=" + this.getPriority() + ", timestamp=" + toDate(getTimestamp()) + ",expiration=" + toDate(getExpiration()) + ", durable=" + durable + ", address=" + getAddress() + ",size=" + getPersistentSize(true) + ",properties=" + (properties != null ? properties.toString() : "") + "]@" + System.identityHashCode(this); <END> } catch (Exception e) { e.printStackTrace(); return "LargeServerMessage[messageID=" + messageID + "]"; } }</code><technical_language>remove fileSize here... change need</technical_language>

Target:
public String toString() { try { return "LargeServerMessage[messageID=" + messageID + ",durable=" + isDurable() + ",userID=" + getUserID() + ",priority=" + this.getPriority() + ", timestamp=" + toDate(getTimestamp()) + ",expiration=" + toDate(getExpiration()) + ", durable=" + durable + ", address=" + getAddress() + ", properties=" + (properties != null ? properties.toString() : "") + "]@" + System.identityHashCode(this); } catch (Exception e) { e.printStackTrace(); return "LargeServerMessage[messageID=" + messageID + "]"; } }
Source:
<code>public void onRestResponse(RestResponse res, RequestContext requestContext, Map<String, String> wireAttrs, NextFilter<RestRequest, RestResponse> nextFilter) { <START> Object request = requestContext.getLocalAttr(ORIGINAL_REQUEST); <END> if (request instanceof RestRequest) { if (_darkClusterVerifier.isEnabled()) { _executorService.execute(() -> _darkClusterVerifier.onResponse((RestRequest) request, ResponseImpl.success(res))); } } nextFilter.onResponse(res, requestContext, wireAttrs); }</code><technical_language>Check out RequestContextUtil#getObjectWithKey RequestContextUtil#getServerRequestFinalizerManager. do a similar here? dependencies work out RequestContextUtil is in r2-core module</technical_language>

Target:
public void onRestResponse(RestResponse res, RequestContext requestContext, Map<String, String> wireAttrs, NextFilter<RestRequest, RestResponse> nextFilter) { Object request = requestContext.getLocalAttr(ORIGINAL_REQUEST_KEY); if (request instanceof RestRequest) { _darkClusterVerifierManager.onResponse((RestRequest) request, res); } nextFilter.onResponse(res, requestContext, wireAttrs); }
Source:
<code><START> public void testTryFill() throws Exception { <END> try (final ServerSocket socket = new ServerSocket(0)) { final ForkJoinTask<?> forked = ForkJoinTask.adapt(() -> { try { socket.setSoTimeout(1000); socket.accept().getOutputStream().write(1); } catch (Exception e) { throw new RuntimeException(e); } }).fork(); try (SocketChannel channel = SocketChannel.open()) { channel.configureBlocking(false); channel.connect(new InetSocketAddress(InetAddress.getLoopbackAddress(), socket.getLocalPort())); TimeoutTask.attempt(t -> channel.finishConnect(), 100, 1); final ByteBuffer buffer = ByteBuffer.allocate(1); SingleInstanceManager.tryFill(channel, buffer, 100); assertFalse(buffer.hasRemaining()); } forked.join(); } }</code><technical_language>failed CI server</technical_language>

Target:
public void testTryFill() throws Exception { try (final ServerSocket socket = new ServerSocket(0)) { final ForkJoinTask<?> forked = ForkJoinTask.adapt(() -> { try { socket.setSoTimeout(1000); socket.accept().getOutputStream().write(1); } catch (Exception e) { throw new RuntimeException(e); } }).fork(); try (SocketChannel channel = SocketChannel.open()) { channel.configureBlocking(false); channel.connect(new InetSocketAddress(InetAddress.getLoopbackAddress(), socket.getLocalPort())); TimeoutTask.attempt(t -> channel.finishConnect(), 1000, 1); final ByteBuffer buffer = ByteBuffer.allocate(1); SingleInstanceManager.tryFill(channel, buffer, 1000); assertFalse(buffer.hasRemaining()); } forked.join(); } }
Source:
<code>private Function<String, Object> getMapperFunction(final VCFHeaderLineType genValType) { <START> if (genValType == VCFHeaderLineType.Integer) { <END> return Integer::parseInt; } if (genValType == VCFHeaderLineType.Float) { return Double::parseDouble; } return x -> x.charAt(0); }</code><technical_language>this a switch handles types a default explodes</technical_language>

Target:
private Function<String, Object> getMapperFunction(final VCFHeaderLineType genValType) { switch(genValType){ case String: return x -> x; case Integer: return Integer::parseInt; case Float: return Double::parseDouble; case Character: return x -> x.charAt(0); default: throw new IllegalArgumentException("Unknown type of genotype field's value(s)"); } }
Source:
<code>public void testOrConstraint() { final String drl = "import org.drools.testcoverage.common.model.Employee;\n" + "import org.drools.testcoverage.common.model.Address;\n" + "global java.util.List list\n" + "\n" + "rule R when\n" + " $emp: Employee( $address: /address{ street == 'Elm' || city == 'Big City' } )\n" + " Employee( this != $emp, /address{ street == 'Elm' || city == 'Big City' } )\n" + "then\n" + " list.add( $address.getCity() );\n" + "end\n"; final KieBase kieBase = KieBaseUtil.getKieBaseFromDRLResources(true, KIE_SERVICES.getResources().newByteArrayResource(drl.getBytes())); this.kieSession = kieBase.newKieSession(); final List<String> list = new ArrayList<String>(); this.kieSession.setGlobal("list", list); <START> final Address addressOfBruno = new Address("Elm", 10, "Small City"); <END> final Employee bruno = new Employee("Bruno"); bruno.setAddress(addressOfBruno); final Address addressOfAlice = new Address("Elm", 10, "Big City"); final Employee alice = new Employee("Alice"); alice.setAddress(addressOfAlice); this.kieSession.insert(bruno); this.kieSession.insert(alice); this.kieSession.fireAllRules(); Assertions.assertThat(list).containsExactlyInAnyOrder("Big City", "Small City"); }</code><technical_language>This is repeated often, extracted separate method reused</technical_language>

Target:
public void testOrConstraint() { final String drl = "import org.drools.testcoverage.common.model.Employee;\n" + "import org.drools.testcoverage.common.model.Address;\n" + "global java.util.List list\n" + "\n" + "rule R when\n" + " $emp: Employee( $address: /address{ street == 'Elm' || city == 'Big City' } )\n" + " Employee( this != $emp, /address{ street == 'Elm' || city == 'Big City' } )\n" + "then\n" + " list.add( $address.getCity() );\n" + "end\n"; final KieBase kieBase = KieBaseUtil.getKieBaseFromDRLResources(true, KIE_SERVICES.getResources().newByteArrayResource(drl.getBytes())); this.initKieSession(kieBase); this.kieSession.fireAllRules(); Assertions.assertThat(this.results).containsExactlyInAnyOrder("Big City", "Small City"); }
Source:
<code><START> public List<ValidationError> validate(){ <END> Pattern hasLetters = Pattern.compile("[a-zA-Z]"); List<ValidationError> errors = new ArrayList<>(); if (hasLetters.matcher(phoneNumber).find()) errors.add(new ValidationError("phoneNumber", "The Phone Number must NOT contain letters")); return errors.isEmpty() ? null : errors; }</code><technical_language>This a global error instead of handling gracefully, is end in database, I guess, triggerable difficulty I issue. checks letters, regex client-side removes non-digit. Meaning send symbol gladly put database</technical_language>

Target:
public List<ValidationError> validate(){ Pattern hasLetters = Pattern.compile("[\\D]"); List<ValidationError> errors = new ArrayList<>(); if (hasLetters.matcher(phoneNumber).find()) errors.add(new ValidationError("phoneNumber", "The Phone Number must ONLY contain numbers")); return errors.isEmpty() ? null : errors; }
Source:
<code>public CompletableFuture<@Nullable Void> setValue(Command command) { String mqttCommandValue = getValue().update(command); final MqttBrokerConnection connection = this.connection; if (!config.commandTopic.isEmpty() && connection != null) { if (config.formatBeforePublish.length() > 0) { try (Formatter formatter = new Formatter()) { Formatter format = formatter.format(config.formatBeforePublish, mqttCommandValue); <START> mqttCommandValue = format.toString(); <END> } } return connection.publish(config.commandTopic, mqttCommandValue.getBytes(), 1, config.retained) .thenRun(() -> { }); } else { CompletableFuture<@Nullable Void> f = new CompletableFuture<>(); f.completeExceptionally(new IllegalStateException("No connection or no command topic!")); return f; } }</code><technical_language>this fail silently? If so, I suggest a debug logging give users a hint</technical_language>

Target:
public CompletableFuture<@Nullable Void> setValue(Command command) { String mqttCommandValue = getValue().update(command); final MqttBrokerConnection connection = this.connection; if (!readOnly && connection != null) { if (config.formatBeforePublish.length() > 0) { try (Formatter formatter = new Formatter()) { Formatter format = formatter.format(config.formatBeforePublish, mqttCommandValue); mqttCommandValue = format.toString(); } catch (IllegalFormatException e) { logger.debug("Format pattern incorrect for {}", channelUID, e); } } return connection.publish(config.commandTopic, mqttCommandValue.getBytes(), 1, config.retained) .thenRun(() -> { }); } else { CompletableFuture<@Nullable Void> f = new CompletableFuture<>(); f.completeExceptionally(new IllegalStateException("No connection or readOnly channel!")); return f; } }
Source:
<code>public void testIsHeartbeatTopic() throws InterruptedException, TimeoutException { MirrorClient client = new FakeMirrorClient(); assertTrue(client.isHeartbeatTopic("heartbeats")); assertTrue(client.isHeartbeatTopic("source1.heartbeats")); assertTrue(client.isHeartbeatTopic("source2.source1.heartbeats")); assertFalse(client.isHeartbeatTopic("heartbeats!")); assertFalse(client.isHeartbeatTopic("!heartbeats")); assertFalse(client.isHeartbeatTopic("source1heartbeats")); assertFalse(client.isHeartbeatTopic("source1-heartbeats")); <START> client.close(); <END> }</code><technical_language>calling close do avoid warnings? warnings coming from</technical_language>

Target:
public void testIsHeartbeatTopic() throws InterruptedException, TimeoutException { MirrorClient client = new FakeMirrorClient(); assertTrue(client.isHeartbeatTopic("heartbeats")); assertTrue(client.isHeartbeatTopic("source1.heartbeats")); assertTrue(client.isHeartbeatTopic("source2.source1.heartbeats")); assertFalse(client.isHeartbeatTopic("heartbeats!")); assertFalse(client.isHeartbeatTopic("!heartbeats")); assertFalse(client.isHeartbeatTopic("source1heartbeats")); assertFalse(client.isHeartbeatTopic("source1-heartbeats")); }
Source:
<code>public void testAddTransfer_Owner(){ addTicketTransfer(user.getUsername(), "password").then().statusCode(HttpStatus.SC_OK); ticket = ticketRepository.findByKey(ticket.getKey()).orElse(null); if(ticket == null) Assert.fail("Could not refresh ticket"); <START> Assert.assertTrue(ticket.isLockedForTransfer()); <END> }</code><technical_language>junit.Assert is deprecated. Please a</technical_language>

Target:
public void testAddTransfer_Owner(){ String token = addTicketTransfer(user.getUsername(), "password") .then() .statusCode(HttpStatus.SC_OK) .extract().path("object.token"); TicketTransferToken ttt = tttRepository.findByToken(token).orElseThrow(() -> new TokenNotFoundException(token)); Assert.assertTrue(ttt.isValid()); Assert.assertTrue(ttt.getTicket().getOwner().equals(user)); Assert.assertTrue(ttt.getUser().equals(ticketReceiver)); }
Source:
<code>public void onNext(T element) { try { received.add(element); } catch (IllegalStateException ex) { <START> if (ex.getMessage().contains("Queue full")) { <END> throw new IllegalStateException("Received more than bufferSize (" + received.QUEUE_SIZE + ") onNext signals. " + "The Publisher probably emited more signals than expected!", ex); } else throw ex; } }</code><technical_language>this fragile</technical_language>

Target:
public void onNext(T element) { try { received.add(element); } catch (IllegalStateException ex) { throw new SubscriberBufferOverflowException( String.format("Received more than bufferSize (%d) onNext signals. " + "The Publisher probably emited more signals than expected!", received.QUEUE_SIZE), ex); } }
Source:
<code>public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { try { if (currentFormat != null) calc(); } catch (GeopointException e) { <START> context.showToast(e.getMessage()); <END> spinner.setSelection(currentFormat.ordinal()); return; } currentFormat = coordInputFormatEnum.fromInt(pos); settings.setCoordInputFormat(currentFormat); updateGUI(); }</code><technical_language>good idea. ;)</technical_language>

Target:
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { if (currentFormat != null && !calc()) { spinner.setSelection(currentFormat.ordinal()); return; } currentFormat = coordInputFormatEnum.fromInt(pos); settings.setCoordInputFormat(currentFormat); updateGUI(); }
Source:
<code>public MesosSlaveInfo copyWithDockerImage(String label, String dockerImage) { LOGGER.fine(String.format("Customize mesos slave %s using docker image %s", this.getLabelString(), dockerImage)); try { return new MesosSlaveInfo( label, mode, slaveCpus, slaveMem, minExecutors, maxExecutors, executorCpus, executorMem, remoteFSRoot, idleTerminationMinutes, slaveAttributes, jvmArgs, jnlpArgs, defaultSlave, containerInfo.copyWithDockerImage(dockerImage), additionalURIs, nodeProperties ); } catch (Descriptor.FormException e) { <START> return null; <END> } catch (IOException e) { return null; } }</code><technical_language>log exception</technical_language>

Target:
public MesosSlaveInfo copyWithDockerImage(String label, String dockerImage) { LOGGER.fine(String.format("Customize mesos slave %s using docker image %s", this.getLabelString(), dockerImage)); try { return new MesosSlaveInfo( label, mode, slaveCpus, slaveMem, minExecutors, maxExecutors, executorCpus, executorMem, remoteFSRoot, idleTerminationMinutes, slaveAttributes, jvmArgs, jnlpArgs, defaultSlave, containerInfo.copyWithDockerImage(dockerImage), additionalURIs, nodeProperties ); } catch (Descriptor.FormException e) { LOGGER.log(Level.WARNING, "Failed to create customized mesos container info", e); return null; } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to create customized mesos slave info", e); return null; } }
Source:
<code>public DataSegment push(final File inDir, final DataSegment segment, final boolean useUniquePath) throws IOException { final String storageDir = this.getStorageDir(segment, false); log.info( "Copying segment[%s] to HDFS at location[%s/%s]", segment.getId(), fullyQualifiedStorageDirectory.get(), storageDir ); final String uniquePrefix = useUniquePath ? DataSegmentPusher.generateUniquePath() + "_" : ""; final Path outIndexFile = new Path(StringUtils.format( "%s/%s/%d_%sindex.zip", fullyQualifiedStorageDirectory.get(), storageDir, segment.getShardSpec().getPartitionNum(), uniquePrefix )); FileSystem fs = outIndexFile.getFileSystem(hadoopConfig); fs.mkdirs(outIndexFile.getParent()); log.info("Compressing files from[%s] to [%s]", inDir, outIndexFile); final long size; <START> try (FSDataOutputStream out = fs.create(outIndexFile)) { <END> size = CompressionUtils.zip(inDir, out); } return segment.withLoadSpec(makeLoadSpec(outIndexFile.toUri())) .withSize(size) .withBinaryVersion(SegmentUtils.getVersionFromDir(inDir)); }</code><technical_language>I default fs.create allows overwriting, is a reason to? Overwriting dangerous lead segments inconsistent data historicals - if segment is pushed for some reason. do setting overwrite false</technical_language>

Target:
public DataSegment push(final File inDir, final DataSegment segment, final boolean useUniquePath) throws IOException { final String storageDir = this.getStorageDir(segment, false); log.info( "Copying segment[%s] to HDFS at location[%s/%s]", segment.getId(), fullyQualifiedStorageDirectory.get(), storageDir ); final String uniquePrefix = useUniquePath ? DataSegmentPusher.generateUniquePath() + "_" : ""; final Path outIndexFile = new Path(StringUtils.format( "%s/%s/%d_%sindex.zip", fullyQualifiedStorageDirectory.get(), storageDir, segment.getShardSpec().getPartitionNum(), uniquePrefix )); FileSystem fs = outIndexFile.getFileSystem(hadoopConfig); fs.mkdirs(outIndexFile.getParent()); log.info("Compressing files from[%s] to [%s]", inDir, outIndexFile); final long size; try (FSDataOutputStream out = fs.create(outIndexFile, false)) { size = CompressionUtils.zip(inDir, out); } return segment.withLoadSpec(makeLoadSpec(outIndexFile.toUri())) .withSize(size) .withBinaryVersion(SegmentUtils.getVersionFromDir(inDir)); }
Source:
<code>private int readIntConfigWithDefaultValue(Map<String, String> configs, String key, int defaultValue) { int intConfigValue; String intConfigStrValue = configs.get(key); if (intConfigStrValue != null) { try { intConfigValue = Integer.parseInt(intConfigStrValue); } catch (Exception e) { intConfigValue = defaultValue; } } else { intConfigValue = defaultValue; <START> } <END> return intConfigValue; }</code><technical_language>is this config for</technical_language>

Target:
private int readIntConfigWithDefaultValue(Map<String, String> configs, String key, int defaultValue) { int intConfigValue; String intConfigStrValue = configs.get(key); if (intConfigStrValue != null) { try { intConfigValue = Integer.parseInt(intConfigStrValue); } catch (Exception e) { LOGGER.warn("Failed to read the int config with the key = {}. Using default value = {}", key, defaultValue); intConfigValue = defaultValue; } } else { intConfigValue = defaultValue; } return intConfigValue; }
Source:
<code>private void initSession() throws RuntimeException, InterruptedException { int retryCounter = cassandraConnectionMaxRetries; while (retryCounter-- != 0) { try { createSession(); <START> break; <END> } catch (NoHostAvailableException e) { log.error(e.getMessage()); Thread.sleep(cassandraConnectionMaxDelay); } } throw new RuntimeException("Cassandra connection retry limit exceeded."); }</code><technical_language>this needs return; instead, a break end throw new RuntimeException("Cassandra connection retry limit exceeded."); if session created successfully</technical_language>

Target:
private void initSession() throws RuntimeException, InterruptedException { int retryCounter = cassandraConnectionMaxRetries; while (retryCounter-- != 0) { try { createSession(); return; } catch (NoHostAvailableException e) { log.error(e.getMessage()); Thread.sleep(cassandraConnectionMaxDelay); } } throw new RuntimeException("Cassandra connection retry limit exceeded."); }
Source:
<code>public void shouldFailWithoutAdditionalInfosWhenMimeTypeIsNotSupportedByConverter() throws IOException { String converterName = cs.getConverterName("image/jpeg", "application/pdf"); BlobHolder blobHolder = getBlobFromPath("test-docs/" + "hello.xls", "application/vnd.ms-excel"); try { cs.convert(converterName, blobHolder, Collections.emptyMap()); } catch (ConversionException e) { assertNotNull(e.getInfos()); <START> assertTrue(CollectionUtils.isEmpty(e.getInfos())); <END> } }</code><technical_language>need CollectionUtils asserting nullity</technical_language>

Target:
public void shouldFailWithoutAdditionalInfosWhenMimeTypeIsNotSupportedByConverter() throws IOException { String converterName = cs.getConverterName("image/jpeg", "application/pdf"); BlobHolder blobHolder = getBlobFromPath("test-docs/hello.xls", "application/vnd.ms-excel"); try { cs.convert(converterName, blobHolder, Collections.emptyMap()); fail("Should have raised a ConversionException"); } catch (ConversionException e) { assertTrue(e.getInfos().isEmpty()); } }
Source:
<code>public RegistryAuthLocator(AuthConfig defaultAuthConfig) { this.defaultAuthConfig = defaultAuthConfig; <START> this.configFile = new File(System.getProperty("user.home") + "/.docker/config.json"); <END> this.commandPathPrefix = ""; }</code><technical_language>DefaultDockerClientConfig::dockerConfigPath field</technical_language>

Target:
public RegistryAuthLocator(AuthConfig defaultAuthConfig) { this.defaultAuthConfig = defaultAuthConfig; final String dockerConfigLocation = System.getenv().getOrDefault("DOCKER_CONFIG", System.getProperty("user.home") + "/.docker"); this.configFile = new File(dockerConfigLocation + "/config.json"); this.commandPathPrefix = ""; }
Source:
<code>public void initClass() { Log.setGlobalLogLevel(LogLevel.ERROR); <START> } <END></code><technical_language>I capture log level avoid weird timing discrepancy</technical_language>

Target:
public void initClass() { globalLogLevel = Log.getGlobalLogLevel(); Log.setGlobalLogLevel(LogLevel.ERROR); }
Source:
<code>public void disableManager() { _logger.info("Disabling Metric Manager"); if (_isManagerEnabled) { _isManagerEnabled = false; for (IMetricEmitter emitter : _metricEmitters) { try { emitter.purgeAllData(); } catch (Exception ex) { <START> _logger.error("Failed to purge data " + ex.toString()); <END> } } } }</code><technical_language>get more useful info. _logger.error("Failed purge data", ex);</technical_language>

Target:
public void disableManager() { logger.info("Disabling Metric Manager"); if (isManagerEnabled) { isManagerEnabled = false; for (IMetricEmitter emitter : metricEmitters) { try { emitter.purgeAllData(); } catch (MetricException ex) { logger.error("Failed to purge data ", ex); } } } }
Source:
<code>private boolean contentCheck(DirCacheEntry entry, ObjectReader reader) throws IOException { if (getEntryObjectId().equals(entry.getObjectId())) { entry.setLength((int) getEntryLength()); return false; } else { if (mode == FileMode.SYMLINK.getBits()) <START> return !new File(FS.detect().normalize( <END> readContentAsString(current()))).equals(new File((FS .detect().normalize(readContentAsString(entry))))); if (reader == null) return true; switch (getOptions().getAutoCRLF()) { case INPUT: case TRUE: InputStream dcIn = null; try { ObjectLoader loader = reader.open(entry.getObjectId()); if (loader == null) return true; dcIn = new EolCanonicalizingInputStream( loader.openStream(), true, true ); long dcInLen; try { dcInLen = computeLength(dcIn); } catch (EolCanonicalizingInputStream.IsBinaryException e) { return true; } finally { dcIn.close(); } dcIn = new EolCanonicalizingInputStream( loader.openStream(), true); byte[] autoCrLfHash = computeHash(dcIn, dcInLen); boolean changed = getEntryObjectId().compareTo( autoCrLfHash, 0) != 0; return changed; } catch (IOException e) { return true; } finally { if (dcIn != null) try { dcIn.close(); } catch (IOException e) { } } case FALSE: break; } return true; } }</code><technical_language>move normalize calls readContentAsString methods improve readability</technical_language>

Target:
private boolean contentCheck(DirCacheEntry entry, ObjectReader reader) throws IOException { if (getEntryObjectId().equals(entry.getObjectId())) { entry.setLength((int) getEntryLength()); return false; } else { if (mode == FileMode.SYMLINK.getBits()) return !new File(readContentAsNormalizedString(current())) .equals(new File((readContentAsNormalizedString(entry)))); if (reader == null) return true; switch (getOptions().getAutoCRLF()) { case INPUT: case TRUE: InputStream dcIn = null; try { ObjectLoader loader = reader.open(entry.getObjectId()); if (loader == null) return true; dcIn = new EolCanonicalizingInputStream( loader.openStream(), true, true ); long dcInLen; try { dcInLen = computeLength(dcIn); } catch (EolCanonicalizingInputStream.IsBinaryException e) { return true; } finally { dcIn.close(); } dcIn = new EolCanonicalizingInputStream( loader.openStream(), true); byte[] autoCrLfHash = computeHash(dcIn, dcInLen); boolean changed = getEntryObjectId().compareTo( autoCrLfHash, 0) != 0; return changed; } catch (IOException e) { return true; } finally { if (dcIn != null) try { dcIn.close(); } catch (IOException e) { } } case FALSE: break; } return true; } }
Source:
<code>public static SmartThread asyncLoop(final Callable afn, boolean isDaemon, final Thread.UncaughtExceptionHandler eh, int priority, final boolean isFactory, boolean startImmediately, String threadName) { SmartThread thread = new SmartThread(new Runnable() { public void run() { try { final Callable<Long> fn = isFactory ? (Callable<Long>) afn.call() : afn; while (true) { final Long s = fn.call(); if (s==null) break; if (s>0) Time.sleep(s); } } catch (Throwable t) { <START> LOG.info("Async loop Exception Stacktrace is: ", getStackTrace(t)); <END> if (Utils.exceptionCauseIsInstanceOf( InterruptedException.class, t)) { LOG.info("Async loop interrupted!"); return; } LOG.error("Async loop died!", t); throw new RuntimeException(t); } } }); if (eh != null) { thread.setUncaughtExceptionHandler(eh); } else { thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { LOG.error("Async loop died!", e); Utils.exitProcess(1, "Async loop died!"); } }); } thread.setDaemon(isDaemon); thread.setPriority(priority); if (threadName != null && !threadName.isEmpty()) { thread.setName(thread.getName() +"-"+ threadName); } if (startImmediately) { thread.start(); } return thread; }</code><technical_language>stack trace log in line 372</technical_language>

Target:
public static SmartThread asyncLoop(final Callable afn, boolean isDaemon, final Thread.UncaughtExceptionHandler eh, int priority, final boolean isFactory, boolean startImmediately, String threadName) { SmartThread thread = new SmartThread(new Runnable() { public void run() { try { final Callable<Long> fn = isFactory ? (Callable<Long>) afn.call() : afn; while (true) { final Long s = fn.call(); if (s == null) { break; } if (s > 0) { Time.sleep(s); } } } catch (Throwable t) { if (Utils.exceptionCauseIsInstanceOf( InterruptedException.class, t)) { LOG.error("Async loop interrupted!", t); return; } LOG.error("Async loop died!", t); throw new RuntimeException(t); } } }); if (eh != null) { thread.setUncaughtExceptionHandler(eh); } else { thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { LOG.error("Async loop died!", e); Utils.exitProcess(1, "Async loop died!"); } }); } thread.setDaemon(isDaemon); thread.setPriority(priority); if (threadName != null && !threadName.isEmpty()) { thread.setName(thread.getName() + "-" + threadName); } if (startImmediately) { thread.start(); } return thread; }
Source:
<code>synchronized long expireServer(final ServerName serverName, boolean force) { ZKWatcher zkw = master.getZooKeeper(); if (serverName.equals(master.getServerName())) { if (!(master.isAborted() || master.isStopped())) { master.stop("We lost our znode?"); } return Procedure.NO_PROC_ID; } if (this.deadservers.isDeadServer(serverName)) { LOG.warn("Expiration called on but already in DeadServer", serverName); return Procedure.NO_PROC_ID; } moveFromOnlineToDeadServers(serverName); String drainingZnode = ZNodePaths.joinZNode(zkw.getZNodePaths().drainingZNode, serverName.getServerName()); try { ZKUtil.deleteNodeFailSilent(zkw, drainingZnode); } catch (KeeperException e) { <START> LOG.warn("Error deleting the znode for draining server " + drainingZnode); <END> } if (isClusterShutdown()) { LOG.info("Cluster shutdown set; " + serverName + " expired; onlineServers=" + this.onlineServers.size()); if (this.onlineServers.isEmpty()) { master.stop("Cluster shutdown set; onlineServer=0"); } return Procedure.NO_PROC_ID; } LOG.info("Processing expiration of " + serverName + " on " + this.master.getServerName()); long pid = master.getAssignmentManager().submitServerCrash(serverName, true, force); if (!this.listeners.isEmpty()) { this.listeners.stream().forEach(l -> l.serverRemoved(serverName)); } if (flushedSeqIdFlusher != null) { flushedSeqIdFlusher.triggerNow(); } return pid; }</code><technical_language>LOG.warn("Error deleting znode for draining server {}", serverName.getServerName(), e) providing stacktrace better</technical_language>

Target:
synchronized long expireServer(final ServerName serverName, boolean force) { if (serverName.equals(master.getServerName())) { if (!(master.isAborted() || master.isStopped())) { master.stop("We lost our znode?"); } return Procedure.NO_PROC_ID; } if (this.deadservers.isDeadServer(serverName)) { LOG.warn("Expiration called on but already in DeadServer", serverName); return Procedure.NO_PROC_ID; } moveFromOnlineToDeadServers(serverName); if (master.getZooKeeper() != null) { String drainingZnode = ZNodePaths .joinZNode(master.getZooKeeper().getZNodePaths().drainingZNode, serverName.getServerName()); try { ZKUtil.deleteNodeFailSilent(master.getZooKeeper(), drainingZnode); } catch (KeeperException e) { LOG.warn("Error deleting the draining znode for stopping server " + serverName.getServerName(), e); } } if (isClusterShutdown()) { LOG.info("Cluster shutdown set; " + serverName + " expired; onlineServers=" + this.onlineServers.size()); if (this.onlineServers.isEmpty()) { master.stop("Cluster shutdown set; onlineServer=0"); } return Procedure.NO_PROC_ID; } LOG.info("Processing expiration of " + serverName + " on " + this.master.getServerName()); long pid = master.getAssignmentManager().submitServerCrash(serverName, true, force); if (!this.listeners.isEmpty()) { this.listeners.stream().forEach(l -> l.serverRemoved(serverName)); } if (flushedSeqIdFlusher != null) { flushedSeqIdFlusher.triggerNow(); } return pid; }
Source:
<code><START> void scrollToBottom() { <END> final HTMLElement container = (HTMLElement) getElement(); container.scrollTop = container.scrollHeight - container.clientHeight; }</code><technical_language>I re-introduce logic [1] [2], point of view worth extract this scroll logic a separate class reuse multiple times. [1] <LINK_0> [2] <LINK_1></technical_language>

Target:
private void scrollToBottom() { scrollHelper.scrollToBottom(getElement()); }
Source:
<code>private boolean checkTetrahedral(int u, int[] mapping) { int v = mapping[u]; if (targetTypes[v] != null && targetTypes[v] != Type.Tetrahedral) return false; ITetrahedralChirality queryElement = (ITetrahedralChirality) queryElements[u]; ITetrahedralChirality targetElement = (ITetrahedralChirality) targetElements[v]; IAtom queryAtom = query.getAtom(u); IAtom targetAtom = target.getAtom(v); if (targetTypes[v] == null) return ((QueryAtom)queryAtom).getExpression().matches(targetAtom, 0); if (targetTypes[v] != Type.Tetrahedral) return false; int[] us = map(u, v, neighbors(queryElement, queryMap), mapping); int[] vs = neighbors(targetElement, targetMap); int focusIdx = targetMap.get(targetAtom); for (int i = 0; i < 4; i++) { int j = 0, k = 0; for (; j < 4; j++) { if (vs[i] == us[j]) break; if (us[j] == focusIdx) k = j; } if (j == 4) us[k] = vs[i]; <START> } <END> int parity = permutationParity(us) * permutationParity(vs) * parity(targetElement.getStereo()); if (parity < 0) return ((QueryAtom) queryAtom).getExpression() .matches(targetAtom, IStereoElement.LEFT); else if (parity > 0) return ((QueryAtom) queryAtom).getExpression() .matches(targetAtom, IStereoElement.RIGHT); else return ((QueryAtom) queryAtom).getExpression() .matches(targetAtom, 0); }</code><technical_language>(no change needed, perspective) this code block, I clue this code is supposed do. I want I review this (in reasonable time), I this bit of code is supposed do</technical_language>

Target:
private boolean checkTetrahedral(int u, int[] mapping) { int v = mapping[u]; if (targetTypes[v] != null && targetTypes[v] != Type.Tetrahedral) return false; ITetrahedralChirality queryElement = (ITetrahedralChirality) queryElements[u]; ITetrahedralChirality targetElement = (ITetrahedralChirality) targetElements[v]; IAtom queryAtom = query.getAtom(u); IAtom targetAtom = target.getAtom(v); if (targetTypes[v] == null) return ((QueryAtom)queryAtom).getExpression().matches(targetAtom, 0); if (targetTypes[v] != Type.Tetrahedral) return false; int[] us = map(u, v, neighbors(queryElement, queryMap), mapping); int[] vs = neighbors(targetElement, targetMap); int focusIdx = targetMap.get(targetAtom); for (int i = 0; i < 4; i++) { int j = indexOf(us, vs[i]); if (j < 0) us[indexOf(us, focusIdx)] = vs[i]; } int parity = permutationParity(us) * permutationParity(vs) * parity(targetElement.getStereo()); if (parity < 0) return ((QueryAtom) queryAtom).getExpression() .matches(targetAtom, IStereoElement.LEFT); else if (parity > 0) return ((QueryAtom) queryAtom).getExpression() .matches(targetAtom, IStereoElement.RIGHT); else return ((QueryAtom) queryAtom).getExpression() .matches(targetAtom, 0); }
Source:
<code><START> public Decision decide(final RepositoryPath repositoryPath) throws IOException <END> { RepositoryPath checksumRepositoryPath = resolveSiblingChecksum(repositoryPath, EncryptionAlgorithmsEnum.SHA1); String currentChecksum = readChecksum(checksumRepositoryPath); if (currentChecksum == null) { checksumRepositoryPath = resolveSiblingChecksum(repositoryPath, EncryptionAlgorithmsEnum.MD5); currentChecksum = readChecksum(checksumRepositoryPath); if (currentChecksum == null) { logger.debug("Unable to read local checksum for {}, will refetch metadata", repositoryPath.normalize()); return UNDECIDED; } } proxyRepositoryArtifactResolver.fetchRemoteResource(checksumRepositoryPath); final String newRemoteChecksum = readChecksum(checksumRepositoryPath); if (newRemoteChecksum == null) { logger.debug("Unable to fetch remote checksum for {}, will refetch metadata", repositoryPath.normalize()); return UNDECIDED; } if (currentChecksum.equals(newRemoteChecksum)) { logger.debug("Local and remote checksums match for {}, no need to refetch metadata", repositoryPath.normalize()); return USABLE; } else { logger.debug("Local and remote checksums differ for {}, will refetch metadata", repositoryPath.normalize()); return EXPIRED; } }</code><technical_language>@cbrianhill I changed original logic here. In currently existing method (org.carlspring.strongbox.providers.io.MavenMetadataExpiredRepositoryPathHandler#handleExpiration ) MD5 case is checked if SHA1 case give a "valid" decision (either YES_FETCH NO_LEAVE_IT). In case situation happen: * RepositoryPath checksumRepositoryPath = resolveSiblingChecksum(repositoryPath, EncryptionAlgorithmsEnum.SHA1); * currentChecksum = readChecksum(checksumRepositoryPath); * if (currentChecksum == null) returns false * proxyRepositoryArtifactResolver.fetchRemoteResource(checksumRepositoryPath); * final String newRemoteChecksum = readChecksum(checksumRepositoryPath); * if (newRemoteChecksum == null) returns true * result is UNDECIDED; check MD5 case in this situation, implementation</technical_language>

Target:
public Decision decide(final RepositoryPath repositoryPath) throws IOException { Decision decision = decideUsingChecksumAlgorithm(repositoryPath, EncryptionAlgorithmsEnum.SHA1); if (UNDECIDED.equals(decision)) { decision = decideUsingChecksumAlgorithm(repositoryPath, EncryptionAlgorithmsEnum.MD5); } return decision; }
Source:
<code>public void start() { <START> checkNotNull(bootstrap); <END> server = bootstrap.start(); }</code><technical_language>reserve checkNotNull for argument checking, checkState for state-like checks</technical_language>

Target:
public void start() { server = createWithValidation(validators).start(); }
Source:
<code>static ResourceMapping getContributedResourceMapping(IAdaptable element) { <START> Object resourceAdapter <END> = Adapters.getAdapter(element, IContributorResourceAdapter.class, true); if (resourceAdapter != null) { if (resourceAdapter instanceof IContributorResourceAdapter2) { IContributorResourceAdapter2 mappingAdapter = (IContributorResourceAdapter2) resourceAdapter; ResourceMapping mapping = mappingAdapter.getAdaptedResourceMapping(element); if (mapping != null) { return mapping; } } if (resourceAdapter instanceof IContributorResourceAdapter) { IResource resource = ((IContributorResourceAdapter) resourceAdapter).getAdaptedResource(element); if (resource != null) { ResourceMapping mapping = Adapters.getAdapter(resource, ResourceMapping.class, true); if (mapping != null) { return mapping; } } } } return null; }</code><technical_language>Object -> IContributorResourceAdapter</technical_language>

Target:
static ResourceMapping getContributedResourceMapping(IAdaptable element) { IContributorResourceAdapter resourceAdapter = Adapters.getAdapter(element, IContributorResourceAdapter.class, true); if (resourceAdapter != null) { if (resourceAdapter instanceof IContributorResourceAdapter2) { IContributorResourceAdapter2 mappingAdapter = (IContributorResourceAdapter2) resourceAdapter; ResourceMapping mapping = mappingAdapter.getAdaptedResourceMapping(element); if (mapping != null) { return mapping; } } IResource resource = resourceAdapter.getAdaptedResource(element); if (resource != null) { ResourceMapping mapping = Adapters.getAdapter(resource, ResourceMapping.class, true); if (mapping != null) { return mapping; } } } return null; }
Source:
<code>private static void registerTransformers_WF_17(ResourceTransformationDescriptionBuilder subsystem) { ResourceTransformationDescriptionBuilder externalConnectionFactory = subsystem.addChildResource(MessagingExtension.CONNECTION_FACTORY_PATH); rejectDefinedAttributeWithDefaultValue(externalConnectionFactory, ConnectionFactoryAttributes.Common.USE_TOPOLOGY); ResourceTransformationDescriptionBuilder externalPooledConnectionFactory = subsystem.addChildResource(MessagingExtension.POOLED_CONNECTION_FACTORY_PATH); <START> rejectDefinedAttributeWithDefaultValue(externalPooledConnectionFactory, ConnectionFactoryAttributes.Common.USE_TOPOLOGY); <END> ResourceTransformationDescriptionBuilder server = subsystem.addChildResource(SERVER_PATH); ResourceTransformationDescriptionBuilder connectionFactory = server.addChildResource(MessagingExtension.CONNECTION_FACTORY_PATH); rejectDefinedAttributeWithDefaultValue(connectionFactory, ConnectionFactoryAttributes.Common.USE_TOPOLOGY); ResourceTransformationDescriptionBuilder pooledConnectionFactory = server.addChildResource(MessagingExtension.POOLED_CONNECTION_FACTORY_PATH); rejectDefinedAttributeWithDefaultValue(pooledConnectionFactory, ConnectionFactoryAttributes.Common.USE_TOPOLOGY); rejectDefinedAttributeWithDefaultValue(server, ServerDefinition.JOURNAL_FILE_OPEN_TIMEOUT); }</code><technical_language>I checked Emmanuel correct</technical_language>

Target:
private static void registerTransformers_WF_17(ResourceTransformationDescriptionBuilder subsystem) { ResourceTransformationDescriptionBuilder externalConnectionFactory = subsystem.addChildResource(MessagingExtension.CONNECTION_FACTORY_PATH); rejectDefinedAttributeWithDefaultValue(externalConnectionFactory, ConnectionFactoryAttributes.Common.USE_TOPOLOGY, ConnectionFactoryAttributes.External.ENABLE_AMQ1_PREFIX); ResourceTransformationDescriptionBuilder externalPooledConnectionFactory = subsystem.addChildResource(MessagingExtension.POOLED_CONNECTION_FACTORY_PATH); rejectDefinedAttributeWithDefaultValue(externalPooledConnectionFactory, ConnectionFactoryAttributes.Common.USE_TOPOLOGY, ConnectionFactoryAttributes.External.ENABLE_AMQ1_PREFIX); ResourceTransformationDescriptionBuilder server = subsystem.addChildResource(SERVER_PATH); ResourceTransformationDescriptionBuilder connectionFactory = server.addChildResource(MessagingExtension.CONNECTION_FACTORY_PATH); rejectDefinedAttributeWithDefaultValue(connectionFactory, ConnectionFactoryAttributes.Common.USE_TOPOLOGY); ResourceTransformationDescriptionBuilder pooledConnectionFactory = server.addChildResource(MessagingExtension.POOLED_CONNECTION_FACTORY_PATH); rejectDefinedAttributeWithDefaultValue(pooledConnectionFactory, ConnectionFactoryAttributes.Common.USE_TOPOLOGY); rejectDefinedAttributeWithDefaultValue(server, ServerDefinition.JOURNAL_FILE_OPEN_TIMEOUT); }
Source:
<code>public boolean canHandle(Message<?> message) { <START> return super.canHandle(message) && deadlineNameMatch((DeadlineMessage) message); <END> }</code><technical_language>I turn this && around. A simple deadlineName check is a lot cheaper full parameter assignment verification</technical_language>

Target:
public boolean canHandle(Message<?> message) { return message instanceof DeadlineMessage && deadlineNameMatch((DeadlineMessage) message) && super.canHandle(message); }