auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void handleBitbucketCloudEvent(Event event, Map postedEvent) { String repoProject = ""; String slug = ""; String hash = ""; String branch = ""; BitbucketCloudEvent bitbucketCloudEvent = objectMapper.convertValue(postedEvent, BitbucketCloudEvent.class); if (bitbucketCloudEvent.repository != null) { slug = emptyOrDefault(bitbucketCloudEvent.repository.fullName, ""); if (bitbucketCloudEvent.repository.owner != null) { repoProject = emptyOrDefault(bitbucketCloudEvent.repository.owner.username, ""); } } if (bitbucketCloudEvent.pullRequest != null) { BitbucketCloudEvent.PullRequest pullRequest = bitbucketCloudEvent.pullRequest; if (pullRequest.mergeCommit != null) { hash = emptyOrDefault(pullRequest.mergeCommit.hash, ""); } if (pullRequest.destination != null && pullRequest.destination.branch != null) { branch = emptyOrDefault(pullRequest.destination.branch.name, ""); } } else if (bitbucketCloudEvent.push != null) { BitbucketCloudEvent.Push push = bitbucketCloudEvent.push; <START> if (push.changes.size() > 0) { <END> BitbucketCloudEvent.Change change = push.changes.get(0); if (change.newObj != null) { branch = emptyOrDefault(change.newObj.name, ""); } if (change.commits.size() > 0) { BitbucketCloudEvent.Commit commit = change.commits.get(0); hash = emptyOrDefault(commit.hash,""); } } } event.content.put("repoProject", repoProject); event.content.put("slug", slug); event.content.put("hash", hash); event.content.put("branch", branch); }</code><technical_language>Prefer isEmpty if checking for gt 0</technical_language>

Target:
private void handleBitbucketCloudEvent(Event event, Map postedEvent) { String repoProject = ""; String slug = ""; String hash = ""; String branch = ""; BitbucketCloudEvent bitbucketCloudEvent = objectMapper.convertValue(postedEvent, BitbucketCloudEvent.class); if (bitbucketCloudEvent.repository != null) { slug = emptyOrDefault(bitbucketCloudEvent.repository.fullName, ""); if (bitbucketCloudEvent.repository.owner != null) { repoProject = emptyOrDefault(bitbucketCloudEvent.repository.owner.username, ""); } } if (bitbucketCloudEvent.pullRequest != null) { BitbucketCloudEvent.PullRequest pullRequest = bitbucketCloudEvent.pullRequest; if (pullRequest.mergeCommit != null) { hash = emptyOrDefault(pullRequest.mergeCommit.hash, ""); } if (pullRequest.destination != null && pullRequest.destination.branch != null) { branch = emptyOrDefault(pullRequest.destination.branch.name, ""); } } else if (bitbucketCloudEvent.push != null) { BitbucketCloudEvent.Push push = bitbucketCloudEvent.push; if (!push.changes.isEmpty()) { BitbucketCloudEvent.Change change = push.changes.get(0); if (change.newObj != null) { branch = emptyOrDefault(change.newObj.name, ""); } if (!change.commits.isEmpty()) { BitbucketCloudEvent.Commit commit = change.commits.get(0); hash = emptyOrDefault(commit.hash,""); } } } event.content.put("repoProject", repoProject); event.content.put("slug", slug); event.content.put("hash", hash); event.content.put("branch", branch); }
Source:
<code>private void configWithValues(int maxCellTsPairsToExamine, int candidateBatchSize, int deleteBatchSize) { <START> adjustableConfig = AdjustableSweepBatchConfigSource.create(() -> new SweepBatchConfig() { <END> @Override public int maxCellTsPairsToExamine() { return maxCellTsPairsToExamine; } @Override public int candidateBatchSize() { return candidateBatchSize; } @Override public int deleteBatchSize() { return deleteBatchSize; } }); updatePreviousValues(); }</code><technical_language>ImmutableSweepBatchConfig.builder create sweepBatchConfig</technical_language>

Target:
private void configWithValues(int maxCellTsPairsToExamine, int candidateBatchSize, int deleteBatchSize) { adjustableConfig = AdjustableSweepBatchConfigSource.create(() -> ImmutableSweepBatchConfig.builder() .maxCellTsPairsToExamine(maxCellTsPairsToExamine) .candidateBatchSize(candidateBatchSize) .deleteBatchSize(deleteBatchSize) .build() ); updatePreviousValues(); }
Source:
<code><START> public Response cancelAction(@PathParam("id") String id) throws URISyntaxException { <END> IAtsUser asUser = atsApi.getUserService().getUserByAccountId(httpHeaders); IAtsWorkItem workItem = atsApi.getQueryService().getWorkItem(id); if (workItem.isInWork()) { Conditions.assertNotNull(workItem, "workItem can not be found"); if (asUser == null) { asUser = AtsCoreUsers.SYSTEM_USER; } ActionOperations ops = new ActionOperations(asUser, workItem, atsApi); ops.setActionAttributeByType(id, AttributeKey.State.name(), Arrays.asList("Cancelled")); } String htmlUrl = atsApi.getWorkItemService().getHtmlUrl(workItem, atsApi); return Response.temporaryRedirect(new URI(htmlUrl)).build(); }</code><technical_language>throwing specific exceptions this level</technical_language>

