auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Optional<BaseExpressionGrid> getExpressionGrid(final String nodeUUID) { <START> return cache.containsKey(nodeUUID) ? cache.get(nodeUUID) : Optional.empty(); <END> }</code><technical_language>I is touched this PR, I rewrite cache.getOrDefault(nodeUUID, Optional.empty());</technical_language>

Target:
public Optional<BaseExpressionGrid> getExpressionGrid(final String nodeUUID) { return cache.getOrDefault(nodeUUID, Optional.empty()); }
Source:
<code>protected <T> void notifyTransactionObservers(List<ObserverMethod<? super T>> observers, T event, EventMetadata metadata) { if (observers.isEmpty()) { return; } if (transactionServices == null || !transactionServices.isTransactionActive()) { notifySyncObservers(observers, event, metadata); } else { try { for (ObserverMethod<? super T> observer : observers) { <START> deferNotification(event, metadata, observer); <END> } } catch (Exception e) { if (e.getCause() instanceof RollbackException || e.getCause() instanceof IllegalStateException) { List<ObserverMethod<? super T>> filteredObservers = new ArrayList<>(observers); for (Iterator<ObserverMethod<? super T>> it = filteredObservers.iterator(); it.hasNext(); ) { ObserverMethod<? super T> observerMethod = it.next(); if (observerMethod.getTransactionPhase().equals(TransactionPhase.AFTER_SUCCESS)) { it.remove(); } } Collections.sort(filteredObservers, new Comparator<ObserverMethod<? super T>>() { @Override public int compare(ObserverMethod<? super T> o1, ObserverMethod<? super T> o2) { return o2.getTransactionPhase().toString().compareTo(o1.getTransactionPhase().toString()); } }); notifySyncObservers(filteredObservers, event, metadata); } else { throw e; } } } }</code><technical_language>Theoretically, some registrations pass. in catch block process observers for registration failed. E.g. create a copy of observers catch block, remove observer for registration passed process copy in catch block</technical_language>

Target:
protected <T> void notifyTransactionObservers(List<ObserverMethod<? super T>> observers, T event, EventMetadata metadata) { if (observers.isEmpty()) { return; } if (transactionServices == null || !transactionServices.isTransactionActive()) { notifySyncObservers(observers, event, metadata); } else { List<ObserverMethod<? super T>> failedObservers = new ArrayList<>(observers); try { for (ObserverMethod<? super T> observer : observers) { deferNotification(event, metadata, observer); failedObservers.remove(observer); } } catch (Exception e) { if (e.getCause() instanceof RollbackException || e.getCause() instanceof IllegalStateException) { List<ObserverMethod<? super T>> filteredObservers = new ArrayList<>(failedObservers); for (Iterator<ObserverMethod<? super T>> it = filteredObservers.iterator(); it.hasNext(); ) { ObserverMethod<? super T> observerMethod = it.next(); if (observerMethod.getTransactionPhase().equals(TransactionPhase.AFTER_SUCCESS)) { it.remove(); } } Collections.sort(filteredObservers, new Comparator<ObserverMethod<? super T>>() { @Override public int compare(ObserverMethod<? super T> o1, ObserverMethod<? super T> o2) { return o2.getTransactionPhase().toString().compareTo(o1.getTransactionPhase().toString()); } }); notifySyncObservers(filteredObservers, event, metadata); } else { throw e; } } } }
Source:
<code>public boolean equals(Object o) { if (this == o) { return true; } <START> if (o == null || getClass() != o.getClass()) { <END> return false; } TransactionEdit that = (TransactionEdit) o; return Objects.equal(this.writePointer, that.writePointer) && Objects.equal(this.visibilityUpperBound, that.visibilityUpperBound) && Objects.equal(this.commitPointer, that.commitPointer) && Objects.equal(this.expirationDate, that.expirationDate) && Objects.equal(this.state, that.state) && Objects.equal(this.changes, that.changes) && Objects.equal(this.canCommit, that.canCommit) && Objects.equal(this.type, that.type); }</code><technical_language>I class equality checks inflexible, priority instanceof instead. a big deal though</technical_language>

Target:
public final boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof TransactionEdit)) { return false; } TransactionEdit that = (TransactionEdit) o; return Objects.equal(this.writePointer, that.writePointer) && Objects.equal(this.visibilityUpperBound, that.visibilityUpperBound) && Objects.equal(this.commitPointer, that.commitPointer) && Objects.equal(this.expirationDate, that.expirationDate) && Objects.equal(this.state, that.state) && Objects.equal(this.changes, that.changes) && Objects.equal(this.canCommit, that.canCommit) && Objects.equal(this.type, that.type); }
Source:
<code>private void messageRead(HttpServerExchange exchange, byte[] messageContent, AttachmentContent attachment) { try { contentLengthChecker.check(exchange, messageContent.length, attachment); attachment.getCachedTopic().reportMessageContentSize(messageContent.length); <START> throughputLimiter.check( <END> attachment.getCachedTopic().getTopicName(), attachment.getCachedTopic().getThroughput()); attachment.setMessageContent(messageContent); endWithoutDefaultResponse(exchange); if (exchange.isInIoThread()) { dispatchToWorker(exchange, attachment); } else { next.handleRequest(exchange); } } catch (ContentLengthChecker.InvalidContentLengthException | ContentLengthChecker.ContentTooLargeException e) { attachment.removeTimeout(); messageErrorProcessor.sendAndLog(exchange, attachment.getTopic(), attachment.getMessageId(), error(e.getMessage(), VALIDATION_ERROR)); } catch (FixedThroughputLimiter.QuotaViolationException e) { respondWithQuotaViolation(exchange, attachment, e); } catch (Exception e) { attachment.removeTimeout(); messageErrorProcessor.sendAndLog(exchange, attachment.getTopic(), attachment.getMessageId(), e); } }</code><technical_language>do check throughput in 2 places? handleRequest</technical_language>

