auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Promise<List<SearchResult>> search(QueryExpression expression) { final String url = encodeAllowEscapes(getBaseUrl() + SEARCH + (isNullOrEmpty(expression.getPath()) ? Path.ROOT : path(expression.getPath()))); StringBuilder queryParameters = new StringBuilder(); if (expression.getName() != null && !expression.getName().isEmpty()) { queryParameters.append("&name=").append(expression.getName()); } if (expression.getText() != null && !expression.getText().isEmpty()) { queryParameters.append("&text=").append(expression.getText()); } if (expression.getMaxItems() != 0) { queryParameters.append("&maxItems=").append(expression.getMaxItems()); } if (expression.getSkipCount() != 0) { queryParameters.append("&skipCount=").append(expression.getSkipCount()); } return reqFactory.createGetRequest(url + queryParameters.toString().replaceFirst("&", "?")) .header(ACCEPT, MimeType.APPLICATION_JSON) .loader(loaderFactory.newLoader("Searching...")) .send(unmarshaller.newListUnmarshaller(SearchResultDto.class)).then( (Function<List<SearchResultDto>, List<SearchResult>>)arg -> { if (arg.isEmpty()) { return Collections.emptyList(); } List<SearchResult> results = new ArrayList<>(arg.size()); for (SearchResultDto dto : arg) { results.add(new SearchResult(dto)); } <START> return results; <END> }); }</code><technical_language>do return arg.stream().map(SearchResult::new).collect(toList());, - is more readable..</technical_language>

Target:
public Promise<List<SearchResult>> search(QueryExpression expression) { final String url = encodeAllowEscapes(getBaseUrl() + SEARCH + (isNullOrEmpty(expression.getPath()) ? Path.ROOT : path(expression.getPath()))); StringBuilder queryParameters = new StringBuilder(); if (expression.getName() != null && !expression.getName().isEmpty()) { queryParameters.append("&name=").append(expression.getName()); } if (expression.getText() != null && !expression.getText().isEmpty()) { queryParameters.append("&text=").append(expression.getText()); } if (expression.getMaxItems() != 0) { queryParameters.append("&maxItems=").append(expression.getMaxItems()); } if (expression.getSkipCount() != 0) { queryParameters.append("&skipCount=").append(expression.getSkipCount()); } return reqFactory.createGetRequest(url + queryParameters.toString().replaceFirst("&", "?")) .header(ACCEPT, MimeType.APPLICATION_JSON) .loader(loaderFactory.newLoader("Searching...")) .send(unmarshaller.newListUnmarshaller(SearchResultDto.class)).then( (Function<List<SearchResultDto>, List<SearchResult>>)arg -> { if (arg.isEmpty()) { return Collections.emptyList(); } return arg.stream().map(SearchResult::new).collect(Collectors.toList()); }); }
Source:
<code>private static void validate(CloudBigtableConfiguration configuration, String tableId) { checkNotNullOrEmpty(configuration.getProjectId(), "projectId"); checkNotNullOrEmpty(configuration.getZoneId(), "zoneId"); checkNotNullOrEmpty(configuration.getClusterId(), "clusterId"); if (tableId != null) { checkNotNullOrEmpty(tableId, "tableid"); } <START> if (BigtableSession.isAlpnConfigured()) { <END> try (BigtableConnection conn = new BigtableConnection(configuration.toHBaseConfig()); Admin admin = conn.getAdmin()) { if (tableId != null) { Preconditions.checkState(admin.tableExists(TableName.valueOf(tableId))); } else { admin.listTableNames(); } } catch (IOException | IllegalArgumentException | ExceptionInInitializerError e) { LoggerFactory.getLogger(CloudBigtableIO.class).error( String.format("Could not validate that the table exists: %s (%s)", e.getClass().getName(), e.getMessage()), e); } } }</code><technical_language>want log if Ssl provider is availabe</technical_language>

Target:
private static void validate(CloudBigtableConfiguration configuration, String tableId) { checkNotNullOrEmpty(configuration.getProjectId(), "projectId"); checkNotNullOrEmpty(configuration.getZoneId(), "zoneId"); checkNotNullOrEmpty(configuration.getClusterId(), "clusterId"); if (tableId != null) { checkNotNullOrEmpty(tableId, "tableid"); if (BigtableSession.isAlpnConfigured()) { try (BigtableConnection conn = new BigtableConnection(configuration.toHBaseConfig()); Admin admin = conn.getAdmin()) { Preconditions.checkState(admin.tableExists(TableName.valueOf(tableId))); } catch (IOException | IllegalArgumentException | ExceptionInInitializerError e) { LOG.error(String.format("Could not validate that the table exists: %s (%s)", e.getClass() .getName(), e.getMessage()), e); } } else { LOG.info("ALPN is not configured. Skipping table existence check."); } } }
Source:
<code>private Merovingian2(long msId) { super(MerovingianMBean.class, false); _msId = msId; <START> try (Connection conn = TransactionLegacy.getStandaloneConnectionWithException();) { <END> conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); conn.setAutoCommit(true); _concierge = new ConnectionConcierge("LockMaster", conn, true); } catch (SQLException e) { s_logger.error("Unable to get a new db connection", e); throw new CloudRuntimeException("Unable to initialize a connection to the database for locking purposes: ", e); } }</code><technical_language>Connection is in ConnectionConcierge object. failure else if Connection get GC'ed</technical_language>

Target:
private Merovingian2(long msId) { super(MerovingianMBean.class, false); _msId = msId; Connection conn = null; try { conn = TransactionLegacy.getStandaloneConnectionWithException(); conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); conn.setAutoCommit(true); _concierge = new ConnectionConcierge("LockMaster", conn, true); } catch (SQLException e) { s_logger.error("Unable to get a new db connection", e); throw new CloudRuntimeException("Unable to initialize a connection to the database for locking purposes", e); } finally { if (_concierge == null && conn != null) { try { conn.close(); } catch (SQLException e) { s_logger.debug("closing connection failed after everything else.", e); } } } }
Source:
<code>private TopicName createTrackedTopic(String group, String name) { TopicName topic = new TopicName(group, name); operations.createGroup(topic.getGroupName()); <START> operations.createTopic(topic.getGroupName(), topic.getName()); <END> operations.updateTopic(topic, Topic.Builder.topic() .withName(topic) .withTrackingEnabled(true).build()); return topic; }</code><technical_language>this hacky, create new operations#createTopic(Topic) method instead of creating updating</technical_language>