Target:
public Response cancelAction(@PathParam("id") String id) { IAtsUser asUser = atsApi.getUserService().getUserByAccountId(httpHeaders); IAtsWorkItem workItem = atsApi.getQueryService().getWorkItem(id); if (workItem.isInWork()) { Conditions.assertNotNull(workItem, "workItem can not be found"); if (asUser == null) { asUser = AtsCoreUsers.SYSTEM_USER; } ActionOperations ops = new ActionOperations(asUser, workItem, atsApi); ops.setActionAttributeByType(id, AttributeKey.State.name(), Arrays.asList("Cancelled")); } String htmlUrl = atsApi.getWorkItemService().getHtmlUrl(workItem, atsApi); try { return Response.temporaryRedirect(new URI(htmlUrl)).build(); } catch (Exception ex) { throw new OseeWrappedException(ex); } }
Source:
<code>private <V> List<V> runAllTasksCancelOnFailure(List<Callable<V>> tasks) { if (tasks.size() == 1) { try { return Collections.singletonList(tasks.get(0).call()); } catch (Exception e) { throw Throwables.throwUncheckedException(e); } } List<Future<V>> futures = Lists.newArrayListWithCapacity(tasks.size()); for (Callable<V> task : tasks) { futures.add(executor.submit(task)); } try { List<V> results = Lists.newArrayListWithCapacity(tasks.size()); for (Future<V> future : futures) { results.add(future.get()); } return results; } catch (ExecutionException e) { <START> throw Throwables.throwUncheckedException(e.getCause()); <END> } catch (Exception e) { throw Throwables.throwUncheckedException(e); } finally { for (Future<V> future : futures) { future.cancel(true); } } }</code><technical_language>other places in this class (e.g. getRowsForSingleHost, getRowsColumnRangeForSingleHost, runAllTasksCancelOnFailure line 2424) want unwrap get more streamlined cause, worth adding %s/Throwables.throwUncheckedException/Throwables.unwrapAndThrowUncheckedException/g in here: public static RuntimeException unwrapAndThrowUncheckedException(Throwable e) { if (e instanceof ExecutionException || e instanceof InvocationTargetException) { throw Throwables.throwUncheckedException(e.getCause()); } throw Throwables.throwUncheckedException(e); }</technical_language>

Target:
private <V> List<V> runAllTasksCancelOnFailure(List<Callable<V>> tasks) { if (tasks.size() == 1) { try { return Collections.singletonList(tasks.get(0).call()); } catch (Exception e) { throw Throwables.unwrapAndThrowUncheckedException(e); } } List<Future<V>> futures = Lists.newArrayListWithCapacity(tasks.size()); for (Callable<V> task : tasks) { futures.add(executor.submit(task)); } try { List<V> results = Lists.newArrayListWithCapacity(tasks.size()); for (Future<V> future : futures) { results.add(future.get()); } return results; } catch (Exception e) { throw Throwables.unwrapAndThrowUncheckedException(e); } finally { for (Future<V> future : futures) { future.cancel(true); } } }
Source:
<code>public Boolean visitScope(Scope scope) { Provider<ScopeCleanupMarker> scopedMarkerProvider = scope.scope(Key.get(ScopeCleanupMarker.class), markerProvider); ManagedInstanceAction instanceAction = new ManagedInstanceAction(injectee, lifecycleActions); ScopeCleanupMarker marker = scopedMarkerProvider.get(); Integer markerKey = System.identityHashCode(marker); synchronized(scopedCleanupActions) { <START> if (scopedCleanupActions.containsKey(markerKey)) { <END> scopedCleanupActions.get(markerKey).add(scopedMarkerProvider, instanceAction); } else { scopedCleanupActions.put(markerKey, new ScopeCleanupAction(markerKey, scopedMarkerProvider, marker, markerReferenceQueue, instanceAction)); } } return true; }</code><technical_language>Java8 start map#compute</technical_language>

Target:
public Boolean visitScope(Scope scope) { Provider<ScopeCleanupMarker> scopedMarkerProvider = scope.scope(MARKER_KEY, markerProvider); ManagedInstanceAction instanceAction = new ManagedInstanceAction(injectee, lifecycleActions); ScopeCleanupMarker marker = scopedMarkerProvider.get(); UUID markerKey = marker.getId(); synchronized(scopedCleanupActions) { if (scopedCleanupActions.containsKey(markerKey)) { scopedCleanupActions.get(markerKey).add(scopedMarkerProvider, instanceAction); } else { scopedCleanupActions.put(markerKey, new ScopeCleanupAction(markerKey, scopedMarkerProvider, marker, markerReferenceQueue, instanceAction)); } } return true; }
Source:
<code>public long deleteAll(Iterator<ObjectId> ids) { long count = 0; <START> while (ids.hasNext()) { <END> if (delete(ids.next())) count += 1; } return count; }</code><technical_language>is a in mongo do bulk deletes</technical_language>

Target:
public long deleteAll(Iterator<ObjectId> ids) { Iterator<List<ObjectId>> chunks = Iterators.partition(ids, 500); long count = 0; while (chunks.hasNext()) { count += deleteChunk(chunks.next()); } return count; }
Source:
<code>protected abstract PollingResult checkForChanges(Job<?, ?> project) throws IOException, InterruptedException; public boolean checkout(Run<?, ?> build, Launcher launcher, FilePath jenkinsWorkspace, TaskListener listener, File changelogFile) throws IOException, InterruptedException { setup(launcher, jenkinsWorkspace, listener); if(server.isServerDisabled()){ listener.fatalError("Checkout skipped due to server disabled!"); <START> throw new InterruptedException(); <END> } if (StringUtils.isEmpty(scm.getDepot())) { throw new IllegalStateException("Must specify a depot"); } if (StringUtils.isEmpty(scm.getStream())) { throw new IllegalStateException("Must specify a stream"); } final EnvVars environment = build.getEnvironment(listener); accurevEnv.putAll(environment); localStream = environment.expand(scm.getStream()); listener.getLogger().println("Getting a list of streams..."); final Map<String, AccurevStream> streams = ShowStreams.getStreams(scm, localStream, server, accurevEnv, jenkinsWorkspace, listener, launcher); if (streams == null) { throw new IllegalStateException("Stream(s) not found"); } if (!streams.containsKey(localStream)) { listener.fatalError("The specified stream, '" + localStream + "' does not appear to exist!"); throw new IllegalStateException("Specified stream not found"); } if (server.isUseColor()) { setStreamColor(); } return checkout(build, changelogFile) && populate(build) && captureChangeLog(build, changelogFile, streams); }</code><technical_language>Please put a message interrupted exception</technical_language>