Target:
private void messageRead(HttpServerExchange exchange, byte[] messageContent, AttachmentContent attachment) { try { contentLengthChecker.check(exchange, messageContent.length, attachment); attachment.getCachedTopic().reportMessageContentSize(messageContent.length); ThroughputLimiter.QuotaInsight quotaCheck = throughputLimiter.checkQuota( attachment.getCachedTopic().getTopicName(), attachment.getCachedTopic().getThroughput()); if (quotaCheck.hasQuota()) { finalizeMessageRead(exchange, messageContent, attachment); } else { respondWithQuotaViolation(exchange, attachment, quotaCheck.getReason()); } } catch (ContentLengthChecker.InvalidContentLengthException | ContentLengthChecker.ContentTooLargeException e) { attachment.removeTimeout(); messageErrorProcessor.sendAndLog(exchange, attachment.getTopic(), attachment.getMessageId(), error(e.getMessage(), VALIDATION_ERROR)); } catch (Exception e) { attachment.removeTimeout(); messageErrorProcessor.sendAndLog(exchange, attachment.getTopic(), attachment.getMessageId(), e); } }
Source:
<code>public boolean processNextEvent() { <START> synchronized(this) { <END> if (queue.isEmpty() || status.get() == Status.RUNNING) { return false; } if (status.compareAndSet(Status.READY, Status.RUNNING)) { if (queue.isEmpty()) { status.set(Status.READY); return false; } final Tuple<MistEvent, Direction> event; event = queue.poll(); process(event); status.set(Status.READY); if (operatorChainManager != null && !queue.isEmpty()) { operatorChainManager.insert(this); } return true; } else { return false; } } }</code><technical_language>synchronised here? previous code synchronized checked if is ready queue is empty</technical_language>

Target:
public boolean processNextEvent() { if (queue.isEmpty() || status.get() == Status.RUNNING) { return false; } if (status.compareAndSet(Status.READY, Status.RUNNING)) { if (queue.isEmpty()) { status.set(Status.READY); return false; } final Tuple<MistEvent, Direction> event; synchronized (this) { event = queue.poll(); } process(event); status.set(Status.READY); if (operatorChainManager != null && !queue.isEmpty()) { operatorChainManager.insert(this); } return true; } else { return false; } }
Source:
<code>private synchronized void sendNextRequest() { TaskStatus taskStatus = getTaskInfo().getTaskStatus(); if (!running) { return; } if (isDone(getTaskInfo())) { stop(); return; } if (future != null && !future.isDone()) { return; } ListenableFuture<?> errorRateLimit = errorTracker.acquireRequestPermit(); if (!errorRateLimit.isDone()) { errorRateLimit.addListener(this::sendNextRequest, executor); return; } HttpUriBuilder httpUriBuilder = uriBuilderFrom(taskStatus.getSelf()); URI uri = summarizeTaskInfo ? httpUriBuilder.addParameter("summarize").build() : httpUriBuilder.build(); Request.Builder uriBuilder = setContentTypeHeaders(isBinaryTransportEnabled, prepareGet()); if (taskInfoRefreshMaxWait.toMillis() > 0) { uriBuilder.setHeader(PRESTO_CURRENT_STATE, taskStatus.getState().toString()) <START> .setHeader(PRESTO_MAX_WAIT, taskInfoRefreshMaxWait.toString()); <END> } Request request = uriBuilder.setUri(uri).build(); ResponseHandler responseHandler; if (isBinaryTransportEnabled) { responseHandler = createFullSmileResponseHandler((SmileCodec<TaskInfo>) taskInfoCodec); } else { responseHandler = createAdaptingJsonResponseHandler(unwrapJsonCodec(taskInfoCodec)); } errorTracker.startRequest(); future = httpClient.executeAsync(request, responseHandler); currentRequestStartNanos.set(System.nanoTime()); Futures.addCallback(future, new SimpleHttpResponseHandler<>(this, request.getUri(), stats), executor); }</code><technical_language>Currently TaskResource is implemented - long header is set (even 0s) - creates features, more if header is set. imply this is a problem, feels some sense default additional implications. I check for 0 here, if delay is 0 - set header</technical_language>

Target:
private synchronized void sendNextRequest() { TaskStatus taskStatus = getTaskInfo().getTaskStatus(); if (!running) { return; } if (isDone(getTaskInfo())) { stop(); return; } if (future != null && !future.isDone()) { return; } ListenableFuture<?> errorRateLimit = errorTracker.acquireRequestPermit(); if (!errorRateLimit.isDone()) { errorRateLimit.addListener(this::sendNextRequest, executor); return; } HttpUriBuilder httpUriBuilder = uriBuilderFrom(taskStatus.getSelf()); URI uri = summarizeTaskInfo ? httpUriBuilder.addParameter("summarize").build() : httpUriBuilder.build(); Request.Builder uriBuilder = setContentTypeHeaders(isBinaryTransportEnabled, prepareGet()); if (taskInfoRefreshMaxWait.toMillis() != 0L) { uriBuilder.setHeader(PRESTO_CURRENT_STATE, taskStatus.getState().toString()) .setHeader(PRESTO_MAX_WAIT, taskInfoRefreshMaxWait.toString()); } Request request = uriBuilder.setUri(uri).build(); ResponseHandler responseHandler; if (isBinaryTransportEnabled) { responseHandler = createFullSmileResponseHandler((SmileCodec<TaskInfo>) taskInfoCodec); } else { responseHandler = createAdaptingJsonResponseHandler(unwrapJsonCodec(taskInfoCodec)); } errorTracker.startRequest(); future = httpClient.executeAsync(request, responseHandler); currentRequestStartNanos.set(System.nanoTime()); Futures.addCallback(future, new SimpleHttpResponseHandler<>(this, request.getUri(), stats), executor); }
Source:
<code>public List<T> query(Query query) { Uri uri = getQueryUri(query); ContentResolver contentResolver = getContentResolver(); Cursor cursor = null; List<T> dataList = new ArrayList<T>(); try { cursor = contentResolver.query(uri, null, null, null, null); <START> System.out.println("contentResolver value = " + contentResolver); <END> CursorDataExtractor<T> extractor = getCursorDataExtractor(); cursor.moveToFirst(); while (!cursor.isAfterLast()) { T data = extractor.extract(cursor, query); dataList.add(data); cursor.moveToNext(); } } catch (Throwable t) { Log.e(TAG, "Error Reading data from Content Resolver", t); throw new RuntimeException(t); } finally { if (cursor != null && !cursor.isClosed()) { cursor.close(); } } return dataList; }</code><technical_language>System.out please</technical_language>