Target:
private TopicName createTrackedTopic(String group, String name) { TopicName topic = new TopicName(group, name); operations.createGroup(topic.getGroupName()); operations.createTopic(topic().withName(topic).withTrackingEnabled(true).build()); return topic; }
Source:
<code>private Result visitAggregate(Aggregate e, List<Integer> groupKeyList) { final Result x = visitChild(0, e.getInput()); final Builder builder; <START> if ((e.getInput() instanceof Project) && (groupKeyList.isEmpty() || !x.withGroupBy())) { <END> builder = x.builder(e); builder.clauses.add(Clause.GROUP_BY); } else { builder = x.builder(e, Clause.GROUP_BY); } final List<SqlNode> selectList = new ArrayList<>(); final List<SqlNode> groupByList = generateGroupList(builder, selectList, e, groupKeyList); return buildAggregate(e, builder, selectList, groupByList); }</code><technical_language>If x.withGroupBy() is true groupKeyList is empty, is ok this IF clause</technical_language>

Target:
private Result visitAggregate(Aggregate e, List<Integer> groupKeyList) { final Result x = visitChild(0, e.getInput()); final Builder builder; if (e.getInput() instanceof Project) { builder = x.builder(e); builder.clauses.add(Clause.GROUP_BY); } else { builder = x.builder(e, Clause.GROUP_BY); } final List<SqlNode> selectList = new ArrayList<>(); final List<SqlNode> groupByList = generateGroupList(builder, selectList, e, groupKeyList); return buildAggregate(e, builder, selectList, groupByList); }
Source:
<code><START> public void sendFullCubeLoadPacketsWhereNecessary(Collection<? extends ICube> cubes, EntityPlayerMP player, CubePos offset, Set<ChunkPos> clientLoadedChunks) { <END> if (!CubicChunksConfig.allowVanillaClients) { return; } Map<Chunk, List<ICube>> columns = cubes.stream().collect(Collectors.groupingBy(ICube::getColumn)); for (Map.Entry<Chunk, List<ICube>> chunkPosListEntry : columns.entrySet()) { Chunk chunk = chunkPosListEntry.getKey(); ChunkPos pos = chunk.getPos(); List<ICube> column = chunkPosListEntry.getValue(); if (clientLoadedChunks.contains(new ChunkPos(pos.x + offset.getX(), pos.z + offset.getZ()))) { player.connection.sendPacket(constructChunkData(pos, column, offset, world.provider.hasSkyLight())); } else { player.connection.sendPacket(constructFullChunkData(chunk, column, offset, world.provider.hasSkyLight())); clientLoadedChunks.add(pos); } } }</code><technical_language>This need public</technical_language>

Target:
private Set<ChunkPos> sendFullCubeLoadPacketsWhereNecessary(Collection<? extends ICube> cubes, EntityPlayerMP player, CubePos offset, Set<ChunkPos> clientLoadedChunks) { if (!CubicChunksConfig.allowVanillaClients) { return Collections.emptySet(); } Map<Chunk, List<ICube>> columns = cubes.stream().collect(Collectors.groupingBy(ICube::getColumn)); Set<ChunkPos> sentAsFullChunks = Collections.emptySet(); for (Map.Entry<Chunk, List<ICube>> chunkPosListEntry : columns.entrySet()) { Chunk chunk = chunkPosListEntry.getKey(); ChunkPos offsetPos = new ChunkPos(chunk.x + offset.getX(), chunk.z + offset.getZ()); List<ICube> column = chunkPosListEntry.getValue(); if (clientLoadedChunks.contains(offsetPos)) { player.connection.sendPacket(constructChunkData(chunk.getPos(), column, offset, world.provider.hasSkyLight())); } else { player.connection.sendPacket(constructFullChunkData(chunk, column, offset, world.provider.hasSkyLight())); (sentAsFullChunks.isEmpty() ? sentAsFullChunks = new HashSet<>() : sentAsFullChunks).add(offsetPos); } } return sentAsFullChunks; }
Source:
<code>public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { super.onLoadingComplete(imageUri, view, loadedImage); <START> updateNotificationThumbnail(); <END> updateNotification(-1); }</code><technical_language>I I this too, updateNotificatinThumbnail is costly lag phone updating bitmap a second. try benchmarking this again, preferably older phone</technical_language>

Target:
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { super.onLoadingComplete(imageUri, view, loadedImage); resetNotification(); updateNotificationThumbnail(); updateNotification(-1); }
Source:
<code>public boolean accept(FilterableIssue issue) { if (filterAnyRule) { return !(issue.componentKey().equals(componentKey) && excludedLinesByRule.get(ANY_RULE_KEY).contains(issue.line())); <START> } <END> return !(issue.componentKey().equals(componentKey) && excludedLinesByRule.get(issue.ruleKey().rule()).contains(issue.line())); }</code><technical_language>This rewritten change key depending of filterAnyRule</technical_language>

Target:
public boolean accept(FilterableIssue issue) { return !(issue.componentKey().equals(componentKey) && excludedLinesByRule.get(issue.ruleKey().rule()).contains(issue.line())); }
Source:
<code>public List<MappedResource<E>> getMatches(String path) { boolean isRootPath = "/".equals(path); List<MappedResource<E>> ret = new ArrayList<>(); for (MappedResource<E> mr : _mappings) { switch (mr.getPathSpec().group) { case ROOT: if (isRootPath) ret.add(mr); break; case DEFAULT: if (isRootPath || mr.getPathSpec().matches(path)) ret.add(mr); break; default: if (mr.getPathSpec().matches(path)) ret.add(mr); break; } } <START> ret.sort(LogicalDeclarationComparator.INSTANCE); <END> return ret; }</code><technical_language>Do need this LogicalDeclarationComparator if _mappings sorted is a TreeSet</technical_language>