Target:
protected abstract PollingResult checkForChanges(Job<?, ?> project) throws IOException, InterruptedException; public boolean checkout(Run<?, ?> build, Launcher launcher, FilePath jenkinsWorkspace, TaskListener listener, File changelogFile) throws IOException, InterruptedException { setup(launcher, jenkinsWorkspace, listener); if(server.isServerDisabled()){ listener.fatalError("Checkout skipped due to server disabled!"); throw new InterruptedException("Checkout skipped"); } if (StringUtils.isEmpty(scm.getDepot())) { throw new IllegalStateException("Must specify a depot"); } if (StringUtils.isEmpty(scm.getStream())) { throw new IllegalStateException("Must specify a stream"); } final EnvVars environment = build.getEnvironment(listener); accurevEnv.putAll(environment); localStream = environment.expand(scm.getStream()); listener.getLogger().println("Getting a list of streams..."); final Map<String, AccurevStream> streams = ShowStreams.getStreams(scm, localStream, server, accurevEnv, jenkinsWorkspace, listener, launcher); if (streams == null) { throw new IllegalStateException("Stream(s) not found"); } if (!streams.containsKey(localStream)) { listener.fatalError("The specified stream, '" + localStream + "' does not appear to exist!"); throw new IllegalStateException("Specified stream not found"); } if (server.isUseColor()) { setStreamColor(); } return checkout(build, changelogFile) && populate(build) && captureChangeLog(build, changelogFile, streams); }
Source:
<code>protected String executeSingle(ResourceBundle language, String[] labelFragments, Command command) throws InterpretationException { ArrayList<Item> items = getMatchingItems(language, labelFragments, command.getClass()); if (items.size() < 1) { throw new InterpretationException(language.getString("no_objects")); } else if (items.size() > 1) { throw new InterpretationException(language.getString("multiple_objects")); } else { Item item = items.get(0); if (command instanceof State) { try { State newState = (State) command; State oldState = item.getStateAs(newState.getClass()); if (oldState.equals(newState)) { String template = language.getString("state_already_singular"); String cmdName = "state_" + command.toString().toLowerCase(); String stateText = null; try { stateText = language.getString(cmdName); } catch (Exception e) { <START> stateText = language.getString("state_current"); <END> } return template.replace("<state>", stateText); } } catch (Exception ex) { logger.debug("Failed constructing response: {}", ex.getMessage()); return language.getString(ERROR); } } eventPublisher.post(ItemEventFactory.createCommandEvent(item.getName(), command)); return language.getString(OK); } }</code><technical_language>For error a new const created above, for state_current magic variable is here</technical_language>

Target:
protected String executeSingle(ResourceBundle language, String[] labelFragments, Command command) throws InterpretationException { ArrayList<Item> items = getMatchingItems(language, labelFragments, command.getClass()); if (items.size() < 1) { throw new InterpretationException(language.getString(NO_OBJECTS)); } else if (items.size() > 1) { throw new InterpretationException(language.getString(MULTIPLE_OBJECTS)); } else { Item item = items.get(0); if (command instanceof State) { try { State newState = (State) command; State oldState = item.getStateAs(newState.getClass()); if (oldState.equals(newState)) { String template = language.getString(STATE_ALREADY_SINGULAR); String cmdName = "state_" + command.toString().toLowerCase(); String stateText = null; try { stateText = language.getString(cmdName); } catch (Exception e) { stateText = language.getString(STATE_CURRENT); } return template.replace("<state>", stateText); } } catch (Exception ex) { logger.debug("Failed constructing response: {}", ex.getMessage()); return language.getString(ERROR); } } eventPublisher.post(ItemEventFactory.createCommandEvent(item.getName(), command)); return language.getString(OK); } }
Source:
<code>public Map<String, Object> moveStudyFolder(final HttpServletRequest req) { final String sourceId = req.getParameter("sourceId"); final String targetId = req.getParameter("targetId"); final Map<String, Object> resultsMap = new HashMap<>(); try { final GermplasmList gpList = this.germplasmListManager.getGermplasmListById(Integer.parseInt(sourceId)); <START> if (targetId != null && PROGRAM_LISTS.equals(targetId) && CROP_LISTS.equals(targetId)) { <END> final GermplasmList parent = this.germplasmListManager.getGermplasmListById(Integer.parseInt(targetId)); gpList.setParent(parent); } else { gpList.setParent(null); } if (CROP_LISTS.equals(targetId)) { gpList.setProgramUUID(null); } else { gpList.setProgramUUID(this.contextUtil.getCurrentProgramUUID()); } this.germplasmListManager.updateGermplasmList(gpList); } catch (final Exception e) { GermplasmTreeController.LOG.error(e.getMessage(), e); } return resultsMap; }</code><technical_language>Create tests for **moveStudyFolder** method</technical_language>

Target:
public Map<String, Object> moveStudyFolder(final HttpServletRequest req) { final String sourceId = req.getParameter("sourceId"); final String targetId = req.getParameter("targetId"); final Map<String, Object> resultsMap = new HashMap<>(); try { final GermplasmList gpList = this.germplasmListManager.getGermplasmListById(Integer.parseInt(sourceId)); if (targetId == null || PROGRAM_LISTS.equals(targetId) || CROP_LISTS.equals(targetId)) { gpList.setParent(null); } else { final GermplasmList parent = this.germplasmListManager.getGermplasmListById(Integer.parseInt(targetId)); gpList.setParent(parent); } if (CROP_LISTS.equals(targetId)) { gpList.setProgramUUID(null); } else { gpList.setProgramUUID(this.contextUtil.getCurrentProgramUUID()); } this.germplasmListManager.updateGermplasmList(gpList); } catch (final Exception e) { GermplasmTreeController.LOG.error(e.getMessage(), e); } return resultsMap; }
Source:
<code>public void writeBatchScores(final List<AggregateScore> scores) { final List<WriteRequest> scoreList = new ArrayList<>(); <START> for (final AggregateScore score : scores) { <END> LOGGER.debug("Batch: {}, {}, {}", score.accountId, score.date, score.score); final HashMap<String, AttributeValue> item = new HashMap<>(); item.put(ACCOUNT_ID_ATTRIBUTE_NAME, new AttributeValue().withN(String.valueOf(score.accountId))); item.put(DATE_ATTRIBUTE_NAME, new AttributeValue().withS(score.date)); item.put(SCORE_ATTRIBUTE_NAME, new AttributeValue().withN(String.valueOf(score.score))); item.put(MESSAGE_ATTRIBUTE_NAME, new AttributeValue().withS(score.message)); item.put(TYPE_ATTRIBUTE_NAME, new AttributeValue().withS(score.scoreType)); item.put(VERSION_ATTRIBUTE_NAME, new AttributeValue().withS(score.version)); scoreList.add(new WriteRequest().withPutRequest(new PutRequest().withItem(item))); } Map<String, List<WriteRequest>> requestItems = new HashMap<>(); requestItems.put(this.tableName, scoreList); BatchWriteItemResult result; final BatchWriteItemRequest batchWriteItemRequest = new BatchWriteItemRequest(); do { batchWriteItemRequest.withRequestItems(requestItems); result = this.dynamoDBClient.batchWriteItem(batchWriteItemRequest); requestItems = result.getUnprocessedItems(); LOGGER.debug("Unprocessed put request count {}", requestItems.size()); } while (result.getUnprocessedItems().size() > 0); }</code><technical_language>If split settings attributes making request, duplicate code</technical_language>