Target:
public List<T> query(Query query) { Uri uri = getQueryUri(query); ContentResolver contentResolver = getContentResolver(); Cursor cursor = null; List<T> dataList = new ArrayList<T>(); try { cursor = contentResolver.query(uri, null, null, null, null); CursorDataExtractor<T> extractor = getCursorDataExtractor(); cursor.moveToFirst(); while (!cursor.isAfterLast()) { T data = extractor.extract(cursor, query); dataList.add(data); cursor.moveToNext(); } } catch (Throwable t) { Log.e(TAG, "Error Reading data from Content Resolver", t); throw new RuntimeException(t); } finally { if (cursor != null && !cursor.isClosed()) { cursor.close(); } } return dataList; }
Source:
<code>public void constructorValidValues() { <START> AmqpAnnotatedMessage actual = new AmqpAnnotatedMessage(new AmqpDataBody(Collections.singletonList(new BinaryData(CONTENTS_BYTES)))); <END> Assertions.assertEquals(AmqpBodyType.DATA, actual.getBody().getBodyType()); Assertions.assertNotNull(actual.getProperties()); Assertions.assertNotNull(actual.getHeader()); Assertions.assertNotNull(actual.getFooter()); Assertions.assertNotNull(actual.getApplicationProperties()); Assertions.assertNotNull(actual.getDeliveryAnnotations()); Assertions.assertNotNull(actual.getMessageAnnotations()); Assertions.assertNotNull(actual.getApplicationProperties()); Assertions.assertNotNull(actual.getBody()); List<BinaryData> dataList = ((AmqpDataBody) actual.getBody()).getData().stream().collect(Collectors.toList()); assertEquals(1, dataList.size()); byte[] actualData = dataList.get(0).getData(); assertArrayEquals(CONTENTS_BYTES, actualData); }</code><technical_language>arrangement set of new operators. act creation of message</technical_language>

Target:
public void constructorValidValues() { final List<BinaryData> expectedBinaryData = Collections.singletonList(DATA_BYTES); final AmqpDataBody amqpDataBody = new AmqpDataBody(expectedBinaryData); final AmqpAnnotatedMessage actual = new AmqpAnnotatedMessage(amqpDataBody); assertMessageCreation(AmqpBodyType.DATA, expectedBinaryData.size(), actual); }
Source:
<code>private void validate(StatementsResponse readEntity, EntityKey key, Tuple tuple) { if (!readEntity.getErrors().isEmpty() ) { ErrorResponse errorResponse = readEntity.getErrors().get( 0 ); switch ( errorResponse.getCode() ) { <START> case EmbeddedNeo4jDialect.CONSTRAINT_VIOLATION_CODE: <END> throw extractException( key, tuple, errorResponse ); default: throw new HibernateException( String.valueOf( errorResponse ) ); } } }</code><technical_language>move constant a commonly place</technical_language>

Target:
private void validate(StatementsResponse readEntity, EntityKey key, Tuple tuple) { if (!readEntity.getErrors().isEmpty() ) { ErrorResponse errorResponse = readEntity.getErrors().get( 0 ); switch ( errorResponse.getCode() ) { case BaseNeo4jDialect.CONSTRAINT_VIOLATION_CODE: throw extractException( key, tuple, errorResponse ); default: throw new HibernateException( String.valueOf( errorResponse ) ); } } }
Source:
<code>public void initialize(Context context) { context.registerSyntaxNodeConsumer(Kind.ASSIGNMENT_STMT, ctx -> { AssignmentStatement assignment = (AssignmentStatement) ctx.syntaxNode(); getSubscriptionToCookies(assignment.lhsExpressions()) .forEach(sub -> { if (isSettingFlag(sub, flagName()) && isFalsy(assignment.assignedValue())) { ctx.addIssue(assignment, message()); } }); }); context.registerSyntaxNodeConsumer(Kind.CALL_EXPR, ctx -> { CallExpression callExpression = (CallExpression) ctx.syntaxNode(); Symbol calleeSymbol = callExpression.calleeSymbol(); if (calleeSymbol != null && sensitiveArgumentByFQN().containsKey(calleeSymbol.fullyQualifiedName())) { if (callExpression.arguments().stream().anyMatch(argument -> argument.is(Kind.UNPACKING_EXPR))) { return; } <START> RegularArgument secureArgument = getArgument(callExpression.arguments(), sensitiveArgumentByFQN().get(calleeSymbol.fullyQualifiedName()), flagName()); <END> if (secureArgument == null || isFalsy(secureArgument.expression())) { ctx.addIssue(callExpression.callee(), message()); } } }); }</code><technical_language>I forgot renaming variable name secureArgument while refactoring</technical_language>

Target:
public void initialize(Context context) { context.registerSyntaxNodeConsumer(Kind.ASSIGNMENT_STMT, ctx -> { AssignmentStatement assignment = (AssignmentStatement) ctx.syntaxNode(); getSubscriptionToCookies(assignment.lhsExpressions()) .forEach(sub -> { if (isSettingFlag(sub, flagName()) && isFalsy(assignment.assignedValue())) { ctx.addIssue(assignment, message()); } }); }); context.registerSyntaxNodeConsumer(Kind.CALL_EXPR, ctx -> { CallExpression callExpression = (CallExpression) ctx.syntaxNode(); Symbol calleeSymbol = callExpression.calleeSymbol(); if (calleeSymbol != null && sensitiveArgumentByFQN().containsKey(calleeSymbol.fullyQualifiedName())) { if (callExpression.arguments().stream().anyMatch(argument -> argument.is(Kind.UNPACKING_EXPR))) { return; } RegularArgument flagArgument = getArgument(callExpression.arguments(), sensitiveArgumentByFQN().get(calleeSymbol.fullyQualifiedName()), flagName()); if (flagArgument == null || isFalsy(flagArgument.expression())) { ctx.addIssue(callExpression.callee(), message()); } } }); }
Source:
<code>public GHDeployKey addDeployKey(String title, String key) throws IOException { return root.retrieve() <START> .method("POST") <END> .with("title", title) .with("key", key) .method("POST") .withUrlPath(getApiTailUrl("keys")) .to(GHDeployKey.class) .wrap(this); }</code><technical_language>redundant method("POST")</technical_language>