Target:
public List<MappedResource<E>> getMatches(String path) { boolean isRootPath = "/".equals(path); List<MappedResource<E>> ret = new ArrayList<>(); for (MappedResource<E> mr : _mappings) { switch (mr.getPathSpec().group) { case ROOT: if (isRootPath) ret.add(mr); break; case DEFAULT: if (isRootPath || mr.getPathSpec().matches(path)) ret.add(mr); break; default: if (mr.getPathSpec().matches(path)) ret.add(mr); break; } } return ret; }
Source:
<code>public void query(ActivityScope scope, IProgressMonitor monitor) throws CoreException { if (scope instanceof TaskActivityScope) { ITask scopeTask = ((TaskActivityScope) scope).getTask(); GetAssociatedTasks collector = new GetAssociatedTasks(session); IndexReference reference = new IndexReference(); try { TaskListIndex taskListIndex = reference.index(); <START> taskListIndex.find(scopeTask.getTaskId(), collector, 10); <END> } finally { reference.dispose(); } } }</code><technical_language>I matching URL primarily yield lead false positives is other traceability features in Mylyn use. fine this implement a start refining get some mileage it</technical_language>

Target:
public void query(ActivityScope scope, IProgressMonitor monitor) throws CoreException { if (scope instanceof TaskActivityScope) { ITask scopeTask = ((TaskActivityScope) scope).getTask(); GetAssociatedTasks collector = new GetAssociatedTasks(session); IndexReference reference = new IndexReference(); try { TaskListIndex taskListIndex = reference.index(); taskListIndex.find(scopeTask.getTaskKey(), collector, 50); } finally { reference.dispose(); } } }
Source:
<code>ErrorType getErrorType(@Nullable Throwable caught) { if (caught != null && is404(caught)) { return ErrorType.PAGE_MISSING; } else if (caught != null && isTimeout(caught)) { return ErrorType.TIMEOUT; <START> } else if (caught != null && isOffline(caught)) { <END> return ErrorType.OFFLINE; } return ErrorType.GENERIC; }</code><technical_language>Do caught != null null check conditions necessary</technical_language>

Target:
ErrorType getErrorType(@Nullable Throwable caught) { if (caught != null && is404(caught)) { return ErrorType.PAGE_MISSING; } else if (isTimeout(caught)) { return ErrorType.TIMEOUT; } else if (isOffline(caught)) { return ErrorType.OFFLINE; } return ErrorType.GENERIC; }
Source:
<code>private void newDR() { if (getWindow() != null) { return; } final StorageDomain storageDomain = getEntity(); if (storageDomain == null) { return; } final StorageDRModel model = new StorageDRModel(); model.setHelpTag(HelpTag.new_storage_dr); model.setHashName("new_storage_dr"); model.setTitle(ConstantsManager.getInstance().getConstants().newDRSetup()); setWindow(model); <START> model.startProgress(); <END> model.getStorageDomain().setEntity(storageDomain); AsyncDataProvider.getInstance().getGlusterGeoRepSessionsForStorageDomain(new AsyncQuery<>(new AsyncCallback<List<GlusterGeoRepSession>>() { @Override public void onSuccess(List<GlusterGeoRepSession> geoRepSessions) { model.getGeoRepSession().setItems(geoRepSessions); model.stopProgress(); } }), storageDomain.getId()); UICommand okCommand = UICommand.createDefaultOkUiCommand("onNewDR", this); model.getCommands().add(okCommand); UICommand cancelCommand = UICommand.createCancelUiCommand("Cancel", this); model.getCommands().add(cancelCommand); }</code><technical_language>move line 184 - right query invocation (just for convention reasons)</technical_language>

Target:
private void newDR() { if (getWindow() != null) { return; } final StorageDomain storageDomain = getEntity(); if (storageDomain == null) { return; } final StorageDRModel model = new StorageDRModel(); model.setHelpTag(HelpTag.new_storage_dr); model.setHashName("new_storage_dr"); model.setTitle(ConstantsManager.getInstance().getConstants().newDRSetup()); setWindow(model); model.getStorageDomain().setEntity(storageDomain); model.startProgress(); AsyncDataProvider.getInstance().getGlusterGeoRepSessionsForStorageDomain(new AsyncQuery<>(new AsyncCallback<List<GlusterGeoRepSession>>() { @Override public void onSuccess(List<GlusterGeoRepSession> geoRepSessions) { model.getGeoRepSession().setItems(geoRepSessions); model.stopProgress(); } }), storageDomain.getId()); UICommand okCommand = UICommand.createDefaultOkUiCommand("onNewDR", this); model.getCommands().add(okCommand); UICommand cancelCommand = UICommand.createCancelUiCommand("Cancel", this); model.getCommands().add(cancelCommand); }
Source:
<code>public void handleGet(ActionParameters params) throws ActionException { try { final JSONObject root = new JSONObject(); getRoles(root); <START> getPermissionTypes(root,params.getLocale().getLanguage()); <END> ResponseHelper.writeResponse(params, root); } catch (Exception e) { throw new ActionException("Something went wrong getting roles and permission types from the platform", e); } }</code><technical_language>Refactor getRoles() getPermissionTypes() return array construct response object methods need root param</technical_language>

Target:
public void handleGet(ActionParameters params) throws ActionException { try { final JSONObject root = new JSONObject(); JSONHelper.putValue(root, JSKEY_ROLES, getRoles()); JSONHelper.putValue(root, JSKEY_PERMISSION_TYPES, getPermissionTypes(params.getLocale().getLanguage())); ResponseHelper.writeResponse(params, root); } catch (Exception e) { throw new ActionException("Something went wrong getting roles and permission types from the platform", e); } }
Source:
<code>public void accept( PageCursor cursor ) { byte[] bytesToWrite = failureBytes; cursor.putByte( NativeSchemaNumberIndexPopulator.BYTE_FAILED ); int availableSpace = cursor.getCurrentPageSize() - cursor.getOffset(); if ( bytesToWrite.length + HEADER_LENGTH_FIELD_LENGTH > availableSpace ) { <START> bytesToWrite = Arrays.copyOf( bytesToWrite, availableSpace - 2 ); <END> } cursor.putShort( (short) bytesToWrite.length ); cursor.putBytes( bytesToWrite ); }</code><technical_language>fix magic 2 :)</technical_language>