Target:
public void writeBatchScores(final List<AggregateScore> scores) { final List<WriteRequest> scoreList = new ArrayList<>(); for (final AggregateScore score : scores) { LOGGER.debug("Batch: {}, {}, {}", score.accountId, score.date, score.score); final HashMap<String, AttributeValue> item = this.createItem(score); scoreList.add(new WriteRequest().withPutRequest(new PutRequest().withItem(item))); } Map<String, List<WriteRequest>> requestItems = new HashMap<>(); requestItems.put(this.tableName, scoreList); BatchWriteItemResult result; final BatchWriteItemRequest batchWriteItemRequest = new BatchWriteItemRequest(); do { batchWriteItemRequest.withRequestItems(requestItems); result = this.dynamoDBClient.batchWriteItem(batchWriteItemRequest); requestItems = result.getUnprocessedItems(); LOGGER.debug("Unprocessed put request count {}", requestItems.size()); } while (result.getUnprocessedItems().size() > 0); }
Source:
<code>private String getCrumb(String baseUrl, String token) throws Exception{ final String crumbUrl = baseUrl + "/crumbIssuer/api/xml?xpath=concat( final int maxRetries = 3; final int sleepRetryMS = 3000; for( int retry = 0; retry < maxRetries; ++retry ) { try { final HttpURLConnection connection = setupConnection(crumbUrl, token); connection.connect(); final int status = connection.getResponseCode(); if (status == 200) { return new BufferedReader(new InputStreamReader((connection.getInputStream()))).readLine(); } else { <START> if( retry+1 < maxRetries ) { <END> logger.warn("Could not connect to " + baseUrl + ", got HTTP status " + status + " will retry in " + sleepRetryMS + "ms"); } else { return null; } } } catch(final Exception e) { if( retry+1 < maxRetries ) { logger.warn("Could not connect to " + baseUrl + ", will retry in " + sleepRetryMS + "ms", e); } else { throw e; } } Thread.sleep(sleepRetryMS); } return null; }</code><technical_language>a mix of tabs spaces for indentation here. please convert indents tabs match rest of file? a bit difficult read github mix</technical_language>

Target:
private String getCrumb(String baseUrl, String token) throws Exception{ final String crumbUrl = baseUrl + "/crumbIssuer/api/xml?xpath=concat( final int maxRetries = 3; final int sleepRetryMS = 3000; for( int retry = 1; retry <= maxRetries; ++retry ) { try { final HttpURLConnection connection = setupConnection(crumbUrl, token); connection.connect(); final int status = connection.getResponseCode(); if (status == 200) { return new BufferedReader(new InputStreamReader((connection.getInputStream()))).readLine(); } else { logger.warn("Could not connect to " + baseUrl + ", got HTTP status " + status + "."); return null; } } catch(final SSLException e) { if( retry < maxRetries ) { logger.warn("Could not connect to " + baseUrl + ", will retry in " + sleepRetryMS + "ms", e); } else { throw e; } } Thread.sleep(sleepRetryMS); } return null; }
Source:
<code>public List<OrderGroup> getOrderGroupsByPatient(Patient patient) { Criteria criteria = sessionFactory.getCurrentSession().createCriteria(OrderGroup.class); if (patient != null) { criteria.add(Restrictions.eq("patient", patient)); } else{ <START> criteria.add(Restrictions.isNull("patient")); <END> } return criteria.list(); }</code><technical_language>order group a patient</technical_language>

Target:
public List<OrderGroup> getOrderGroupsByPatient(Patient patient) throws APIException { if (patient == null) { throw new APIException("Patient cannot be null"); } Criteria criteria = sessionFactory.getCurrentSession().createCriteria(OrderGroup.class); criteria.add(Restrictions.eq("patient", patient)); return criteria.list(); }
Source:
<code>static Mono<Object> decode(HttpResponse httpResponse, SerializerAdapter serializer, HttpResponseDecodeData decodeData) { Type headerType = decodeData.getHeadersType(); if (headerType == null) { return Mono.empty(); } else { return Mono.defer(() -> { try { return Mono.justOrEmpty(deserializeHeaders(httpResponse.getHeaders(), serializer, decodeData)); } catch (IOException e) { return Mono.error(new HttpResponseException( <START> "HTTP response has malformed headers", httpResponse, e)); <END> } }); } }</code><technical_language>suggestion "HTTP response malformed headers.", httpResponse, e));</technical_language>

Target:
static Mono<Object> decode(HttpResponse httpResponse, SerializerAdapter serializer, HttpResponseDecodeData decodeData) { Type headerType = decodeData.getHeadersType(); if (headerType == null) { return Mono.empty(); } else { return Mono.fromCallable(() -> serializer.deserialize(httpResponse.getHeaders(), decodeData.getHeadersType())) .onErrorResume(IOException.class, e -> Mono.error(new HttpResponseException( "HTTP response has malformed headers", httpResponse, e))); } }
Source:
<code>private static String getMetastoreJdbcPasswd(HiveConf conf) { try { return ShimLoader.getHadoopShims().getPassword(conf, HiveConf.ConfVars.METASTOREPWD.varname); } catch (IOException io) { <START> } <END> return null; }</code><technical_language>this throwing exception</technical_language>

Target:
private static String getMetastoreJdbcPasswd(HiveConf conf) throws IOException { return ShimLoader.getHadoopShims().getPassword(conf, HiveConf.ConfVars.METASTOREPWD.varname); }
Source:
<code>public void shouldUpdateSourceTopicsWithNewMatchingTopic() { topology.addSource("source-1", "topic-1"); final ProcessorTopology processorTopology = topology.getInternalBuilder("X").buildTopology(); assertNull(processorTopology.source("topic-2")); processorTopology.updateSourceTopics(Collections.singletonMap("source-1", asList("topic-1", "topic-2"))); <START> assertThat(processorTopology.source("topic-2"), instanceOf(SourceNode.class)); <END> }</code><technical_language>verify name of processorTopology.source("topic-2") source-1</technical_language>