Target:
public GHDeployKey addDeployKey(String title, String key) throws IOException { return root.createRequest() .method("POST") .with("title", title) .with("key", key) .withUrlPath(getApiTailUrl("keys")) .fetch(GHDeployKey.class) .wrap(this); }
Source:
<code>public void testSerialization() throws IOException, ClassNotFoundException { <START> ByteArrayOutputStream bos = new ByteArrayOutputStream(); <END> ObjectOutputStream oos = new ObjectOutputStream(bos); Schema payload = new Schema.Parser() .parse("{\"type\":\"record\",\"name\":\"KeyValue\",\"namespace\":\"org.apache.avro\"," + "\"doc\":\"generic key value type\",\"fields\":[{\"name\":\"key\",\"type\":{\"type\":\"string\"," + "\"avro.java.string\":\"String\"},\"doc\":\"generic key type\"}," + "{\"name\":\"value\",\"type\":[\"null\",{\"type\":\"string\",\"avro.java.string\":\"String\"}]," + "\"doc\":\"generic value type\"}]}"); oos.writeObject(payload); oos.close(); ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bis); Schema sp = (Schema) ois.readObject(); assertEquals(payload, sp); ois.close(); }</code><technical_language>wrap try-with-resources. I is a test, I give a good example</technical_language>