Target:
public void accept( PageCursor cursor ) { byte[] bytesToWrite = failureBytes; cursor.putByte( NativeSchemaNumberIndexPopulator.BYTE_FAILED ); int availableSpace = cursor.getCurrentPageSize() - cursor.getOffset(); if ( bytesToWrite.length + HEADER_LENGTH_FIELD_LENGTH > availableSpace ) { bytesToWrite = Arrays.copyOf( bytesToWrite, availableSpace - HEADER_LENGTH_FIELD_LENGTH ); } cursor.putShort( (short) bytesToWrite.length ); cursor.putBytes( bytesToWrite ); }
Source:
<code>private void pushToRemoteSteam() { try { LOG.debug("Push latest changed from remote stream"); PushCommand pushCommand = git.push(); pushCommand.setCredentialsProvider( new UsernamePasswordCredentialsProvider( zeppelinConfiguration.getZeppelinNotebookGitUsername(), zeppelinConfiguration.getZeppelinNotebookGitAccessToken() ) ); pushCommand.call(); } catch (GitAPIException e) { LOG.error("Error when pushing latest changes from remote repository"); <START> e.printStackTrace(); <END> } }</code><technical_language>LOG.error("Error pushing latest changes remote repository", e);</technical_language>

Target:
private void pushToRemoteSteam() { try { LOG.debug("Push latest changed from remote stream"); PushCommand pushCommand = git.push(); pushCommand.setCredentialsProvider( new UsernamePasswordCredentialsProvider( zeppelinConfiguration.getZeppelinNotebookGitUsername(), zeppelinConfiguration.getZeppelinNotebookGitAccessToken() ) ); pushCommand.call(); } catch (GitAPIException e) { LOG.error("Error when pushing latest changes from remote repository", e); } }
Source:
<code><START> public void shouldFailForConversions(String value) { <END> String payload = format("{" + " \"reference\" : %s," + " \"return_url\" : \"<LINK_0>\"" + "}", value); given().port(app.getLocalPort()) .body(payload) .accept(JSON) .contentType(JSON) .header(AUTHORIZATION, "Bearer " + API_KEY) .post("/v1/directdebit/mandates") .then().log().body() .statusCode(HttpStatus.SC_UNPROCESSABLE_ENTITY) .body("size()", is(3)) .body("field", is("reference")) .body("code", is("P0102")) .body("description", is("Invalid attribute value: reference. Must be of type String")); }</code><technical_language>suggestion public void nonStringTypesShouldBeConsideredInvalid(String value) {</technical_language>

Target:
public void shouldFailForConversions(String value) { String payload = format("{" + " \"reference\" : %s," + " \"return_url\" : \"<LINK_0>\"" + "}", value); given().port(app.getLocalPort()) .body(payload) .accept(JSON) .contentType(JSON) .header(AUTHORIZATION, "Bearer " + API_KEY) .post("/v1/directdebit/mandates") .then() .statusCode(HttpStatus.SC_UNPROCESSABLE_ENTITY) .body("size()", is(3)) .body("field", is("reference")) .body("code", is("P0102")) .body("description", is("Invalid attribute value: reference. Must be of type String")); }
Source:
<code>static String toJavaName(String opensslName) { if (opensslName == null) { return null; } Matcher matcher = PATTERN.matcher(opensslName); if (matcher.matches()) { String group2 = matcher.group(2); if (group2 != null) { return group2.toUpperCase(Locale.ROOT) + "with" + matcher.group(3).toUpperCase(Locale.ROOT); } if (matcher.group(4) != null) { return matcher.group(7).toUpperCase(Locale.ROOT) + "with" + matcher.group(5).toUpperCase(Locale.ROOT); } if (matcher.group(8) != null) { return matcher.group(11).toUpperCase(Locale.ROOT) + "with" + matcher.group(9).toUpperCase(Locale.ROOT); } <START> if (matcher.group(8) != null) { <END> return matcher.group(10).toUpperCase(Locale.ROOT) + "with" + matcher.group(5).toUpperCase(Locale.ROOT); } if (matcher.group(12) != null) { return matcher.group(14).toUpperCase(Locale.ROOT) + "with" + matcher.group(13).toUpperCase(Locale.ROOT); } } return null; }</code><technical_language>group 8 checked. groups mentioned in this block pretty screwy</technical_language>

Target:
static String toJavaName(String opensslName) { if (opensslName == null) { return null; } Matcher matcher = PATTERN.matcher(opensslName); if (matcher.matches()) { String group1 = matcher.group(1); if (group1 != null) { return group1.toUpperCase(Locale.ROOT) + "with" + matcher.group(2).toUpperCase(Locale.ROOT); } if (matcher.group(3) != null) { return matcher.group(4).toUpperCase(Locale.ROOT) + "with" + matcher.group(3).toUpperCase(Locale.ROOT); } if (matcher.group(5) != null) { return matcher.group(6).toUpperCase(Locale.ROOT) + "with" + matcher.group(5).toUpperCase(Locale.ROOT); } } return null; }
Source:
<code>private ECPControlDescription getControlCandidate(Class<?> controlClass, EObject domainModel, VDomainModelReference domainModelReference) { int highestPriority = -1; ECPControlDescription bestCandidate = null; IObservableValue observableValue; try { observableValue = Activator.getDefault().getEMFFormsDatabinding() <START> .getObservableValue(domainModelReference, domainModel); <END> } catch (final DatabindingFailedException ex) { Activator.getDefault().getReportService().report(new DatabindingFailedReport(ex)); return bestCandidate; } catch (final IllegalArgumentException ex) { Activator.getDefault().getReportService().report(new AbstractReport(ex)); return bestCandidate; } final EObject eObject = (EObject) ((IObserving) observableValue).getObserved(); final EStructuralFeature structuralFeature = (EStructuralFeature) observableValue.getValueType(); observableValue.dispose(); for (final ECPControlDescription description : controlDescriptors) { if (!controlClass.isAssignableFrom(description.getControlClass())) { continue; } int currentPriority = -1; for (final ECPApplicableTester tester : description.getTester()) { final int testerPriority = tester.isApplicable(eObject, structuralFeature); if (testerPriority > currentPriority) { currentPriority = testerPriority; } } if (currentPriority > highestPriority) { highestPriority = currentPriority; bestCandidate = description; } } return bestCandidate; }</code><technical_language>simply check domainModel oder domainModelReference is null before</technical_language>

Target:
private ECPControlDescription getControlCandidate(Class<?> controlClass, EObject domainModel, VDomainModelReference domainModelReference) { int highestPriority = -1; ECPControlDescription bestCandidate = null; if (domainModelReference == null) { return bestCandidate; } IObservableValue observableValue; try { observableValue = Activator.getDefault().getEMFFormsDatabinding() .getObservableValue(domainModelReference, domainModel); } catch (final DatabindingFailedException ex) { Activator.getDefault().getReportService().report(new DatabindingFailedReport(ex)); return bestCandidate; } catch (final IllegalArgumentException ex) { Activator.getDefault().getReportService().report(new AbstractReport(ex)); return bestCandidate; } final EObject eObject = (EObject) ((IObserving) observableValue).getObserved(); final EStructuralFeature structuralFeature = (EStructuralFeature) observableValue.getValueType(); observableValue.dispose(); for (final ECPControlDescription description : controlDescriptors) { if (!controlClass.isAssignableFrom(description.getControlClass())) { continue; } int currentPriority = -1; for (final ECPApplicableTester tester : description.getTester()) { final int testerPriority = tester.isApplicable(eObject, structuralFeature); if (testerPriority > currentPriority) { currentPriority = testerPriority; } } if (currentPriority > highestPriority) { highestPriority = currentPriority; bestCandidate = description; } } return bestCandidate; }
Source:
<code>public ShaderProvider getPassShaderProvider (int n) { <START> if (n >= passShaderProviders.length) <END> throw new GdxRuntimeException("ShaderProvider " + n + " doesn't exist in " + getClass().getName()); return passShaderProviders[n]; }</code><technical_language>I dont this check is needed (otherwise throw index out of bounds exception, same). <LINK_0></technical_language>

Target:
public ShaderProvider getPassShaderProvider (int n) { return passShaderProviders[n]; }
Source:
<code>public static boolean equalAsCollectionSansNullability( RelDataTypeFactory factory, RelDataType type1, RelDataType type2) { if (type1.equals(type2)) { return true; } if (isCollection(type1) && isCollection(type2)) { return equalSansNullability(factory, type1.getComponentType(), type2.getComponentType()); } else { return false; <START> } <END> }</code><technical_language>add assertion instead in line: assert isCollection(type1) && isCollection(type2)</technical_language>

Target:
public static boolean equalAsCollectionSansNullability( RelDataTypeFactory factory, RelDataType type1, RelDataType type2) { Preconditions.checkArgument(isCollection(type1)); Preconditions.checkArgument(isCollection(type2)); return (type1 == type2) || (type1.getSqlTypeName() == type2.getSqlTypeName() && equalSansNullability(factory, type1.getComponentType(), type2.getComponentType())); }
Source:
<code>private static boolean checkFirstMiddleLastNameContents(EnExplicitFamily lastname, EnExplicitGiven firstname, EnExplicitGiven middlename, Personname personNameDBModel) { boolean namefound = false; if (lastname != null && lastname.getContent() != null) { personNameDBModel.setLastName(lastname.getContent()); <START> LOG.info("FamilyName : ", personNameDBModel.getLastName()); <END> namefound = true; } if (firstname != null && firstname.getContent() != null) { personNameDBModel.setFirstName(firstname.getContent()); LOG.info("GivenName(first) : ", personNameDBModel.getFirstName()); namefound = true; } if (middlename != null && middlename.getContent() != null) { personNameDBModel.setMiddleName(middlename.getContent()); LOG.info("GivenName(middle) : ", personNameDBModel.getMiddleName()); namefound = true; } return namefound; }</code><technical_language>need log parameter in string</technical_language>

Target:
private static boolean checkFirstMiddleLastNameContents(EnExplicitFamily lastname, EnExplicitGiven firstname, EnExplicitGiven middlename, Personname personNameDBModel) { boolean namefound = false; if (lastname != null && lastname.getContent() != null) { personNameDBModel.setLastName(lastname.getContent()); LOG.info("FamilyName : ", personNameDBModel.getLastName()); namefound = true; } if (firstname != null && firstname.getContent() != null) { personNameDBModel.setFirstName(firstname.getContent()); LOG.info("GivenName(first) : ", personNameDBModel.getFirstName()); namefound = true; } if (middlename != null && middlename.getContent() != null) { personNameDBModel.setMiddleName(middlename.getContent()); LOG.info("GivenName(middle) : ", personNameDBModel.getMiddleName()); namefound = true; } return namefound; }
Source:
<code>public void whenTemplateWithGivenInputTemplate_String_shouldRenderBlobAsIt() throws IOException { TemplateSourceDocument templateSrc = createTemplateSourceDoc("We are introducing ${myStringInCtxt} !", WEBVIEW_RENDITION); TemplateBasedDocument templateBase = createTemplateBasedDoc(templateSrc.getAdaptedDoc()); <START> List<TemplateInput> params = Arrays.asList( <END> factory("myStringInCtxt", StringValue, "Beautiful String") ); templateBase.saveParams(TEMPLATE_NAME, params, true); Blob result = templateBase.renderWithTemplate(TEMPLATE_NAME); assertNotNull(result); assertEquals("We are introducing Beautiful String !", result.getString()); }</code><technical_language>List#of Collections#singletonList</technical_language>

Target:
public void whenTemplateWithGivenInputTemplate_String_shouldRenderBlobAsIt() throws IOException { TemplateSourceDocument templateSrc = createTemplateSourceDoc("We are introducing ${myStringInCtxt} !", WEBVIEW_RENDITION); TemplateBasedDocument templateBase = createTemplateBasedDoc(templateSrc.getAdaptedDoc()); List<TemplateInput> params = List.of( factory("myStringInCtxt", StringValue, "Beautiful String") ); templateBase.saveParams(TEMPLATE_NAME, params, true); Blob result = templateBase.renderWithTemplate(TEMPLATE_NAME); assertNotNull(result); assertEquals("We are introducing Beautiful String !", result.getString()); }
Source:
<code>boolean getAsBoolean() throws Exception; } public static void waitUntil( String message, int timeoutSeconds, BooleanSupplierWithThrow predicate) throws <START> Exception { <END> int sleep = 125; final long timeout = System.currentTimeMillis() + timeoutSeconds * 1000; while (System.currentTimeMillis() < timeout) { if (predicate.getAsBoolean()) { return; } RunUtil.getDefault().sleep(sleep); } fail(message); }</code><technical_language>throw a more targeted exception</technical_language>