Target:
public void shouldUpdateSourceTopicsWithNewMatchingTopic() { topology.addSource("source-1", "topic-1"); final ProcessorTopology processorTopology = topology.getInternalBuilder("X").buildTopology(); assertNull(processorTopology.source("topic-2")); processorTopology.updateSourceTopics(Collections.singletonMap("source-1", asList("topic-1", "topic-2"))); assertThat(processorTopology.source("topic-2").name(), equalTo("source-1")); }
Source:
<code>private void validateContent(JSONObject payloadObject, String schemaString, MessageContext messageContext) { logger.debug("Validating JSON content against the schema"); String finalMessage = ""; List<String> errorMessages; JSONObject jsonSchema = new JSONObject(schemaString); Schema schema = SchemaLoader.load(jsonSchema); if (schema == null) { return; } try { schema.validate(payloadObject); } catch (ValidationException e) { errorMessages = e.getAllMessages(); for (String message : errorMessages) { <START> finalMessage += message + ", "; <END> } if (messageContext.isResponse()) { logger.error("Schema validation failed in the Response :" + e.getMessage(), e); GatewayUtils.handleThreat(messageContext, APIMgtGatewayConstants.INTERNAL_ERROR_CODE, "Schema validation failed in the Response :" + finalMessage); } else { logger.error("Schema validation failed in the Request :" + e.getMessage(), e); GatewayUtils.handleThreat(messageContext, APIMgtGatewayConstants.HTTP_SC_CODE, "Schema validation failed in the Request :" + finalMessage); } } }</code><technical_language>string builders</technical_language>

Target:
private void validateContent(JSONObject payloadObject, String schemaString, MessageContext messageContext) { logger.debug("Validating JSON content against the schema"); StringBuilder finalMessage = new StringBuilder(); List<String> errorMessages; JSONObject jsonSchema = new JSONObject(schemaString); Schema schema = SchemaLoader.load(jsonSchema); if (schema == null) { return; } try { schema.validate(payloadObject); } catch (ValidationException e) { errorMessages = e.getAllMessages(); for (String message : errorMessages) { finalMessage.append(message).append(", "); } if (messageContext.isResponse()) { String message = "Schema validation failed in the Response: "; logger.error(message + e.getMessage(), e); GatewayUtils.handleThreat(messageContext, APIMgtGatewayConstants.INTERNAL_ERROR_CODE, message + finalMessage); } else { String errMessage = "Schema validation failed in the Request: "; logger.error(errMessage + e.getMessage(), e); GatewayUtils.handleThreat(messageContext, APIMgtGatewayConstants.HTTP_SC_CODE, errMessage + finalMessage); } } }
Source:
<code>public InputStream call(InputStream endpointState, SessionState session, InputStream workUnit, InputStream[] input) { newCallContext().withEndpointState(endpointState).withSessionState(session) .withWorkUnit(workUnit); <START> return call(newCallContext(), input); <END> }</code><technical_language>call line 61 call context constructed line 59. Currently, constructed call context is thrown away, parameters passed in call. equivalent refactoring in InputOutputEndpointImpl is correct</technical_language>