Target:
public void testSerialization() throws IOException, ClassNotFoundException { try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); InputStream jsonSchema = getClass().getResourceAsStream("/SchemaBuilder.avsc")) { Schema payload = new Schema.Parser().parse(jsonSchema); oos.writeObject(payload); try (ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bis)) { Schema sp = (Schema) ois.readObject(); assertEquals(payload, sp); } } }
Source:
<code>private Map<String, String> convert(String prefix, Iterable value) { Map<String, String> map = new LinkedHashMap<String, String>(); <START> if (!value.iterator().hasNext()) { <END> map.put(prefix, ""); return map; } int i = 0; for (Object o : value) { map.putAll(this.convert(prefix + "[" + (i++) + "]", o)); } return map; }</code><technical_language>java Iterator iterator = value.iterator(); if (!iterator.hasNext()) { // ... } for (int i = 0; iterator.hasNext(); i++) { Object o = iterator.next(); // ... } is more effective</technical_language>

Target:
private Map<String, String> convert(String prefix, Iterable value) { Map<String, String> map = new LinkedHashMap<String, String>(); Iterator iterator = value.iterator(); if (!iterator.hasNext()) { map.put(prefix, ""); return map; } for (int i = 0; iterator.hasNext(); i++) { map.putAll(this.convert(prefix + "[" + i + "]", iterator.next())); } return map; }
Source:
<code>public KafkaSystemConsumer(Consumer<K, V> kafkaConsumer, String systemName, Config config, String clientId, KafkaSystemConsumerMetrics metrics, Clock clock) { super(metrics.registry(), clock, metrics.getClass().getName()); this.kafkaConsumer = kafkaConsumer; this.samzaConsumerMetrics = metrics; this.clientId = clientId; this.systemName = systemName; this.config = config; this.metricName = String.format("%s %s", systemName, clientId); this.fetchThresholdBytesEnabled = new KafkaConfig(config).isConsumerFetchThresholdBytesEnabled(systemName); <START> messageSink = new KafkaConsumerMessageSink(); <END> proxy = new KafkaConsumerProxy(kafkaConsumer, systemName, clientId, messageSink, samzaConsumerMetrics, metricName); LOG.info("Created consumer proxy: " + proxy); LOG.info("Created SamzaKafkaSystemConsumer for system={}, clientId={}, metricName={}, KafkaConsumer={}", systemName, clientId, metricName, this.kafkaConsumer.toString()); }</code><technical_language>this.messageSink consistently. for proxy</technical_language>

Target:
public KafkaSystemConsumer(Consumer<K, V> kafkaConsumer, String systemName, Config config, String clientId, KafkaSystemConsumerMetrics metrics, Clock clock) { super(metrics.registry(), clock, metrics.getClass().getName()); this.kafkaConsumer = kafkaConsumer; this.clientId = clientId; this.systemName = systemName; this.config = config; this.metrics = metrics; fetchThresholdBytesEnabled = new KafkaConfig(config).isConsumerFetchThresholdBytesEnabled(systemName); messageSink = new KafkaConsumerMessageSink(); String metricName = String.format("%s", systemName); proxy = new KafkaConsumerProxy(kafkaConsumer, systemName, clientId, messageSink, metrics, metricName); LOG.info("{}: Created KafkaConsumerProxy ", this, proxy); }
Source:
<code>private Set<File> findDotProjectFiles(List<File> files) { Set<File> result = new HashSet<File>(); for (File file : files) { if (file.isFile()) { while (file != null) { File f = new File(file.getParent() + File.separator + ".project"); <START> if (f.exists()) { <END> result.add(f); break; } file = file.getParentFile(); } } } return result; }</code><technical_language>f.isFile() is checks if .project a directory accidentally</technical_language>

Target:
private Set<File> findDotProjectFiles(List<File> files) { Set<File> result = new HashSet<File>(); for (File file : files) { if (file.isFile()) { while (file != null) { File f = new File(file.getParent() + File.separator + ".project"); if (f.isFile()) { result.add(f); break; } file = file.getParentFile(); } } } return result; }
Source:
<code>private void updateLocalWindowIfNeeded() { if (flowControlledBytes != 0) { int bytes = flowControlledBytes; flowControlledBytes = 0; write0(parentContext(), new DefaultHttp2WindowUpdateFrame(bytes).stream(stream)) <START> .addListener(WINDOW_UPDATE_FRAME_LISTENER); <END> writeDoneAndNoFlush = true; } }</code><technical_language>ChannelFuture attached child channel</technical_language>

Target:
private void updateLocalWindowIfNeeded() { if (flowControlledBytes != 0) { int bytes = flowControlledBytes; flowControlledBytes = 0; ChannelFuture future = write0(parentContext(), new DefaultHttp2WindowUpdateFrame(bytes).stream(stream)); if (future.isDone()) { windowUpdateFrameWriteComplete(future, AbstractHttp2StreamChannel.this); } else { future.addListener(windowUpdateFrameWriteListener); writeDoneAndNoFlush = true; } } }
Source:
<code><START> public void hoverClickAndViewRecipientPhotoOnTableCell(int questionBodyIndex, int tableRow, String urlRegex) throws Exception { <END> String idOfQuestionBody = "questionBody-" + questionBodyIndex; WebElement photoDiv = browser.driver.findElement(By.id(idOfQuestionBody)) .findElements(By.cssSelector(".dataTable tbody tr")) .get(tableRow) .findElements(By.cssSelector("td")) .get(2) .findElement(By.className("profile-pic-icon-hover")); Actions actions = new Actions(browser.driver); actions.moveToElement(photoDiv).build().perform(); waitForElementToAppear(By.cssSelector(".popover-content")); JavascriptExecutor jsExecutor = (JavascriptExecutor) browser.driver; jsExecutor.executeScript("document.getElementsByClassName('popover-content')[0]" + ".getElementsByTagName('a')[0].click();"); waitForElementToAppear(By.cssSelector(".popover-content > img")); AssertHelper.assertContainsRegex(urlRegex, browser.driver.findElements(By.cssSelector(".popover-content > img")) .get(0) .getAttribute("src")); jsExecutor.executeScript("document.getElementsByClassName('popover')[0].parentNode.removeChild(document.getElementsByClassName('popover')[0])"); }</code><technical_language>specific reason a separate function for this? I suggest creating a generic function takes in column number a parameter, functions call column number</technical_language>

Target:
public void hoverClickAndViewRecipientPhotoOnTableCell(int questionBodyIndex, int tableRow, String urlRegex) throws Exception { hoverClickAndViewPhotoOnTableCell(questionBodyIndex, tableRow, 2, urlRegex); }
Source:
<code>public synchronized void start() { <START> log.info("started"); <END> }</code><technical_language>start() effectively do nothing</technical_language>

Target:
public void start() { if (!lifecycleLock.canStart()) { throw new ISE("can't start."); } try { log.info("starting"); listenerExecutor = Execs.singleThreaded("CuratorDruidNodeDiscoveryProvider-ListenerExecutor"); log.info("started"); lifecycleLock.started(); } finally { lifecycleLock.exitStart(); } }
Source:
<code>protected void attemptSync() { <START> if (ConnectivityStatus.isNetworkNotConnected(CommCareHomeActivity.this)) { <END> if (ConnectivityStatus.isAirplaneModeOn(CommCareHomeActivity.this)) { displayMessage(Localization.get("notification.sync.airplane.action"), true, true); CommCareApplication._().reportNotificationMessage(NotificationMessageFactory.message(NotificationMessageFactory.StockMessages.Sync_AirplaneMode, AIRPLANE_MODE_CATEGORY)); } else { displayMessage(Localization.get("notification.sync.connections.action"), true, true); CommCareApplication._().reportNotificationMessage(NotificationMessageFactory.message(NotificationMessageFactory.StockMessages.Sync_NoConnections, AIRPLANE_MODE_CATEGORY)); } return; } CommCareApplication._().clearNotifications(AIRPLANE_MODE_CATEGORY); boolean formsSentToServer = checkAndStartUnsentTask(true); if(!formsSentToServer) { syncData(false); } }</code><technical_language>CommCareActivity isNetworkNotConnected() method, calls out a method in AndroidUtil. nice here, move isAirplaneModeOn() method AndroidUtil call in a similar way, need extra util class. of functionalities scattered a places in code right now. good try unified forward, eventually do a real pass eliminating duplicates</technical_language>

Target:
protected void attemptSync() { if (!ConnectivityStatus.isNetworkAvailable(CommCareHomeActivity.this)) { if (ConnectivityStatus.isAirplaneModeOn(CommCareHomeActivity.this)) { displayMessage(Localization.get("notification.sync.airplane.action"), true, true); CommCareApplication._().reportNotificationMessage(NotificationMessageFactory.message(NotificationMessageFactory.StockMessages.Sync_AirplaneMode, AIRPLANE_MODE_CATEGORY)); } else { displayMessage(Localization.get("notification.sync.connections.action"), true, true); CommCareApplication._().reportNotificationMessage(NotificationMessageFactory.message(NotificationMessageFactory.StockMessages.Sync_NoConnections, AIRPLANE_MODE_CATEGORY)); } return; } CommCareApplication._().clearNotifications(AIRPLANE_MODE_CATEGORY); boolean formsSentToServer = checkAndStartUnsentTask(true); if(!formsSentToServer) { syncData(false); } }
Source:
<code>private void handlePopulateWithDebugInfo() { if (debugPopulated) { return; } try { ((XText) getXWidget("Title")).set("tt"); if (atsAi == null) { <START> atsAi = AtsConfigCache.instance.getSoleByGuid("AAABER+4zV8A8O7WAtxxaA", IAtsActionableItem.class); <END> if (atsAi != null) { treeViewer.getViewer().setSelection(new StructuredSelection(Arrays.asList(atsAi))); treeViewer.setInitalChecked(Arrays.asList(atsAi)); } } getContainer().updateButtons(); debugPopulated = true; } catch (OseeCoreException ex) { OseeLog.log(Activator.class, OseeLevel.SEVERE_POPUP, ex); } }</code><technical_language>I assume this is for testing something? Is GUID in other places defined else? GUID.create() here</technical_language>

Target:
private void handlePopulateWithDebugInfo() { if (debugPopulated) { return; } try { ((XText) getXWidget("Title")).set("tt"); if (atsAi == null) { atsAi = AtsConfigCache.instance.getSoleByGuid(ATS_Actionable_Item_Guid_For_Training_And_Demos, IAtsActionableItem.class); if (atsAi != null) { treeViewer.getViewer().setSelection(new StructuredSelection(Arrays.asList(atsAi))); treeViewer.setInitalChecked(Arrays.asList(atsAi)); } } getContainer().updateButtons(); debugPopulated = true; } catch (OseeCoreException ex) { OseeLog.log(Activator.class, OseeLevel.SEVERE_POPUP, ex); } }
Source:
<code><START> public FileParts() { <END> }</code><technical_language>is public set fields if this class, weird a public constructor. I adding @since tags, this constructor private time fields private well. if find this limiting package-private fine well</technical_language>

Target:
private FileParts()
Source:
<code>public Long int64(String name) { Int64Field field = findField(name, Int64Field.class); if (field == null) { return null; } <START> int before = byteBuffer.position(); <END> Long decoded = (Long) field.decode(byteBuffer); int after = byteBuffer.position(); currentlyRead += (after - before); return decoded; }</code><technical_language>spin lines of code out reuse decoding methods</technical_language>

Target:
public Long int64(String name) { Int64Field field = fieldSearcher.nextField(name, Int64Field.class, null, structReadBuffer); if (field == null) { return null; } return (Long) field.decode(structReadBuffer); }
Source:
<code>private void addDeleteKeytab(Cluster cluster, Set<String> hostFilter, String hostParamsJson, CommandParams commandParameters, OrderedRequestStageContainer stageContainer) throws AmbariException { Set<String> hostNames = (CollectionUtils.isEmpty(hostFilter)) ? null : hostFilter.stream() .filter(hostname -> ambariManagementController.getClusters().hostExists(hostname)) .collect(toSet()); <START> if(!CollectionUtils.isEmpty(hostNames)) { <END> Stage stage = createNewStage(stageContainer.getLastStageId(), cluster, stageContainer.getId(), "Delete Keytabs", commandParameters.asJson(), hostParamsJson); Map<String, String> requestParams = new HashMap<>(); List<RequestResourceFilter> requestResourceFilters = new ArrayList<>(); RequestResourceFilter reqResFilter = new RequestResourceFilter("KERBEROS", "KERBEROS_CLIENT", new ArrayList<>(hostNames)); requestResourceFilters.add(reqResFilter); ActionExecutionContext actionExecContext = new ActionExecutionContext( cluster.getClusterName(), "REMOVE_KEYTAB", requestResourceFilters, requestParams); customCommandExecutionHelper.addExecutionCommandsToStage(actionExecContext, stage, requestParams, null); stageContainer.addStage(stage); } }</code><technical_language>nit: CollectionUtils.isNotEmpty(...)</technical_language>

Target:
private void addDeleteKeytab(Cluster cluster, Set<String> hostFilter, String hostParamsJson, CommandParams commandParameters, OrderedRequestStageContainer stageContainer) throws AmbariException { Set<String> hostNames = (CollectionUtils.isEmpty(hostFilter)) ? null : hostFilter.stream() .filter(hostname -> ambariManagementController.getClusters().hostExists(hostname)) .collect(toSet()); if(CollectionUtils.isNotEmpty(hostNames)) { Stage stage = createNewStage(stageContainer.getLastStageId(), cluster, stageContainer.getId(), "Delete Keytabs", commandParameters.asJson(), hostParamsJson); Map<String, String> requestParams = new HashMap<>(); List<RequestResourceFilter> requestResourceFilters = new ArrayList<>(); RequestResourceFilter reqResFilter = new RequestResourceFilter("KERBEROS", "KERBEROS_CLIENT", new ArrayList<>(hostNames)); requestResourceFilters.add(reqResFilter); ActionExecutionContext actionExecContext = new ActionExecutionContext( cluster.getClusterName(), REMOVE_KEYTAB, requestResourceFilters, requestParams); customCommandExecutionHelper.addExecutionCommandsToStage(actionExecContext, stage, requestParams, null); stageContainer.addStage(stage); } }
Source:
<code>public static void main(String[] args) { Config coordinatorSystemConfig = null; final String coordinatorSystemEnv = System.getenv(ShellCommandConfig.ENV_COORDINATOR_SYSTEM_CONFIG()); try { log.info("Parsing coordinator system config {}", coordinatorSystemEnv); coordinatorSystemConfig = new MapConfig(SamzaObjectMapper.getObjectMapper().readValue(coordinatorSystemEnv, Config.class)); } catch (IOException e) { log.error("Exception while reading coordinator stream config {}", e); throw new SamzaException(e); } ClusterBasedJobCoordinator jc = new ClusterBasedJobCoordinator(coordinatorSystemConfig); jc.run(); <START> log.info("Finishing"); <END> }</code><technical_language>log a more descriptive line here.</technical_language>

Target:
public static void main(String[] args) { Config coordinatorSystemConfig = null; final String coordinatorSystemEnv = System.getenv(ShellCommandConfig.ENV_COORDINATOR_SYSTEM_CONFIG()); try { log.info("Parsing coordinator system config {}", coordinatorSystemEnv); coordinatorSystemConfig = new MapConfig(SamzaObjectMapper.getObjectMapper().readValue(coordinatorSystemEnv, Config.class)); } catch (IOException e) { log.error("Exception while reading coordinator stream config {}", e); throw new SamzaException(e); } ClusterBasedJobCoordinator jc = new ClusterBasedJobCoordinator(coordinatorSystemConfig); jc.run(); log.info("Finished ClusterBasedJobCoordinator run"); }
Source:
<code><START> public void write(final File tabixFile) { <END> final LittleEndianOutputStream los = new LittleEndianOutputStream(new BlockCompressedOutputStream(tabixFile)); try { write(los); los.close(); } catch (final IOException e) { throw new TribbleException("Exception writing " + tabixFile.getAbsolutePath(), e); } }</code><technical_language>This a a try-with-resources. weird this throws a TribbleException other writes throw IOException. strangely inconsistent. widen throw IOException narrow TribbleException. I I lean throws IOException work. a breaking change for people calling write a tabix index though. @yfarjoun opinion</technical_language>

Target:
public void write(final File tabixFile) throws IOException { try(final LittleEndianOutputStream los = new LittleEndianOutputStream(new BlockCompressedOutputStream(tabixFile))) { write(los); } }
Source:
<code>public final void handlePacket(SeekableLittleEndianAccessor slea, MapleClient c) { slea.readInt(); int birthday = slea.readInt(); if (!CashOperationHandler.checkBirthday(c, birthday)) { c.announce(MaplePacketCreator.showCashShopMessage((byte) 0xC4)); c.announce(MaplePacketCreator.enableActions()); return; } MapleCharacter chr = c.getPlayer(); if(!ServerConstants.ALLOW_CASHSHOP_WORLD_TRANSFER || Server.getInstance().getWorldsSize() <= 1) { c.announce(MaplePacketCreator.sendWorldTransferRules(9, c)); return; } int worldTransferError = chr.checkWorldTransferEligibility(); if(worldTransferError != 0) { c.announce(MaplePacketCreator.sendWorldTransferRules(worldTransferError, c)); return; } try (Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT completionTime FROM worldtransfers WHERE characterid=?")) { ps.setInt(1, chr.getId()); ResultSet rs = ps.executeQuery(); while(rs.next()) { Timestamp completedTimestamp = rs.getTimestamp("completionTime"); if(completedTimestamp == null) { c.announce(MaplePacketCreator.sendWorldTransferRules(6, c)); return; } else if(completedTimestamp.getTime() + ServerConstants.WORLD_TRANSFER_COOLDOWN > System.currentTimeMillis()) { c.announce(MaplePacketCreator.sendWorldTransferRules(7, c)); return; }; } } catch(SQLException e) { e.printStackTrace(); } <START> c.announce(MaplePacketCreator.sendWorldTransferRules(0, c)); <END> }</code><technical_language>Exception call this</technical_language>

Target:
public final void handlePacket(SeekableLittleEndianAccessor slea, MapleClient c) { slea.readInt(); int birthday = slea.readInt(); if (!CashOperationHandler.checkBirthday(c, birthday)) { c.announce(MaplePacketCreator.showCashShopMessage((byte) 0xC4)); c.announce(MaplePacketCreator.enableActions()); return; } MapleCharacter chr = c.getPlayer(); if(!ServerConstants.ALLOW_CASHSHOP_WORLD_TRANSFER || Server.getInstance().getWorldsSize() <= 1) { c.announce(MaplePacketCreator.sendWorldTransferRules(9, c)); return; } int worldTransferError = chr.checkWorldTransferEligibility(); if(worldTransferError != 0) { c.announce(MaplePacketCreator.sendWorldTransferRules(worldTransferError, c)); return; } try (Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT completionTime FROM worldtransfers WHERE characterid=?")) { ps.setInt(1, chr.getId()); ResultSet rs = ps.executeQuery(); while(rs.next()) { Timestamp completedTimestamp = rs.getTimestamp("completionTime"); if(completedTimestamp == null) { c.announce(MaplePacketCreator.sendWorldTransferRules(6, c)); return; } else if(completedTimestamp.getTime() + ServerConstants.WORLD_TRANSFER_COOLDOWN > System.currentTimeMillis()) { c.announce(MaplePacketCreator.sendWorldTransferRules(7, c)); return; }; } } catch(SQLException e) { e.printStackTrace(); return; } c.announce(MaplePacketCreator.sendWorldTransferRules(0, c)); }
Source:
<code>@Test public void testProjectExceptWithMissingField() { final RelBuilder builder = RelBuilder.create(config().build()); builder.scan("EMP"); RexNode deptnoField = builder.field("DEPTNO"); assertThrows(CalciteException.class, () -> { <START> builder.project( <END> builder.field("EMPNO"), builder.field("ENAME")) .projectExcept(deptnoField); }, "Project should fail since we are trying to remove a field that does not exist."); }</code><technical_language>nice if check error message of Throwable</technical_language>

Target:
@Test public void testProjectExceptWithMissingField() { final RelBuilder builder = RelBuilder.create(config().build()); builder.scan("EMP"); RexNode deptnoField = builder.field("DEPTNO"); IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, () -> { builder.project( builder.field("EMPNO"), builder.field("ENAME")) .projectExcept(deptnoField); }, "Project should fail since we are trying to remove a field that does not exist."); assertThat(ex.getMessage(), allOf(containsString("Expression"), containsString("not found"))); }
Source:
<code>private void processInput(String userInput) { if (userInput.isEmpty()) return; String[] userInputWords = userInput.split(" "); for (int i = 0; i < userInputWords.length; i++) { String currentWord = userInputWords[i]; <START> if (i < userInputWords.length - 1 || userInput.endsWith(" ")) { <END> toggleMilestone(currentWord); } else { filterMilestones(currentWord); } } }</code><technical_language>Give this condition explanatory name. clear means</technical_language>

Target:
private void processInput(String userInput) { if (userInput.isEmpty()) return; String[] userInputWords = userInput.split(" "); Stream.of(userInputWords) .forEach(this::filterMilestones); toggleFirstMatchingMilestone(currentMilestonesList); }
Source:
<code>public DateTimeTag(){ String format = System.getProperty(SYSTEM_PROPERTY_DATE_FORMAT); if(format == null) { this.formatter = DEFAULT_FORMATTER; } else { try { this.formatter = DateTimeFormatter.ofPattern(format).withZone(ZoneId.systemDefault()); } catch (IllegalArgumentException e) { log.log(Level.WARNING, String.format("Can not use System Property %s=%s as dateformat, will fall back to default." + " Please see also java.time.format.DateTimeFormatter for the correct syntax", SYSTEM_PROPERTY_DATE_FORMAT, format) <START> , e); <END> this.formatter = DEFAULT_FORMATTER; } } }</code><technical_language>Is a reason, java.util.Logginginstead of org.slf4j logging? usage of String.format in combination logging odd me</technical_language>

Target:
public DateTimeTag(){ String format = System.getProperty(SYSTEM_PROPERTY_DATE_FORMAT); if(format == null) { this.formatter = DEFAULT_FORMATTER; } else { try { this.formatter = DateTimeFormatter.ofPattern(format).withZone(ZoneId.systemDefault()); } catch (IllegalArgumentException e) { LOG.log(Level.WARNING, String.format("Can not use System Property %s=%s as dateformat, will fall back to default." + " Please see also java.time.format.DateTimeFormatter for the correct syntax", SYSTEM_PROPERTY_DATE_FORMAT, format) , e); this.formatter = DEFAULT_FORMATTER; } } }
Source:
<code>public void testNodeJSAppIsRunning() { ExplorerItem indexJS = new ProjectExplorer().getProject(TEST_APP_NAME).getProjectItem("index.js"); indexJS.select(); runAsNodeJSAppMenu().select(); ConsoleView console = new ConsoleView(); console.activate(); new WaitUntil(new ConsoleHasText("Listening on port 3000")); assertTrue("Node.js App is not running!", <START> console.getConsoleText().contains("Listening on port 3000")); <END> console.terminateConsole(); }</code><technical_language>I this assert is redundant... If console text this point failed wait line 71</technical_language>

Target:
public void testNodeJSAppIsRunning() { ExplorerItem indexJS = new ProjectExplorer().getProject(TEST_APP_NAME).getProjectItem("index.js"); indexJS.select(); runAsNodeJSAppMenu().select(); ConsoleView console = new ConsoleView(); console.activate(); try { new WaitUntil(new ConsoleHasText("Listening on port 3000")); } catch (WaitTimeoutExpiredException e) { Assert.fail("Node.js App is not running!"); } console.terminateConsole(); }
Source:
<code>private void setPropertyIfMetadataPresent( Node node, String propertyName, Object value) throws RepositoryException { if (value != null) { if (value instanceof String && !StringUtil.isBlank((String) value)) { node.setProperty(propertyName, (String) value); } <START> if (value instanceof Long) { <END> node.setProperty(propertyName, (Long) value); } if (value instanceof Integer) { node.setProperty(propertyName, new Long((Integer) value)); } if (value instanceof byte[]) { InputStream is = new ByteArrayInputStream((byte []) value); Binary binaryProperty = (Binary) node.getSession().getValueFactory().createBinary(is); node.setProperty(propertyName, binaryProperty); } } }</code><technical_language>if a floating point (Double Float) change 2 instanceofs lines of: if (value instanceof Number) { setProperty(name, ((Number) value).longValue()) }</technical_language>

Target:
private void setPropertyIfMetadataPresent( Node node, String propertyName, Object value) throws RepositoryException { if (value != null) { if (value instanceof String && !StringUtil.isBlank((String) value)) { node.setProperty(propertyName, (String) value); } else if (value instanceof Double) { node.setProperty(propertyName, (Double) value); } else if (value instanceof Number) { node.setProperty(propertyName, ((Number) value).longValue()); } else if (value instanceof byte[]) { InputStream is = new ByteArrayInputStream((byte []) value); Binary binaryProperty = (Binary) node.getSession().getValueFactory().createBinary(is); node.setProperty(propertyName, binaryProperty); } else { throw new IllegalArgumentException(String.format("The value of the property %s has unknown type and couldn't be saved.", propertyName)); } } }
Source:
<code>default List<DocumentType> getSpecialDocumentTypes() { <START> return new ArrayList<>(); <END> }</code><technical_language>Collections#emptyList better</technical_language>

Target:
default Set<String> getSpecialDocumentTypes() { return Collections.emptySet(); }
Source:
<code>Double getDefaultElevation(CoverageInfo coverage, ReaderDimensionsAccessor dimensions) throws IOException { DimensionInfo elevation = coverage.getMetadata().get(ResourceInfo.ELEVATION, DimensionInfo.class); if (elevation == null || !coverage.isEnabled()) { throw new ServiceException("Layer " + coverage.getPrefixedName() + " does not have time support enabled"); } if (elevation.getDefaultValue() != null) { try { return Double.parseDouble(elevation.getDefaultValue()); } catch (NumberFormatException e) { <START> return dimensions.getMinElevation(); <END> } } else { return dimensions.getMinElevation(); } }</code><technical_language>In case of a mis-setup imho throw error, hide choice of default values. I this is debatable, a visible log statement inform admin. partial fail fast, however, this a topic of discussion devel ml</technical_language>

Target:
Double getDefaultElevation(CoverageInfo coverage, ReaderDimensionsAccessor dimensions) throws IOException { DimensionInfo elevationDimensionInfo = coverage.getMetadata().get(ResourceInfo.ELEVATION, DimensionInfo.class); if (elevationDimensionInfo == null || !coverage.isEnabled()) { throw new ServiceException("Layer " + coverage.getPrefixedName() + " does not have elevation support enabled"); } if (elevationDimensionInfo.getDefaultValue() != null) { Double defaultValue = null; try { defaultValue = Double.parseDouble(elevationDimensionInfo.getDefaultValue()); } catch (NumberFormatException e) { throw new ServiceException("Layer " + coverage.getPrefixedName() + " has an invalid elevation default value." + " " + DEFAULT_ELEVATION_NOT_DOUBLE_MSG); } boolean defaultValueIsInElevationDomain = false; Collection<Object> elevationDomain = dimensions.getElevationDomain(); if (elevationDomain != null && !elevationDomain.isEmpty()) { for (Object elevation : elevationDomain) { if (elevation instanceof Double) { if (((Double)elevation).compareTo(defaultValue) == 0) { defaultValueIsInElevationDomain = true; break; } } else if (elevation instanceof NumberRange) { if (((NumberRange)elevation).contains((Number)defaultValue)) { defaultValueIsInElevationDomain = true; break; } } } } if (!defaultValueIsInElevationDomain) { throw new ServiceException("Layer " + coverage.getPrefixedName() + " has an invalid elevation default value." + " " + DEFAULT_ELEVATION_NOT_IN_DOMAIN_MSG); } return defaultValue; } else { return dimensions.getMinElevation(); } }
Source:
<code>public synchronized void setLookupSource(Supplier<LookupSource> lookupSource) { requireNonNull(lookupSource, "lookupSource is null"); assertIn(State.UNSPILLING); <START> requireNonNull(unspilledLookupSource).set(lookupSource); <END> unspilledLookupSource = null; setState(State.PRODUCED); }</code><technical_language>change requireNonNull checkState(unspilledLookupSource != null, "unspilledLookupSource set").. is hard read a chained call, get a NullPointerException, this is a bad state</technical_language>

Target:
public synchronized void setLookupSource(Supplier<LookupSource> lookupSource) { requireNonNull(lookupSource, "lookupSource is null"); if (state == State.DISPOSED) { return; } assertState(State.UNSPILLING); checkState(unspilledLookupSource != null, "unspilledLookupSource not set"); unspilledLookupSource.set(lookupSource); unspilledLookupSource = null; setState(State.PRODUCED); }