Target:
boolean getAsBoolean() throws Exception; } public static void waitUntil( String message, long timeoutSeconds, BooleanSupplierWithThrow predicate) throws Exception { int sleep = 125; final long timeout = System.currentTimeMillis() + timeoutSeconds * 1000; while (System.currentTimeMillis() < timeout) { if (predicate.getAsBoolean()) { return; } RunUtil.getDefault().sleep(sleep); } fail(message); }
Source:
<code>protected void stopBackgroundDiscovery() { logger.debug("Stop WeMo device background discovery"); <START> <END> }</code><technical_language>idea stop scanningJob here</technical_language>

Target:
protected void stopBackgroundDiscovery() { logger.debug("Stop WeMo device background discovery"); if (scanningJob != null && !scanningJob.isCancelled()) { scanningJob.cancel(true); scanningJob = null; } }
Source:
<code>public void testClientServer() throws Exception { InMemoryZKServer zkServer = InMemoryZKServer.builder().setDataDir(tmpFolder.newFolder()).build(); zkServer.startAndWait(); try { Configuration conf = HBaseConfiguration.create(); conf.set(TxConstants.Service.CFG_DATA_TX_ZOOKEEPER_QUORUM, zkServer.getConnectionStr()); conf.set(TxConstants.Manager.CFG_TX_SNAPSHOT_DIR, tmpFolder.newFolder().getAbsolutePath()); final TransactionServiceMain main = new TransactionServiceMain(conf); Thread t = new Thread() { @Override public void run() { try { main.start(); } catch (Exception e) { throw Throwables.propagate(e); } } }; try { t.start(); <START> TimeUnit.SECONDS.sleep(5); <END> TransactionServiceClient.doMain(true, conf); } finally { main.stop(); t.join(); } } finally { zkServer.stopAndWait(); } }</code><technical_language>is sleep necessary? If a race, explicit signal count latch wait 5 seconds</technical_language>