Target:
public InputStream call(InputStream endpointState, SessionState session, InputStream workUnit, InputStream[] input) { CallContext callContext = newCallContext().withEndpointState(endpointState).withSessionState(session) .withWorkUnit(workUnit); return call(callContext, input); }
Source:
<code>private static void triggerSecureStorageOfPasswordInConnectionDialog(String username, String server, boolean storePassword, ServerType serverType) { OpenShiftExplorerView explorer = new OpenShiftExplorerView(); AbstractOpenShiftConnection connection = explorer.getOpenShiftConnection(username, server, serverType); connection.select(); if (ServerType.OPENSHIFT_2.equals(serverType)) { waitForLoadingConnectionDetails(connection); } new ContextMenu(OpenShiftLabel.ContextMenu.EDIT_CONNECTION).select(); new DefaultShell(OpenShiftLabel.Shell.EDIT_CONNECTION); if (!(new CheckBox(1).isChecked()) && storePassword) { new CheckBox(1).click(); new FinishButton().click(); acceptSSLCertificate(); boolean firstStorage = provideSecureStoragePassword(SystemProperties.SECURE_STORAGE_PASSWORD); if (firstStorage) { try { new DefaultShell(OpenShiftLabel.Shell.PASSWORD_HINT_NEEDED); new NoButton().click(); <START> } catch (SWTLayerException ex) { <END> } new DefaultShell(OpenShiftLabel.Shell.SECURE_STORAGE).setFocus(); new NoButton().click(); } } else if (new CheckBox(1).isChecked() && !storePassword) { new CheckBox(1).click(); new FinishButton().click(); } new WaitWhile(new JobIsRunning()); }</code><technical_language>![MAJOR](<LINK_1> log rethrow this exception. [![rule](<LINK_2>](<LINK_0></technical_language>

Target:
private static void triggerSecureStorageOfPasswordInConnectionDialog(String username, String server, boolean storePassword, ServerType serverType) { OpenShiftExplorerView explorer = new OpenShiftExplorerView(); AbstractOpenShiftConnection connection = explorer.getOpenShiftConnection(username, server, serverType); connection.select(); if (ServerType.OPENSHIFT_2.equals(serverType)) { waitForLoadingConnectionDetails(connection); } new ContextMenu(OpenShiftLabel.ContextMenu.EDIT_CONNECTION).select(); new DefaultShell(OpenShiftLabel.Shell.EDIT_CONNECTION); if (!(new CheckBox(1).isChecked()) && storePassword) { new CheckBox(1).click(); new FinishButton().click(); acceptSSLCertificate(); boolean firstStorage = provideSecureStoragePassword(SystemProperties.SECURE_STORAGE_PASSWORD); if (firstStorage) { try { new DefaultShell(OpenShiftLabel.Shell.PASSWORD_HINT_NEEDED); new NoButton().click(); } catch (SWTLayerException ex) { LOGGER.debug("Password hint did not appear. Skipping."); } } } else if (new CheckBox(1).isChecked() && !storePassword) { new CheckBox(1).click(); new FinishButton().click(); } new WaitWhile(new JobIsRunning()); }
Source:
<code>public ForumBoardPageObject openForumBoard() { WebElement forumBoardLink = null; <START> found: <END> for(int i = 0; i < getForumElementsList().size(); i++) { if(!getForumElementsList().get(i).toString().contains("%")) { forumBoardLink = getForumElementsList().get(i); break found; } } waitForElementByElement(forumBoardLink); waitForElementClickableByElement(forumBoardLink); scrollAndClick(forumBoardLink); PageObjectLogging.log("openForumBoard", "click on the forum Board", true, driver); return new ForumBoardPageObject(driver); }</code><technical_language>remove: "found:", replace "break found;" with: "break;" Jump-out labels</technical_language>

Target:
public ForumBoardPageObject openForumBoard() { WebElement forumBoardLink = null; for(int i = 0; i < getForumElementsList().size(); i++) { if(!getForumElementsList().get(i).toString().contains("%")) { forumBoardLink = getForumElementsList().get(i); break; } } waitForElementByElement(forumBoardLink); waitForElementClickableByElement(forumBoardLink); scrollAndClick(forumBoardLink); PageObjectLogging.log("openForumBoard", "click on the forum Board", true, driver); return new ForumBoardPageObject(driver); }
Source:
<code><START> protected void searchAndLaunch(final Object[] elements, String mode) { <END> if (elements[0] instanceof IResource) { ICElement cElement = CoreModel.getDefault().create( (IResource) elements[0]); if (cElement != null) { super.searchAndLaunch(new Object[] { cElement }, mode); return; } } super.searchAndLaunch(elements, mode); }</code><technical_language>need check 'elements' is null element</technical_language>

Target:
protected void searchAndLaunch(final Object[] elements, String mode) { if (elements == null || elements.length == 0) { return; } if (elements[0] instanceof IResource) { ICElement cElement = CoreModel.getDefault().create( (IResource) elements[0]); if (cElement != null) { super.searchAndLaunch(new Object[] { cElement }, mode); return; } } super.searchAndLaunch(elements, mode); }
Source:
<code>public void testRegistryUrlNotFoundDialog() { <START> String shellTitle = OpenShiftLabel.Shell.REGISTRY_URL_NOT_FOUND; <END> wizard.getImageRegistryUrl().setText(""); wizard.finish(); stopServerAdapter(); wizard = getOpenshiftConnectionWizard(findOpenShiftConnection(null, OPENSHIFT_USERNAME)); switchOffPasswordSaving(wizard); try { wizard.discover(); fail("Expected OpenshiftToolsException was not thrown, possibly no dialog is shown."); } catch (OpenShiftToolsException osExc) { assertTrue("Registry URL not found dialog did not appear.", osExc.getMessage().contains(shellTitle)); new WaitUntil(new ShellIsAvailable(shellTitle), TimePeriod.SHORT); new DefaultShell(shellTitle); new OkButton().click(); } wizard.cancel(); }</code><technical_language>@odockal I variable for shell title, easier readable code</technical_language>

Target:
public void testRegistryUrlNotFoundDialog() { wizard.getImageRegistryUrl().setText(""); wizard.finish(); stopServerAdapter(); wizard = getOpenshiftConnectionWizard(findOpenShiftConnection(null, OPENSHIFT_USERNAME)); switchOffPasswordSaving(wizard); try { wizard.discover(); fail("Expected OpenshiftToolsException was not thrown, possibly no dialog is shown."); } catch (OpenShiftToolsException osExc) { assertTrue("Registry URL not found dialog did not appear.", osExc.getMessage().contains(OpenShiftLabel.Shell.REGISTRY_URL_NOT_FOUND)); new WaitUntil(new ShellIsAvailable(OpenShiftLabel.Shell.REGISTRY_URL_NOT_FOUND), TimePeriod.SHORT); new DefaultShell(OpenShiftLabel.Shell.REGISTRY_URL_NOT_FOUND); new OkButton().click(); } wizard.cancel(); }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recycler_view_sample); Ingredient beef = new Ingredient("beef"); Ingredient cheese = new Ingredient("cheese"); Ingredient salsa = new Ingredient("salsa"); Ingredient tortilla = new Ingredient("tortilla"); Recipe taco = new Recipe("taco", Arrays.asList(beef, cheese, salsa, tortilla)); Recipe quesadilla = new Recipe("quesadilla", Arrays.asList(cheese, tortilla)); final List<Recipe> recipes = Arrays.asList(taco, quesadilla); RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview); mAdapter = new RecipeAdapter(this, recipes); mAdapter.setExpandCollapseListener(new ExpandableRecyclerAdapter.ExpandCollapseListener() { @Override public void onListItemExpanded(int position) { Recipe expandedRecipe = recipes.get(position); Toast.makeText(VerticalLinearRecyclerViewSampleActivity.this, <START> "expanded: " + expandedRecipe.getName(), <END> Toast.LENGTH_SHORT) .show(); } @Override public void onListItemCollapsed(int position) { Recipe collapsedRecipe = recipes.get(position); Toast.makeText(VerticalLinearRecyclerViewSampleActivity.this, "collapsed: " + collapsedRecipe.getName(), Toast.LENGTH_SHORT) .show(); } }); recyclerView.setAdapter(mAdapter); recyclerView.setLayoutManager(new LinearLayoutManager(this)); }</code><technical_language>pulled strings.xml</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recycler_view_sample); Ingredient beef = new Ingredient("beef"); Ingredient cheese = new Ingredient("cheese"); Ingredient salsa = new Ingredient("salsa"); Ingredient tortilla = new Ingredient("tortilla"); Ingredient ketchup = new Ingredient("ketchup"); Ingredient bun = new Ingredient("bun"); Recipe taco = new Recipe("taco", Arrays.asList(beef, cheese, salsa, tortilla)); Recipe quesadilla = new Recipe("quesadilla", Arrays.asList(cheese, tortilla)); Recipe burger = new Recipe("burger", Arrays.asList(beef, cheese, ketchup, bun)); final List<Recipe> recipes = Arrays.asList(taco, quesadilla, burger); RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview); mAdapter = new RecipeAdapter(this, recipes); mAdapter.setExpandCollapseListener(new ExpandableRecyclerAdapter.ExpandCollapseListener() { @Override public void onListItemExpanded(int position) { Recipe expandedRecipe = recipes.get(position); String toastMsg = getResources().getString(R.string.expanded, expandedRecipe.getName()); Toast.makeText(VerticalLinearRecyclerViewSampleActivity.this, toastMsg, Toast.LENGTH_SHORT) .show(); } @Override public void onListItemCollapsed(int position) { Recipe collapsedRecipe = recipes.get(position); String toastMsg = getResources().getString(R.string.collapsed, collapsedRecipe.getName()); Toast.makeText(VerticalLinearRecyclerViewSampleActivity.this, toastMsg, Toast.LENGTH_SHORT) .show(); } }); recyclerView.setAdapter(mAdapter); recyclerView.setLayoutManager(new LinearLayoutManager(this)); }
Source:
<code>public BinaryStatistics() { <START> this(Types.optional(PrimitiveType.PrimitiveTypeName.BINARY).named("")); <END> }</code><technical_language>Instead of creating a new instance of this type time, create a single reuse time? (Same for other Statistics classes.)</technical_language>