Target:
public void testClientServer() throws Exception { InMemoryZKServer zkServer = InMemoryZKServer.builder().setDataDir(tmpFolder.newFolder()).build(); zkServer.startAndWait(); try { Configuration conf = HBaseConfiguration.create(); conf.set(TxConstants.Service.CFG_DATA_TX_ZOOKEEPER_QUORUM, zkServer.getConnectionStr()); conf.set(TxConstants.Manager.CFG_TX_SNAPSHOT_DIR, tmpFolder.newFolder().getAbsolutePath()); final TransactionServiceMain main = new TransactionServiceMain(conf); final CountDownLatch latch = new CountDownLatch(1); Thread t = new Thread() { @Override public void run() { try { main.start(); latch.countDown(); } catch (Exception e) { throw Throwables.propagate(e); } } }; try { t.start(); latch.await(); TransactionServiceClient.doMain(true, conf); } finally { main.stop(); t.join(); } } finally { zkServer.stopAndWait(); } }
Source:
<code>private Metacard readMetacard(File file) throws IngestException { <START> Metacard result; <END> FileInputStream fis = null; ObjectInputStream ois = null; try { if (SERIALIZED_OBJECT_ID.matches(transformerId)) { ois = new ObjectInputStream(new FileInputStream(file)); result = (Metacard) ois.readObject(); ois.close(); } else { fis = new FileInputStream(file); result = generateMetacard(fis); if (StringUtils.isBlank(result.getTitle())) { LOGGER.debug("Metacard title was blank. Setting title to filename."); result.setAttribute(new AttributeImpl(Metacard.TITLE, file.getName())); } fis.close(); } } catch (IOException | IllegalArgumentException | ClassNotFoundException e) { throw new IngestException(e); } finally { if (fis != null) { try { fis.close(); } catch (IOException e1) { console.println(e1); } } if (ois != null) { try { ois.close(); } catch (IOException e2) { console.println(e2); } } } return result; }</code><technical_language>removing null making line 501 return, is undefined if for example, new FileInputStream() throws exception</technical_language>

Target:
private Metacard readMetacard(File file) throws IngestException { Metacard result = null; FileInputStream fis = null; ObjectInputStream ois = null; try { if (SERIALIZED_OBJECT_ID.matches(transformerId)) { ois = new ObjectInputStream(new FileInputStream(file)); result = (Metacard) ois.readObject(); ois.close(); } else { fis = new FileInputStream(file); result = generateMetacard(fis); if (StringUtils.isBlank(result.getTitle())) { LOGGER.debug("Metacard title was blank. Setting title to filename."); result.setAttribute(new AttributeImpl(Metacard.TITLE, file.getName())); } fis.close(); } } catch (IOException | IllegalArgumentException | ClassNotFoundException e) { throw new IngestException(e); } finally { if (fis != null) { try { fis.close(); } catch (IOException e1) { console.println(e1); } } if (ois != null) { try { ois.close(); } catch (IOException e2) { console.println(e2); } } } return result; }
Source:
<code>public BitBuffer(ByteBuffer buf, ByteOrder order) { setByteBuffer(buf); setByteOrder(order); <START> pos = 0; END> }</code><technical_language>exception? reading new version, this is confusing, this method throw any</technical_language>

Target:
public BitBuffer(ByteBuffer buf, ByteOrder order) { setByteBuffer(buf); setByteOrder(order); resetPosition(); }
Source:
<code>private String format(Object o) { if (o instanceof Float) { return format(((Float) o).doubleValue()); } else if (o instanceof Double) { return format(((Double) o).doubleValue()); <START> } else if (o instanceof Byte) { <END> return format(((Byte) o).longValue()); } else if (o instanceof Short) { return format(((Short) o).longValue()); } else if (o instanceof Integer) { return format(((Integer) o).longValue()); } else if (o instanceof Long) { return format(((Long) o).longValue()); } return null; }</code><technical_language>Example of egregipis copy/paste</technical_language>

Target:
private String format(Object o) { if (o instanceof Float) { return format(((Float) o).doubleValue()); } else if (o instanceof Double) { return format(((Double) o).doubleValue()); } else if (o instanceof Byte) { return format(((Byte) o).longValue()); } else if (o instanceof Short) { return format(((Short) o).longValue()); } else if (o instanceof Integer) { return format(((Integer) o).longValue()); } else if (o instanceof Long) { return format(((Long) o).longValue()); } else if (o instanceof BigInteger) { return format(((BigInteger) o).doubleValue()); } else if (o instanceof BigDecimal) { return format(((BigDecimal) o).doubleValue()); } else if (o instanceof Boolean) { return format(((Boolean) o) ? 1 : 0); } return null; }
Source:
<code>public SystemInfo getSystemInfo() throws IOException { PodList chePods = openShiftClient.pods().inNamespace(this.openShiftCheProjectName) <START> .withLabel(OPENSHIFT_DEPLOYMENT_CONFIG_LABEL, OPENSHIFT_DEPLOYMENT_CONFIG_VALUE).list(); <END> if (chePods.getItems().size() > 0) { Pod pod = chePods.getItems().get(0); Node node = openShiftClient.nodes().withName(pod.getSpec().getNodeName()).get(); NodeSystemInfo nodeInfo = node.getStatus().getNodeInfo(); SystemInfo systemInfo = new SystemInfo(); systemInfo.setKernelVersion(nodeInfo.getKernelVersion()); systemInfo.setOperatingSystem(nodeInfo.getOperatingSystem()); systemInfo.setID(node.getMetadata().getUid()); int containers = 0; List<Pod> pods = openShiftClient.pods().inNamespace(this.openShiftCheProjectName).list().getItems(); for (Pod p:pods) { containers += p.getSpec().getContainers().size(); } int images = node.getStatus().getImages().size(); systemInfo.setContainers(containers); systemInfo.setImages(images); systemInfo.setName(node.getMetadata().getName()); String[] labels = new String[node.getMetadata().getLabels().size()]; final int[] i = {0}; node.getMetadata().getLabels().forEach((k,v)-> labels[i[0]++] = k + "=" + v ); systemInfo.setLabels(labels); return systemInfo; } else { throw new OpenShiftException(String.format("Deployment config with %s not found", OPENSHIFT_DEPLOYMENT_CONFIG_VALUE)); } }</code><technical_language>Is this step necessary? I feel explicitly checking for deploymentconfig=che is prone error if deploy script is changed. Is sufficient do openShiftClient.pods().inNamespace(...).list()</technical_language>

Target:
public SystemInfo getSystemInfo() throws IOException { PodList chePods = openShiftClient.pods().inNamespace(this.openShiftCheProjectName).list(); if (chePods.getItems().size() > 0) { Pod pod = chePods.getItems().get(0); Node node = openShiftClient.nodes().withName(pod.getSpec().getNodeName()).get(); NodeSystemInfo nodeInfo = node.getStatus().getNodeInfo(); SystemInfo systemInfo = new SystemInfo(); systemInfo.setKernelVersion(nodeInfo.getKernelVersion()); systemInfo.setOperatingSystem(nodeInfo.getOperatingSystem()); systemInfo.setID(node.getMetadata().getUid()); int containers = openShiftClient.pods().inNamespace(this.openShiftCheProjectName).list().getItems().size(); int images = node.getStatus().getImages().size(); systemInfo.setContainers(containers); systemInfo.setImages(images); systemInfo.setName(node.getMetadata().getName()); String[] labels = node.getMetadata() .getLabels() .entrySet().stream().map(e -> String.format("%s=%s", e.getKey(), e.getValue())) .toArray(String[]::new); systemInfo.setLabels(labels); return systemInfo; } else { throw new OpenShiftException("No pod found"); } }
Source:
<code>public void updatePatientMotechId(Config config, String patientUuid, String newMotechId) { List<Identifier> patientIdentifiers = getPatientIdentifierList(config, patientUuid); for (Identifier patientIdentifier : patientIdentifiers) { <START> if ("MOTECH Id".equals(patientIdentifier.getIdentifierType().getDisplay())) { <END> patientIdentifier.setIdentifier(newMotechId); String requestJson = buildGson().toJson(patientIdentifier); postForJson(config, requestJson, "/patient/{patientUuid}/identifier/{identifierUuid}", patientUuid, patientIdentifier.getUuid()); break; } } }</code><technical_language>this identifier name is configurable. a method get this name. Please this</technical_language>

Target:
public void updatePatientMotechId(Config config, String patientUuid, String newMotechId) { List<Identifier> patientIdentifiers = getPatientIdentifierList(config, patientUuid); for (Identifier patientIdentifier : patientIdentifiers) { if (config.getMotechPatientIdentifierTypeName().equals(patientIdentifier.getIdentifierType().getName())) { patientIdentifier.setIdentifier(newMotechId); updatePatientIdentifier(config, patientUuid, patientIdentifier); break; } } }
Source:
<code><START> @Override public void onDestroyView() { <END> unbinder.unbind(); unbinder = null; super.onDestroyView(); }</code><technical_language>I if necessary, consider calling recyclerView.setAdapter(null); if for lifecycle symmetry. I missed patch I recommend nulling out readingList* lifecycles working expected</technical_language>

Target:
@Override public void onDestroyView() { recyclerView.setAdapter(null); unbinder.unbind(); unbinder = null; readingList = null; super.onDestroyView(); }
Source:
<code>public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String message = data != null ? new String(data) : null; Exception exception = message != null ? new HttpResponseException(command, response, message) : new HttpResponseException(command, response); message = message != null ? message : String.format("%s -> %s", command.getCurrentRequest().getRequestLine(), response.getStatusLine()); switch (response.getStatusCode()) { case 400: exception = new IllegalArgumentException(message, exception); break; case 401: case 403: <START> if (message.contains("\"Code\":\"DependencyViolation\"")) { <END> exception = new DependencyViolationException(message, exception); } else { exception = new AuthorizationException(message, exception); } break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 409: exception = new IllegalStateException(message, exception); break; } command.setException(exception); }</code><technical_language>This flaky. if is a space field name value? (as i examples copied). need do this better</technical_language>