Target:
public BinaryStatistics() { this(DEFAULT_FAKE_TYPE); }
Source:
<code>public MergeCollection execute(RepositoryContext context) { <START> final RemoteJobs jobs = context.service(RemoteJobTracker.class).search(Expressions.matchAll(), Integer.MAX_VALUE); <END> final ObjectMapper mapper = context.service(ObjectMapper.class); final Stream<RemoteJobEntry> resultingJobs = jobs.stream().filter(RemoteJobEntry::isDone); if (!Strings.isNullOrEmpty(source)) { addSourceClause(mapper, resultingJobs); } if (!Strings.isNullOrEmpty(target)) { addTargetClause(mapper, resultingJobs); } if (!Strings.isNullOrEmpty(status)) { addStatusClause(mapper, resultingJobs); } final List<Merge> matchingMerges = resultingJobs.map(job -> job.getResultAs(mapper, Merge.class)).collect(Collectors.toList()); return new MergeCollection(matchingMerges); }</code><technical_language>is define nested filters parameters field. applying a post filter in Java</technical_language>

Target:
public MergeCollection execute(RepositoryContext context) { final ExpressionBuilder expressionBuilder = Expressions.builder(); if (!Strings.isNullOrEmpty(source)) { expressionBuilder.filter(nestedMatch(RemoteJobEntry.Fields.PARAMETERS, exactMatch(SOURCE_FIELD, source))); } if (!Strings.isNullOrEmpty(target)) { expressionBuilder.filter(nestedMatch(RemoteJobEntry.Fields.PARAMETERS, exactMatch(TARGET_FIELD, target))); } if (!Strings.isNullOrEmpty(status)) { expressionBuilder.filter(nestedMatch(RemoteJobEntry.Fields.PARAMETERS, exactMatch(STATUS_FIELD, status))); } final RemoteJobs jobs = context.service(RemoteJobTracker.class).search(expressionBuilder.build(), Integer.MAX_VALUE); final ObjectMapper mapper = context.service(ObjectMapper.class); return new MergeCollection(jobs.stream().filter(RemoteJobEntry::isDone).map(job -> job.getResultAs(mapper, Merge.class)).collect(Collectors.toList())); }
Source:
<code>private NoteService<?> serviceForEntityType(String entityType) { switch (entityType) { case "sample": return sampleService; case "library": return libraryService; case "pool": return poolService; case "run": return runService; case "projectoverview": return projectOverviewWrapper; default: <START> throw new UnsupportedOperationException("Unknown entity type: " + entityType); <END> } }</code><technical_language>a RestException 404 status this a bad url</technical_language>

Target:
private NoteService<?> serviceForEntityType(String entityType) { switch (entityType) { case "sample": return sampleService; case "library": return libraryService; case "pool": return poolService; case "run": return runService; case "projectoverview": return projectOverviewWrapper; default: throw new RestException("Unknown entity type: " + entityType, Status.NOT_FOUND); } }
Source:
<code>public void onMouseEnterUsername() { if (player == null || player.getChatOnly() || usernameLabel.getTooltip() != null) { return; } Tooltip tooltip = new Tooltip(); usernameLabel.setTooltip(tooltip); Runnable setClanTooltip = new Runnable() { @Override public void run() { if (clanMenu.getTooltip() == null && clan != null) { Tooltip clanTooltip = new Tooltip(); clanMenu.setTooltip(clanTooltip); if (clan.getDescription() == null) { clan.setDescription("-"); } <START> clanTooltip.setText(i18n.get("clan.clanName") + "\n" + clan.getClanName() + "\n\r" + i18n.get("clan.describtion") + "\n" + clan.getDescription() + "\n\r" + i18n.get("clan.clanMembers") + "\n" + clan.getClanMembers() + "\n\r" + i18n.get("clan.leader") + "\n" + clan.getLeaderName()); <END> } } }; executorService.submit(setClanTooltip); executorService.shutdown(); tooltip.textProperty().bind(Bindings.createStringBinding( () -> i18n.get("userInfo.ratingFormat", getGlobalRating(player), getLeaderboardRating(player)), player.leaderboardRatingMeanProperty(), player.leaderboardRatingDeviationProperty(), player.globalRatingMeanProperty(), player.globalRatingDeviationProperty() )); }</code><technical_language>clan.description (**p**). \n is a "linefeed", \r a "carriage return". I want \n\n. However, I prefer build UI elements this difficult/impossible style; instead, create FXML file (and a specific controller) for tooltip contents separate labels for item</technical_language>

Target:
public void onMouseEnterUsername() { if (player == null || player.getChatOnly() || usernameLabel.getTooltip() != null) { return; } Tooltip userTooltip = new Tooltip(); usernameLabel.setTooltip(userTooltip); userTooltip.textProperty().bind(Bindings.createStringBinding( () -> i18n.get("userInfo.ratingFormat", getGlobalRating(player), getLeaderboardRating(player)), player.leaderboardRatingMeanProperty(), player.leaderboardRatingDeviationProperty(), player.globalRatingMeanProperty(), player.globalRatingDeviationProperty() )); }
Source:
<code>private static Optional<Pair<URI, FedoraResource>> getEffectiveAcl(final FedoraResource resource) { try { final IdentifierConverter<Resource, FedoraResource> translator = new DefaultIdentifierTranslator(resource.getNode().getSession()); final List<String> acls = new ArrayList<>(); final Model model = createDefaultModel(); resource.getTriples(translator, PropertiesRdfContext.class) .filter(t -> model.asStatement(t).getPredicate().hasURI(WEBAC_ACCESS_CONTROL_VALUE)) .filter(t -> t.getObject().isURI()) .forEachRemaining(t -> { acls.add(t.getObject().getURI()); }); if (!acls.isEmpty()) { if (acls.size() > 1) { LOGGER.warn("Found multiple ACLs defined for this node. Using: {}", acls.get(0)); } return Optional.of(Pair.of(URI.create(acls.get(0)), resource)); } else if (resource.getNode().getDepth() == 0) { LOGGER.debug("No ACLs defined on this node or in parent hierarchy"); return Optional.empty(); } else { LOGGER.trace("Checking parent resource for ACL. No ACL found at {}", resource.getPath()); return getEffectiveAcl(resource.getContainer()); } } catch (final RepositoryException ex) { <START> LOGGER.debug("Exception finding effective ACL: {}", ex); <END> return Optional.empty(); } }</code><technical_language>Please change to: "Exception finding effective ACL: {}", ex.getMessage() Dumping stacktraces log file convolutes debugging</technical_language>

Target:
private static Optional<Pair<URI, FedoraResource>> getEffectiveAcl(final FedoraResource resource) { try { final IdentifierConverter<Resource, FedoraResource> translator = new DefaultIdentifierTranslator(resource.getNode().getSession()); final List<String> acls = new ArrayList<>(); final Model model = createDefaultModel(); resource.getTriples(translator, PropertiesRdfContext.class) .filter(t -> model.asStatement(t).getPredicate().hasURI(WEBAC_ACCESS_CONTROL_VALUE)) .filter(t -> t.getObject().isURI()) .forEachRemaining(t -> { acls.add(t.getObject().getURI()); }); if (!acls.isEmpty()) { if (acls.size() > 1) { LOGGER.warn("Found multiple ACLs defined for this node. Using: {}", acls.get(0)); } return Optional.of(Pair.of(URI.create(acls.get(0)), resource)); } else if (resource.getNode().getDepth() == 0) { LOGGER.debug("No ACLs defined on this node or in parent hierarchy"); return Optional.empty(); } else { LOGGER.trace("Checking parent resource for ACL. No ACL found at {}", resource.getPath()); return getEffectiveAcl(resource.getContainer()); } } catch (final RepositoryException ex) { LOGGER.debug("Exception finding effective ACL: {}", ex.getMessage()); return Optional.empty(); } }
Source:
<code>private void unzipUpdates(File updateFile) { try (ZipInputStream zis = new ZipInputStream(new FileInputStream(updateFile.getAbsolutePath()))) { String extractionFolder = getExtractionFolder(); File folder = new File(extractionFolder); if (!folder.exists()) { <START> folder.mkdir(); <END> } byte[] buffer = new byte[BUFFER_SIZE]; ZipEntry zipEntry; while ((zipEntry = zis.getNextEntry()) != null) { String fileName = zipEntry.getName(); if (zipEntry.isDirectory()) { continue; } File newFile = new File(extractionFolder + File.separator + fileName); new File(newFile.getParent()).mkdirs(); FileOutputStream fos = new FileOutputStream(newFile); int len; while ((len = zis.read(buffer)) > 0) { fos.write(buffer, 0, len); } fos.close(); zis.closeEntry(); } } catch (IOException ex) { ex.printStackTrace(); } }</code><technical_language>want mkdirs (so parent directories created well) please check returned value. return false if wrong</technical_language>

Target:
private void unzipUpdates(File updateFile) { try (ZipInputStream zis = new ZipInputStream(new FileInputStream(updateFile.getAbsolutePath()))) { String extractionFolder = getExtractionFolder(); File folder = new File(extractionFolder); if (!folder.exists()) { if (!folder.mkdirs()) { throw new IOException("Cannot create plugins folder"); } } ZipEntry zipEntry; while ((zipEntry = zis.getNextEntry()) != null) { String fileName = zipEntry.getName(); if (zipEntry.isDirectory()) { continue; } File newFile = new File(extractionFolder + File.separator + fileName); File parent = newFile.getParentFile(); if (!parent.exists()) { if (!parent.mkdirs()) { throw new IOException("Cannot create plugins folder"); } } FileOutputStream fos = new FileOutputStream(newFile); ByteStreams.copy(zis, fos); fos.close(); zis.closeEntry(); } } catch (IOException ex) { GPLogger.log(ex); cancel(true); } }
Source:
<code>protected List<String> findStringsInFileCommon(String regexp, boolean stopOnFirst, int searchLimit, File fileToSearch) <START> throws Exception { <END> return findStringsInFileCommon(regexp, stopOnFirst, searchLimit, fileToSearch, Project.MSG_INFO); }</code><technical_language>stated above, I need for this method throw exception</technical_language>

Target:
protected List<String> findStringsInFileCommon(String regexp, boolean stopOnFirst, int searchLimit, File fileToSearch) { return findStringsInFileCommon(regexp, stopOnFirst, searchLimit, fileToSearch, Project.MSG_INFO); }
Source:
<code>public static <T> T createProxyWithFailover( MetricsManager metricsManager, ServerListConfig serverListConfig, Class<T> type, AuxiliaryRemotingParameters parameters) { <START> return VersionSelectingClients.instrumentWithClientVersionTag( <END> metricsManager.getTaggedRegistry(), ConjureJavaRuntimeTargetFactory.DEFAULT.createProxyWithFailover(serverListConfig, type, parameters), type); }</code><technical_language>I read PR, need miss code in ExperimentRunningProxy: this.refreshingExperimentalServiceSupplier = Suppliers.memoizeWithExpiration( experimentalServiceSupplier::get, CLIENT_REFRESH_INTERVAL.toMinutes(), TimeUnit.MINUTES); this loose 30 minute client reload thing, meaning get lockups again</technical_language>

Target:
public static <T> T createProxyWithFailover( MetricsManager metricsManager, ServerListConfig serverListConfig, Class<T> type, AuxiliaryRemotingParameters parameters) { Supplier<T> clientFactory = () -> instrument( metricsManager.getTaggedRegistry(), ConjureJavaRuntimeTargetFactory.DEFAULT.createProxyWithFailover(serverListConfig, type, parameters), type); return SelfRefreshingProxy.create(clientFactory, type); }