Target:
public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String message = data != null ? new String(data) : null; Exception exception = message != null ? new HttpResponseException(command, response, message) : new HttpResponseException(command, response); message = message != null ? message : String.format("%s -> %s", command.getCurrentRequest().getRequestLine(), response.getStatusLine()); switch (response.getStatusCode()) { case 400: exception = new IllegalArgumentException(message, exception); break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 409: exception = new IllegalStateException(message, exception); break; } command.setException(exception); }
Source:
<code>private void eliminateDuplicates(List<MessageInfo> messageEntries) { Set<StoreKey> setToFindDuplicate = new HashSet<>(); ListIterator<MessageInfo> messageEntriesIterator = messageEntries.listIterator(0); while (messageEntriesIterator.hasNext()) { MessageInfo messageInfo = messageEntriesIterator.next(); if (!messageInfo.isDeleted()) { if (setToFindDuplicate.contains(messageInfo.getStoreKey())) { messageEntriesIterator.remove(); <START> } else { <END> setToFindDuplicate.add(messageInfo.getStoreKey()); } } } setToFindDuplicate.clear(); messageEntriesIterator = messageEntries.listIterator(messageEntries.size()); while (messageEntriesIterator.hasPrevious()) { MessageInfo messageInfo = messageEntriesIterator.previous(); if (setToFindDuplicate.contains(messageInfo.getStoreKey())) { messageEntriesIterator.remove(); } else { setToFindDuplicate.add(messageInfo.getStoreKey()); } } }</code><technical_language>idea eliminateDuplicates(indexEntries). Is do updateStateForMessages() + eliminateDuplicates(messageEntries) caller's loop? This a easy change. do in a new PR enhancement. ---- Question: plan for TTL replication? Replicate TTL entries peer nodes</technical_language>

Target:
private void eliminateDuplicates(List<MessageInfo> messageEntries) { Set<StoreKey> setToFindDuplicate = new HashSet<>(); messageEntries.removeIf( messageInfo -> !messageInfo.isDeleted() && !setToFindDuplicate.add(messageInfo.getStoreKey())); setToFindDuplicate.clear(); ListIterator<MessageInfo> messageEntriesIterator = messageEntries.listIterator(messageEntries.size()); while (messageEntriesIterator.hasPrevious()) { MessageInfo messageInfo = messageEntriesIterator.previous(); if (!setToFindDuplicate.add(messageInfo.getStoreKey())) { messageEntriesIterator.remove(); } } }
Source:
<code>@Override public boolean equals(Object other) { <START> return other != null && (other instanceof Module) && Objects.equals(name, ((Module)other).name); <END> }</code><technical_language>other != null is redundant other instanceof Module, returns false other is null</technical_language>

Target:
@Override public boolean equals(Object other) { return (other instanceof Module) && Objects.equals(name, ((Module)other).name); }
Source:
<code>public void testListStatusNull() { @Nullable <START> Path path = null; <END> assertThrows("hadoopPath must not be null", IllegalArgumentException.class, () -> ghfs.listStatus(path)); }</code><technical_language>pass null a parameter variable (here below)</technical_language>

Target:
public void testListStatusNull() { assertThrows( "hadoopPath must not be null", IllegalArgumentException.class, () -> ghfs.listStatus((Path) null)); }
Source:
<code>public RoutingTableSnapshot getRoutingTableSnapshot() { String key = getRoutingTableKey(DEFAULT_PROPERTY, DEFAULT_TYPE); <START> return new RoutingTableSnapshot(_routingTableRefMap.get(key).get()); <END> }</code><technical_language>check NPE for calls</technical_language>

Target:
public RoutingTableSnapshot getRoutingTableSnapshot() { return new RoutingTableSnapshot(getRoutingTableRef(DEFAULT_PROPERTY_TYPE, DEFAULT_STATE_TYPE)); }
Source:
<code>private void damageEntities() { float power = this.power; this.power *= 2; LivingEntity[] entities = getNearbyEntities(); for (LivingEntity entity : entities) { if (distanceToSquared(entity) > power * power) { continue; } double exposure = world.rayTrace(location, (GlowEntity) entity); double impact = (1 - (distanceTo(entity) / power / 2)) * exposure; double damage = (impact * impact + impact) * 8 * power + 1; int epf = getProtectionFactor(entity); double reduction = calculateEnchantedReduction(epf); damage = damage * reduction; exposure -= exposure * epf * 0.15; DamageCause damageCause; if (source == null || source.getType() == EntityType.PRIMED_TNT) { damageCause = DamageCause.BLOCK_EXPLOSION; } else { damageCause = DamageCause.ENTITY_EXPLOSION; } entity.damage(damage, source, damageCause); <START> if (entity instanceof GlowPlayer) { <END> if (((GlowPlayer) entity).isFlying()) { continue; } } Vector rayLength = RayUtil.getVelocityRay(distanceToHead(entity)); rayLength.multiply(exposure); Vector currentVelocity = entity.getVelocity(); currentVelocity.add(rayLength); entity.setVelocity(currentVelocity); } }</code><technical_language>Merge if statements, please</technical_language>

Target:
private void damageEntities() { float power = this.power; this.power *= 2; LivingEntity[] entities = getNearbyEntities(); for (LivingEntity entity : entities) { if (distanceToSquared(entity) > power * power) { continue; } double exposure = world.rayTrace(location, (GlowEntity) entity); double impact = (1 - (distanceTo(entity) / power / 2)) * exposure; double damage = (impact * impact + impact) * 8 * power + 1; int epf = getProtectionFactor(entity); double reduction = calculateEnchantedReduction(epf); damage = damage * reduction; exposure -= exposure * epf * 0.15; DamageCause damageCause; if (source == null || source.getType() == EntityType.PRIMED_TNT) { damageCause = DamageCause.BLOCK_EXPLOSION; } else { damageCause = DamageCause.ENTITY_EXPLOSION; } entity.damage(damage, source, damageCause); if (entity instanceof GlowPlayer && ((GlowPlayer) entity).isFlying()) { continue; } Vector rayLength = RayUtil.getVelocityRay(distanceToHead(entity)); rayLength.multiply(exposure); Vector currentVelocity = entity.getVelocity(); currentVelocity.add(rayLength); entity.setVelocity(currentVelocity); } }