auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public <T> T getAdapter(Object adaptableObject, Class<T> adapterType) { if (Repository.class.equals(adapterType)) { Repository repository = null; if (adaptableObject instanceof IResource) { IResource resource = (IResource) adaptableObject; repository = getRepository(resource); } else if (adaptableObject instanceof IHistoryView) { IHistoryView historyView = (IHistoryView) adaptableObject; IHistoryPage historyPage = historyView.getHistoryPage(); Object input = historyPage.getInput(); if (input instanceof RepositoryNode) { RepositoryNode node = (RepositoryNode) input; repository = node.getRepository(); } else if (input instanceof IResource) { repository = getRepository((IResource) input); } else if (input instanceof HistoryPageInput) { <START> repository = ((HistoryPageInput) input).getRepository(); <END> } } else if (adaptableObject instanceof ISelection) { IStructuredSelection structuredSelection = SelectionUtils .getStructuredSelection((ISelection) adaptableObject); repository = SelectionUtils.getRepository(structuredSelection); } else { return null; } return adapterType.cast(repository); } return null; }</code><technical_language>I if HistoryPageInput adaptable Repository instead of this hard-coded dependency. RepositoryTreeNode is adaptable Repository</technical_language>

Target:
public <T> T getAdapter(Object adaptableObject, Class<T> adapterType) { if (Repository.class.equals(adapterType)) { Repository repository = null; if (adaptableObject instanceof IResource) { IResource resource = (IResource) adaptableObject; repository = getRepository(resource); } else if (adaptableObject instanceof IHistoryView) { IHistoryView historyView = (IHistoryView) adaptableObject; IHistoryPage historyPage = historyView.getHistoryPage(); Object input = historyPage.getInput(); repository = Adapters.adapt(input, Repository.class); if (repository == null && input instanceof IResource) { repository = getRepository((IResource) input); } } else if (adaptableObject instanceof ISelection) { IStructuredSelection structuredSelection = SelectionUtils .getStructuredSelection((ISelection) adaptableObject); repository = SelectionUtils.getRepository(structuredSelection); } else { return null; } return adapterType.cast(repository); } return null; }
Source:
<code>private void reset(Reader reader) throws IOException { length = 0; lines = null; lineOffsets = null; List<String> slist = new ArrayList<>(); StringBuilder bld = new StringBuilder(); int c; while ((c = reader.read()) != -1) { ++length; redo_c: <START> while (true) { <END> bld.append((char) c); switch (c) { case '\r': c = reader.read(); if (c == -1) { slist.add(bld.toString()); bld.setLength(0); break redo_c; } ++length; if (c == '\n') { bld.append((char) c); slist.add(bld.toString()); bld.setLength(0); break redo_c; } slist.add(bld.toString()); bld.setLength(0); continue redo_c; case '\n': slist.add(bld.toString()); bld.setLength(0); break redo_c; default: } break; } } if (bld.length() > 0) { slist.add(bld.toString()); bld.setLength(0); } else { slist.add(""); } lines = slist.toArray(new String[0]); setLineOffsets(); }</code><technical_language>1 for endless cycles</technical_language>

Target:
private void reset(Reader reader) throws IOException { length = 0; lines = null; lineOffsets = null; List<String> slist = new ArrayList<>(); SourceSplitterScanner scanner = new SourceSplitterScanner(reader); scanner.setTarget(slist); scanner.consume(); length = scanner.getLength(); lines = slist.toArray(new String[0]); setLineOffsets(); }
Source:
<code>public void initialize(Context context, final InitializationCompleteCallback completionCallback, List<MediationConfiguration> mediationConfigurations) { String appId = null; for (MediationConfiguration configuration : mediationConfigurations) { Bundle serverParameters = configuration.getServerParameters(); if (serverParameters == null) { continue; } appId = serverParameters.getString(KEY_APP_ID); if (!TextUtils.isEmpty(appId)) { <START> break; <END> } } if (TextUtils.isEmpty(appId)) { if (completionCallback != null) { completionCallback.onInitializationFailed("Fyber SDK requires an appId to be configured on the AdMob console"); } Log.w(TAG, "No appId received from AdMob. Cannot initialize Fyber marketplace"); } else { InneractiveAdManager.initialize(context, appId); IAConfigManager.addListener(new IAConfigManager.OnConfigurationReadyAndValidListener() { @Override public void onConfigurationReadyAndValid(IAConfigManager iaConfigManager, boolean success, Exception e) { if (completionCallback != null) { if (success) { completionCallback.onInitializationSucceeded(); } else { completionCallback.onInitializationFailed("Fyber SDK initialization failed"); } } IAConfigManager.removeListener(this); } }); } }</code><technical_language>MediationConfiguration multiple appIDs. I store array object initialize SDK, similar other adapters it: - Get appIDs credentials needed for initialization. - Store in array. - If more one, log adapter multiple app IDs init SDK</technical_language>

Target:
public void initialize(Context context, final InitializationCompleteCallback completionCallback, List<MediationConfiguration> mediationConfigurations) { if (InneractiveAdManager.wasInitialized()) { waitForInitializationStatusAndReport(completionCallback); return; } String appId = null; List<String> configuredAppIds = new ArrayList<>(); for (MediationConfiguration configuration : mediationConfigurations) { Bundle serverParameters = configuration.getServerParameters(); if (serverParameters == null) { continue; } appId = serverParameters.getString(KEY_APP_ID); if (!TextUtils.isEmpty(appId)) { configuredAppIds.add(appId); } } if (configuredAppIds.isEmpty()) { Log.w(TAG, "No appId received from AdMob. Cannot initialize Fyber Marketplace"); if (completionCallback != null) { completionCallback.onInitializationFailed("Fyber SDK requires an appId to be configured on the AdMob UI"); } return; } String appIdForInitialization = configuredAppIds.get(0); if (configuredAppIds.size() > 1) { String message = String.format("Multiple '%s' entries found: %s. " + "Using '%s' to initialize the Fyber Marketplace SDK", KEY_APP_ID, appIdForInitialization, appIdForInitialization); Log.w(TAG, message); } InneractiveAdManager.initialize(context, appIdForInitialization); waitForInitializationStatusAndReport(completionCallback); }
Source:
<code>public Properties getKafkaProperties() { <START> return kafkaProperties; <END> }</code><technical_language>worth return immutable copy here</technical_language>

Target:
public Properties getKafkaProperties() { return (Properties) kafkaProperties.clone(); }
Source:
<code>public void characters(String text) { assertOpenBlock(); <START> try { <END> for (int x = 0; x < text.length(); ++x) { char c = text.charAt(x); currentBlock.write(c); } } catch (IOException e) { throw new RuntimeException(e); } }</code><technical_language>currentBlock.write(text) here</technical_language>

Target:
public void characters(String text) { assertOpenBlock(); try { currentBlock.write(text); } catch (IOException e) { throw new RuntimeException(e); } }
Source:
<code>protected void delete(ConceptStopWord delegate, String reason, RequestContext context) throws ResponseException { <START> Context.getConceptService().deleteConceptStopWord(delegate.getId()); <END> }</code><technical_language>I deleteConceptStopWord is a purge operation retiring. inconsistency. Please deleteConceptStopWord in purge throw ResourceDoesNotSupportOperationException here</technical_language>

Target:
protected void delete(ConceptStopWord delegate, String reason, RequestContext context) throws ResponseException { throw new ResourceDoesNotSupportOperationException(); }
Source:
<code>public void setB(ItemMeta cb, Boolean fb, ItemStack d) { cb.setUnbreakable(fb); <START> } <END></code><technical_language>issue above</technical_language>

Target:
public void setB(ItemMeta cb, Boolean fb, ItemStack d) { NmsItemStackMetaUnbreakable.get().setUnbreakable(cb,fb); }
Source:
<code>private int getStartIndexOfTime(GenericColumn timeValues, long time, boolean inclusive) { int low = 0; int high = timeValues.length() - 1; while (low <= high) { int mid = (low + high) >>> 1; long midVal = timeValues.getLongSingleValueRow(mid); if (midVal < time) low = mid + 1; else if (midVal > time) high = mid - 1; else { int i; for (i = mid - 1; i >= 0; i--) { long prev = timeValues.getLongSingleValueRow(i); if (time != prev) { break; } } return inclusive ? i + 1 : i; } } <START> return low; <END> }</code><technical_language>I this lead include extra row for endTime, ? want return -1 for inclusive = false. caller of this method need care of boundary condition this method returns -1</technical_language>

Target:
protected int getStartIndexOfTime(GenericColumn timeValues, long time, boolean inclusive) { int low = 0; int high = timeValues.length() - 1; while (low <= high) { int mid = (low + high) >>> 1; long midVal = timeValues.getLongSingleValueRow(mid); if (midVal < time) low = mid + 1; else if (midVal > time) high = mid - 1; else { int i; for (i = mid - 1; i >= 0; i--) { long prev = timeValues.getLongSingleValueRow(i); if (time != prev) { break; } } return inclusive ? i + 1 : i; } } return inclusive ? low : low - 1; }
Source:
<code>void onEnterKeyDown(KeyDownEvent event) { <START> if (event.getNativeKeyCode() == 13) { <END> onItemSelected(event); } }</code><technical_language>please <LINK_0></technical_language>

Target:
void onEnterKeyDown(KeyDownEvent event) { if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { onItemSelected(event); } }
Source:
<code>public boolean createMenu(final MenuModel menu) { if (menu == null || TextUtils.isEmpty(menu.name)) return false; String path = formatPath(CREATE_MENU_REST_PATH, null); Map<String, String> params = new HashMap<>(); params.put(MENU_NAME_KEY, menu.name); WordPress.getRestClientUtilsV1_1().post(path, params, null, new RestRequest.Listener() { @Override public void onResponse(JSONObject response) { menu.menuId = response.optLong(MENU_ID_KEY); <START> mDelegate.onMenuCreated(HttpURLConnection.HTTP_OK, menu); <END> } }, new RestRequest.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { mDelegate.onMenuCreated(statusCodeFromVolleyError(error), menu); } }); return true; }</code><technical_language>Sounds great</technical_language>

Target:
public int createMenu(final MenuModel menu) { if (menu == null || TextUtils.isEmpty(menu.name)) return -1; final int requestId = ++mRequestCounter; String path = formatPath(CREATE_MENU_REST_PATH, null); Map<String, String> params = new HashMap<>(); params.put(MENU_NAME_KEY, menu.name); WordPress.getRestClientUtilsV1_1().post(path, params, null, new RestRequest.Listener() { @Override public void onResponse(JSONObject response) { menu.menuId = response.optLong(MENU_ID_KEY); mListener.onMenuCreated(requestId, menu); } }, new RestRequest.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { int statusCode = statusCodeFromVolleyError(volleyError); REST_ERROR error = REST_ERROR.CREATE_ERROR; if (statusCode == HTTP_FORBIDDEN) error = REST_ERROR.AUTHENTICATION_ERROR; mListener.onErrorResponse(requestId, error); } }); return requestId; }
Source:
<code>protected boolean canDoAction() { parameter = getParameters(); if (parameter == null || parameter.getVolumeId() == null || parameter.getSlaveNodeIp() == null || parameter.getSlaveVolumeName() == null) { <START> return false; <END> } if(masterVolume == null) { return false; } masterVolume = getGlusterVolumeDao().getById(parameter.getVolumeId()); if (masterVolume.getStatus() == GlusterStatus.DOWN) { return false; } return true; }</code><technical_language>want return a specific validation error. like, "Slave host name is required" "Slave volumes is required"</technical_language>

Target:
protected boolean canDoAction() { parameter = getParameters(); if (parameter == null) { return false; } if (getGlusterVolume() == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_INVALID); return false; } if (parameter.getSlaveNodeIp() == null) { failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_INVALID_VDS_HOSTNAME); return false; } masterVolume = getGlusterVolumeDao().getById(parameter.getVolumeId()); if (masterVolume == null) { return false; } if (masterVolume.getStatus() == GlusterStatus.DOWN) { return false; } return true; }
Source:
<code><START> public List<WebElement> getOngoingSessionsRows() { <END> return ongoingSessionsTable.findElement(By.tagName("tbody")).findElements(By.tagName("tr")); }</code><technical_language>I avoid returning WebElements want minimize interaction of page object</technical_language>

Target:
private List<WebElement> getOngoingSessionsRows() { return ongoingSessionsTable.findElement(By.tagName("tbody")).findElements(By.tagName("tr")); }
Source:
<code>private Multimap<CorruptionCheckViolation, NamespaceAndUseCase> getViolationsToNamespaceToUseCaseMultimap() { <START> List<CompletePaxosHistoryForNamespaceAndUseCase> historyForAll = getHistory(); <END> return HistoryAnalyzer.corruptionHealthReportForHistory(historyForAll).violatingStatusesToNamespaceAndUseCase(); }</code><technical_language>inline this variable - method call is shorter variable</technical_language>

Target:
private Multimap<CorruptionCheckViolation, NamespaceAndUseCase> getViolationsToNamespaceToUseCaseMultimap() { return HistoryAnalyzer.corruptionHealthReportForHistory(getHistory()).violatingStatusesToNamespaceAndUseCase(); }
Source:
<code>public void initResources(Display display) { if (stockImages == null) { stockImages = new Image[stockImageLocations.length]; for (int i = 0; i < stockImageLocations.length; ++i) { Image image = createStockImage(display, stockImageLocations[i]); if (image == null) { freeResources(); throw new IllegalStateException( FileViewer.getResourceString("error.CouldNotLoadResources")); } stockImages[i] = image; } } if (stockCursors == null) { stockCursors = new Cursor[] { null, display.getSystemCursor(SWT.CURSOR_WAIT) }; } iconCache = new HashMap<Program, <START> Image>(); <END> }</code><technical_language>introduce redundant type arguments in bundles moved 1.7+</technical_language>

Target:
public void initResources(Display display) { if (stockImages == null) { stockImages = new Image[stockImageLocations.length]; for (int i = 0; i < stockImageLocations.length; ++i) { Image image = createStockImage(display, stockImageLocations[i]); if (image == null) { freeResources(); throw new IllegalStateException( FileViewer.getResourceString("error.CouldNotLoadResources")); } stockImages[i] = image; } } if (stockCursors == null) { stockCursors = new Cursor[] { null, display.getSystemCursor(SWT.CURSOR_WAIT) }; } iconCache = new HashMap<>(); }
Source:
<code>public void create(final String version, List<String> participants) { String barrierRoot = keyBuilder.getBarrierRoot(); String barrierParticipantsPath = keyBuilder.getBarrierParticipantsPath(version); zkUtils.makeSurePersistentPathsExists(new String[]{ barrierRoot, keyBuilder.getBarrierPath(version), barrierParticipantsPath, keyBuilder.getBarrierStatePath(version)}); LOG.info("Subscribing for child changes at " + barrierParticipantsPath); <START> zkUtils.getZkClient().subscribeChildChanges(barrierParticipantsPath, new ZkBarrierChangeHandler(version, participants, zkUtils)); <END> barrierListenerOptional.ifPresent(zkBarrierListener -> zkBarrierListener.onBarrierCreated(version)); }</code><technical_language>zkUtils.subscribeChildChanges? metrics get lost</technical_language>

Target:
public void create(final String version, List<String> participants) { String barrierRoot = keyBuilder.getBarrierRoot(); String barrierParticipantsPath = keyBuilder.getBarrierParticipantsPath(version); zkUtils.makeSurePersistentPathsExists(new String[]{ barrierRoot, keyBuilder.getBarrierPath(version), barrierParticipantsPath, keyBuilder.getBarrierStatePath(version)}); LOG.info("Subscribing for child changes at " + barrierParticipantsPath); zkUtils.subscribeChildChanges(barrierParticipantsPath, new ZkBarrierChangeHandler(version, participants, zkUtils)); barrierListenerOptional.ifPresent(zkBarrierListener -> zkBarrierListener.onBarrierCreated(version)); }
Source:
<code>public List<BibEntry> performSearch(String query) throws FetcherException { try { obtainAndModifyCookie(); List<BibEntry> foundEntries = new ArrayList<>(20); URIBuilder uriBuilder = new URIBuilder(BASIC_SEARCH_URL); uriBuilder.addParameter("hl", "en"); uriBuilder.addParameter("btnG", "Search"); uriBuilder.addParameter("q", query); try { addHitsFromQuery(foundEntries, uriBuilder.toString()); if (foundEntries.size() == 10) { uriBuilder.addParameter("start", "10"); addHitsFromQuery(foundEntries, uriBuilder.toString()); } <START> } catch (IOException e) { <END> LOGGER.info("IOException for URL {}", uriBuilder.toString()); if (e.getMessage().contains("Server returned HTTP response code: 503 for URL")) { throw new FetcherException("Fetching from Google Scholar failed.", Localization.lang("This might be caused by reaching the traffic limitation of Google Scholar (see 'Help' for details)."), e); } else { throw new FetcherException("Error while fetching from " + getName(), e); } } return foundEntries; } catch (URISyntaxException e) { throw new FetcherException("Error while fetching from " + getName(), e); } }</code><technical_language>Similar above, moved try block</technical_language>

Target:
public List<BibEntry> performSearch(String query) throws FetcherException { LOGGER.debug("Using URL {}", query); obtainAndModifyCookie(); List<BibEntry> foundEntries = new ArrayList<>(20); URIBuilder uriBuilder = null; try { uriBuilder = new URIBuilder(BASIC_SEARCH_URL); } catch (URISyntaxException e) { throw new FetcherException("Error while fetching from " + getName() + " at URL " + BASIC_SEARCH_URL, e); } uriBuilder.addParameter("hl", "en"); uriBuilder.addParameter("btnG", "Search"); uriBuilder.addParameter("q", query); String queryURL = uriBuilder.toString(); try { addHitsFromQuery(foundEntries, queryURL); } catch (IOException e) { if (e.getMessage().contains("Server returned HTTP response code: 503 for URL")) { throw new FetcherException("Fetching from Google Scholar at URL " + queryURL + " failed.", Localization.lang("This might be caused by reaching the traffic limitation of Google Scholar (see 'Help' for details)."), e); } else { throw new FetcherException("Error while fetching from " + getName() + " at URL " + queryURL, e); } } return foundEntries; }
Source:
<code>protected GoVisitor buildGoVisitor(@NotNull final ProblemsHolder holder, @SuppressWarnings({"UnusedParameters", "For future"}) @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitStructType(@NotNull GoStructType o) { <START> super.visitStructType(o); <END> for (GoFieldDeclaration field : o.getFieldDeclarationList()) { ProgressManager.checkCanceled(); GoTag tag = field.getTag(); if (tag == null) continue; if (!isValidTag(tag)) { holder.registerProblem(tag, "Bad syntax for struct tag value"); } } } }; }</code><technical_language>redundant, invoke checkCanceled this statement</technical_language>

Target:
protected GoVisitor buildGoVisitor(@NotNull final ProblemsHolder holder, @SuppressWarnings({"UnusedParameters", "For future"}) @NotNull LocalInspectionToolSession session) { return new GoVisitor() { @Override public void visitStructType(@NotNull GoStructType o) { for (GoFieldDeclaration field : o.getFieldDeclarationList()) { ProgressManager.checkCanceled(); GoTag tag = field.getTag(); if (tag == null) continue; if (!isValidTag(tag)) { holder.registerProblem(tag, "Bad syntax for struct tag value"); } } } }; }
Source:
<code>public String toString() { if (section == null) <START> return "<emtpy>"; <END> StringBuilder b = new StringBuilder("[").append(section); if (subsection != null) b.append(".").append(subsection); if (name != null) b.append(".").append(name); b.append("]"); if (value != null) b.append("=").append(value); return b.toString(); }</code><technical_language>typo empty</technical_language>

Target:
public String toString() { if (section == null) return "<empty>"; StringBuilder b = new StringBuilder(section); if (subsection != null) b.append(".").append(subsection); if (name != null) b.append(".").append(name); if (value != null) b.append("=").append(value); return b.toString(); }
Source:
<code>public static Registry getConfigurationRegistry() throws DeviceTypeMgtPluginException { try { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); org.wso2.carbon.registry.core.service.RegistryService registryService = DeviceTypeExtensionDataHolder .getInstance().getRegistryService(); <START> return registryService == null ? null : registryService.getConfigSystemRegistry(tenantId); <END> } catch (RegistryException e) { throw new DeviceTypeMgtPluginException("Error in retrieving conf registry instance: " + e.getMessage(), e); } }</code><technical_language>need throw exception resgistry service is null? do succesful operation if registry service is null here</technical_language>

Target:
public static Registry getConfigurationRegistry() throws DeviceTypeMgtPluginException { try { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); org.wso2.carbon.registry.core.service.RegistryService registryService = DeviceTypeExtensionDataHolder .getInstance().getRegistryService(); if (registryService == null) { throw new DeviceTypeMgtPluginException("Registry Service is not initialized properly"); } return registryService.getConfigSystemRegistry(tenantId); } catch (RegistryException e) { throw new DeviceTypeMgtPluginException("Error in retrieving conf registry instance: " + e.getMessage(), e); } }
Source:
<code>private static LocalDate changeYear(LocalDate localDate, int yearsDelta) { final Calendar calendar = Calendar.getInstance(); <START> calendar.set(Calendar.YEAR, localDate.getYear()); <END> calendar.set(Calendar.MONTH, localDate.getMonthValue() - 1); calendar.set(Calendar.DAY_OF_MONTH, localDate.getDay()); calendar.add(Calendar.YEAR, yearsDelta); final int year = calendar.get(Calendar.YEAR); final MonthOfYear month = MonthOfYears.getMonth(calendar); final int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH); final LocalDate result = LocalDate.newBuilder() .setYear(year) .setMonth(month) .setDay(dayOfMonth) .build(); return result; }</code><technical_language>Please add on-demand static import for Calendar</technical_language>

Target:
private static LocalDate changeYear(LocalDate localDate, int yearsDelta) { final Calendar cal = createDate(localDate.getYear(), localDate.getMonthValue(), localDate.getDay()); cal.add(YEAR, yearsDelta); final LocalDate result = LocalDate.newBuilder() .setYear(getYear(cal)) .setMonth(Calendars.getMonthOfYear(cal)) .setDay(getDay(cal)) .build(); return result; }
Source:
<code>private void gc() { Ref r; while ((r = (Ref) queue.poll()) != null) { clear(r); boolean found = false; final int s = slot(r.pack, r.position); final Entry e1 = table.get(s); for (Entry n = e1; n != null; n = n.next) { if (n.ref == r) { n.dead = true; found = true; break; } } if (found) { <START> table.compareAndSet(s, e1, clean(e1)); <END> } } }</code><technical_language>Move this loop in place of "found = true" remove "found" variable</technical_language>

Target:
private void gc() { Ref r; while ((r = (Ref) queue.poll()) != null) { clear(r); final int s = slot(r.pack, r.position); final Entry e1 = table.get(s); for (Entry n = e1; n != null; n = n.next) { if (n.ref == r) { n.dead = true; table.compareAndSet(s, e1, clean(e1)); break; } } } }
Source:
<code>public void onLoadProjectSuccess(boolean startProjectActivity) { if (getActivity() == null) { <START> Log.e(TAG, "Null Value of getActivity() at onLoadProjectSuccess"); <END> return; } Intent intent = new Intent(getActivity(), ProjectActivity.class); intent.putExtra(Constants.PROJECT_OPENED_FROM_PROJECTS_LIST, true); getActivity().startActivity(intent); }</code><technical_language>need check for null Task triggers this callback canceled anyway. If problem exists, Crashlytics us</technical_language>

Target:
public void onLoadProjectSuccess(boolean startProjectActivity) { Intent intent = new Intent(getActivity(), ProjectActivity.class); intent.putExtra(Constants.PROJECT_OPENED_FROM_PROJECTS_LIST, true); getActivity().startActivity(intent); }
Source:
<code>public void addNode(@Nullable Long parentId, long id, V value) { <START> if (parentId != null && parentId.equals(id)) return; <END> Node<V> node = new Node<V>().value(value); if (parentId == null && rootNode == null) { rootNode = node; } else { idToNode.put(id, node); idToParent.put(id, parentId); } }</code><technical_language>dropping datas, log wrong ? IMO, dropping data is a good deal this problem people need datas a problem</technical_language>

Target:
public boolean addNode(@Nullable Long parentId, long id, V value) { if (parentId == null) { if (rootId != null) { if (logger.isLoggable(FINE)) { logger.fine(format( "attributing span missing parent to root: traceId=%s, rootSpanId=%s, spanId=%s", traceId, toLowerHex(rootId), toLowerHex(id))); } } else { rootId = id; } } else if (parentId == id) { if (logger.isLoggable(FINE)) { logger.fine( format("skipping circular dependency: traceId=%s, spanId=%s", traceId, toLowerHex(id))); } return false; } Node<V> node = new Node<V>().value(value); if (parentId == null && rootNode == null) { rootNode = node; rootId = id; } else { idToNode.put(id, node); idToParent.put(id, parentId); } return true; }
Source:
<code>public FilterTreeManager(String filterString, SCIMResourceTypeSchema schema) throws IOException { this.schema = schema; input = new StreamTokenizer(new StringReader(filterString)); input.resetSyntax(); input.wordChars('a', 'z'); input.wordChars('A', 'Z'); input.wordChars(128 + 32, 255); input.whitespaceChars(0, ' '); input.commentChar('/'); input.quoteChar('"'); input.quoteChar('\''); input.wordChars('@', '@'); input.wordChars(':', ':'); input.wordChars('_', '_'); input.wordChars('0', '9'); input.wordChars('-', '-'); input.wordChars('+', '+'); <START> input.wordChars('.', '.'); <END> tokenList = new ArrayList<String>(); String concatenatedString = ""; while (input.nextToken() != StreamTokenizer.TT_EOF) { if (input.ttype == 40) { tokenList.add("("); } else if (input.ttype == 41) { concatenatedString = concatenatedString.trim(); tokenList.add(concatenatedString); concatenatedString = ""; tokenList.add(")"); } else if (input.ttype == StreamTokenizer.TT_WORD) { if (!(input.sval.equalsIgnoreCase(SCIMConstants.OperationalConstants.AND) || input.sval.equalsIgnoreCase(SCIMConstants.OperationalConstants.OR) || input.sval.equalsIgnoreCase(SCIMConstants.OperationalConstants.NOT))) { concatenatedString += " " + input.sval; } else { concatenatedString = concatenatedString.trim(); if (!concatenatedString.equals("")) { tokenList.add(concatenatedString); concatenatedString = ""; } tokenList.add(input.sval); } } } if (!(concatenatedString.equals(""))) { tokenList.add(concatenatedString); } }</code><technical_language>* character? Is covered of</technical_language>

Target:
public FilterTreeManager(String filterString, SCIMResourceTypeSchema schema) throws IOException { this.schema = schema; input = new StreamTokenizer(new StringReader(filterString)); input.resetSyntax(); input.wordChars('a', 'z'); input.wordChars('A', 'Z'); input.wordChars(128 + 32, 255); input.whitespaceChars(0, ' '); input.commentChar('/'); input.quoteChar('"'); input.quoteChar('\''); input.wordChars('@', '@'); input.wordChars(':', ':'); input.wordChars('_', '_'); input.wordChars('0', '9'); input.wordChars('-', '-'); input.wordChars('+', '+'); input.wordChars('.', '.'); input.wordChars('*', '*'); tokenList = new ArrayList<String>(); String concatenatedString = ""; while (input.nextToken() != StreamTokenizer.TT_EOF) { if (input.ttype == 40) { tokenList.add("("); } else if (input.ttype == 41) { concatenatedString = concatenatedString.trim(); tokenList.add(concatenatedString); concatenatedString = ""; tokenList.add(")"); } else if (input.ttype == StreamTokenizer.TT_WORD) { if (!(input.sval.equalsIgnoreCase(SCIMConstants.OperationalConstants.AND) || input.sval.equalsIgnoreCase(SCIMConstants.OperationalConstants.OR) || input.sval.equalsIgnoreCase(SCIMConstants.OperationalConstants.NOT))) { concatenatedString += " " + input.sval; } else { concatenatedString = concatenatedString.trim(); if (!concatenatedString.equals("")) { tokenList.add(concatenatedString); concatenatedString = ""; } tokenList.add(input.sval); } } } if (!(concatenatedString.equals(""))) { tokenList.add(concatenatedString); } }
Source:
<code>default N setName(String name) { <START> return setName(Name.parse(name)); <END> }</code><technical_language>Do hate static imports? :)</technical_language>

Target:
default N setName(String name) { assertNonEmpty(name); return setName(Name.parse(name)); }
Source:
<code>public void testMvccEnabledForClientMode() throws Exception { String attrName = "has_cache"; Object attrVal = Boolean.TRUE; final IgniteEx crd = (IgniteEx) startGrid(getTestIgniteInstanceName(0), getConfiguration()); <START> CacheConfiguration ccfg = defaultCacheConfiguration() <END> .setNearConfiguration(null) .setNodeFilter(new AttributeNodeFilter(attrName, attrVal)) .setBackups(0) .setAtomicityMode(TRANSACTIONAL_SNAPSHOT); final Ignite node = startGrid(getTestIgniteInstanceName(1), getConfiguration() .setCacheConfiguration(ccfg) .setUserAttributes(F.asMap(attrName, attrVal))); checkTopology(2); assertTrue(crd.context().coordinators().mvccEnabled()); }</code><technical_language>Do need near, backups, atomicity mode here</technical_language>

Target:
public void testMvccEnabledForClientMode() throws Exception { String attrName = "has_cache"; Object attrVal = Boolean.TRUE; final IgniteEx crd = (IgniteEx) startGrid(getTestIgniteInstanceName(0), getConfiguration()); CacheConfiguration ccfg = defaultCacheConfiguration() .setNearConfiguration(null) .setNodeFilter(new AttributeNodeFilter(attrName, attrVal)) .setAtomicityMode(TRANSACTIONAL_SNAPSHOT); final IgniteEx node = (IgniteEx) startGrid(getTestIgniteInstanceName(1), getConfiguration() .setCacheConfiguration(ccfg) .setUserAttributes(F.asMap(attrName, attrVal))); checkTopology(2); assertTrue(crd.context().coordinators().mvccEnabled()); assertTrue(node.context().coordinators().mvccEnabled()); }
Source:
<code>public Set<PortletCategory> getParentCategories(IPortletDefinition child) { String childKey = child.getPortletDefinitionId().getStringId(); IEntity childEntity = GroupService.getEntity(childKey, IPortletDefinition.class); Set<PortletCategory> parents = new HashSet<PortletCategory>(); <START> Iterator<IEntityGroup> iter = childEntity.getParentGroups().iterator(); <END> while (iter.hasNext()) { IGroupMember gm = iter.next(); if (gm.isGroup()) { String categoryId = gm.getKey(); parents.add(getPortletCategory(categoryId)); } } return parents; }</code><technical_language>Couple of for refactors in this file this PR</technical_language>

Target:
public Set<PortletCategory> getParentCategories(IPortletDefinition child) { String childKey = child.getPortletDefinitionId().getStringId(); IEntity childEntity = GroupService.getEntity(childKey, IPortletDefinition.class); Set<PortletCategory> parents = new HashSet<PortletCategory>(); for (IGroupMember gm : childEntity.getParentGroups()) { if (gm.isGroup()) { String categoryId = gm.getKey(); parents.add(getPortletCategory(categoryId)); } } return parents; }
Source:
<code>public void selectArchetype(String catalog, final String archetype, final String groupId){ new DefaultCombo(0).setSelection(catalog); new WaitWhile(new JobIsRunning(), TimePeriod.VERY_LONG); new WaitUntil(new TableHasRows(new DefaultTable()),TimePeriod.LONG); DefaultTable table = new DefaultTable(); <START> <END> @SuppressWarnings("unchecked") List<TableItem> items = table.getItems(new Matcher<TableItem>() { @Override public void describeTo(Description arg0) @Override public void _dont_implement_Matcher___instead_extend_BaseMatcher_() @Override public void describeMismatch(Object arg0, Description arg1) @Override public boolean matches(Object arg0) { DefaultTableItem ti = (DefaultTableItem)arg0; return ((groupId != null && ti.getText(0).matches(".*"+groupId+".*")) || groupId == null) && ti.getText(1).matches(".*"+archetype+".*"); }}); items.get(0).select(); }</code><technical_language>I getItem(final String itemText, int column) in <LINK_0> filter in wizard instead of matcher delete TODO</technical_language>

Target:
public void selectArchetype(String catalog, final String archetype, final String groupId){ new DefaultCombo(0).setSelection(catalog); new WaitWhile(new JobIsRunning(), TimePeriod.VERY_LONG); new WaitUntil(new TableHasRows(new DefaultTable()),TimePeriod.LONG); DefaultTable table = new DefaultTable(); @SuppressWarnings("unchecked") List<TableItem> items = table.getItems(new ArtifactIdAndGroupIdMatcher(groupId, archetype)); items.get(0).select(); }
Source:
<code>public void testIllegalCombinationsForCredentialReference() throws Exception { <START> final ModelNodeResult bridgePassword = operations.readAttribute(BRIDGE_ADDRESS, PASSWORD); <END> try { undefineBridgePassword(); navigateToBridgeTab(); page.switchToCredentialReference(); new ElytronIntegrationChecker.Builder(client) .address(BRIDGE_ADDRESS) .configFragment(page.getConfigFragment()) .build() .testIllegalCombinationCredentialReferenceAttributes(); } finally { operations.writeAttribute(BRIDGE_ADDRESS, PASSWORD, bridgePassword.value()); } }</code><technical_language>ignore default values => ReadAttributeOption.NOT_INCLUDE_DEFAULTS</technical_language>

Target:
public void testIllegalCombinationsForCredentialReference() throws Exception { final ModelNodeResult bridgePassword = operations.readAttribute(BRIDGE_ADDRESS, PASSWORD, ReadAttributeOption.NOT_INCLUDE_DEFAULTS); try { undefineBridgePassword(); navigateToBridgeTab(); page.switchToCredentialReference(); new ElytronIntegrationChecker.Builder(client) .address(BRIDGE_ADDRESS) .configFragment(page.getConfigFragment()) .build() .testIllegalCombinationCredentialReferenceAttributes(); } finally { operations.writeAttribute(BRIDGE_ADDRESS, PASSWORD, bridgePassword.value()); } }
Source:
<code>Person ingestPerson(org.atlasapi.remotesite.pa.profiles.bindings.Person paPerson) { Person person = new Person(); person.setCanonicalUri(PERSON_URI_PREFIX + paPerson.getId()); Name name = paPerson.getName(); person.withName(name.getFirstname() + " " + name.getLastname()); person.setGivenName(name.getFirstname()); person.setFamilyName(name.getLastname()); person.setGender(paPerson.getGender()); if (paPerson.getBorn() != null) { person.setBirthDate(dateTimeFormatter.parseDateTime(paPerson.getBorn())); } <START> if (paPerson.getBornIn() != null) { <END> person.setBirthPlace(paPerson.getBornIn()); } person.setDescription(paPerson.getEarlyLife() + "\n\n" + paPerson.getCareer()); person.addQuote(paPerson.getQuote()); person.setPublisher(Publisher.PA_PEOPLE); return person; }</code><technical_language>Do need this null check here? do person.setBirthPlace(paPerson.getBornIn())</technical_language>

Target:
Person ingestPerson(org.atlasapi.remotesite.pa.profiles.bindings.Person paPerson) { Person person = new Person(); person.setCanonicalUri(PERSON_URI_PREFIX + paPerson.getId()); Name name = paPerson.getName(); person.withName(name.getFirstname() + " " + name.getLastname()); person.setGivenName(name.getFirstname()); person.setFamilyName(name.getLastname()); person.setGender(paPerson.getGender()); if (paPerson.getBorn() != null) { person.setBirthDate(dateTimeFormatter.parseDateTime(paPerson.getBorn())); } person.setBirthPlace(paPerson.getBornIn()); person.setDescription(paPerson.getEarlyLife() + "\n\n" + paPerson.getCareer()); person.addQuote(paPerson.getQuote()); person.setPublisher(Publisher.PA_PEOPLE); return person; }
Source:
<code>public SubPeer(SocketAddress remoteAddress, @NotNull SubChannel subChannel) { <START> if (subChannel == null) { <END> throw new NullPointerException("`subChannel` cannot be null"); } this.remoteAddress = remoteAddress; this.peerManager = subChannel.getPeerManager(); this.direction = subChannel.getPreferredDirection(); }</code><technical_language>need for manual check</technical_language>

Target:
public SubPeer(SocketAddress remoteAddress, @NotNull SubChannel subChannel) { this.remoteAddress = remoteAddress; this.peerManager = subChannel.getPeerManager(); this.direction = subChannel.getPreferredDirection(); }
Source:
<code>public TimeLockServices createTimeLockServices( String client, Supplier<ManagedTimestampService> rawTimestampServiceSupplier, Supplier<LockService> rawLockServiceSupplier) { log.info("Creating async timelock services for client {}", SafeArg.of("client", client)); AsyncOrLegacyTimelockService asyncOrLegacyTimelockService; AsyncTimelockService asyncTimelockService = instrumentInLeadershipProxy( metricsManager.getTaggedRegistry(), AsyncTimelockService.class, () -> createRawAsyncTimelockService(client, rawTimestampServiceSupplier), client); asyncOrLegacyTimelockService = AsyncOrLegacyTimelockService.createFromAsyncTimelock( new AsyncTimelockResource(lockLog, asyncTimelockService)); LockService lockService = instrumentInLeadershipProxy( metricsManager.getTaggedRegistry(), LockService.class, asyncLockConfiguration.disableLegacySafetyChecksWarningPotentialDataCorruption() ? rawLockServiceSupplier : JavaSuppliers.compose(NonTransactionalLockService::new, rawLockServiceSupplier), client); <START> leadershipCreator.executeWhenLostLeadership(this::deregisterLeaderMetrics); <END> return TimeLockServices.create( asyncTimelockService, lockService, asyncOrLegacyTimelockService, asyncTimelockService); }</code><technical_language>Do need a similar method gain leadership deregister metrics isCurrentSuspectedLeader=false</technical_language>

Target:
public TimeLockServices createTimeLockServices( String client, Supplier<ManagedTimestampService> rawTimestampServiceSupplier, Supplier<LockService> rawLockServiceSupplier) { log.info("Creating async timelock services for client {}", SafeArg.of("client", client)); AsyncOrLegacyTimelockService asyncOrLegacyTimelockService; AsyncTimelockService asyncTimelockService = instrumentInLeadershipProxy( metricsManager.getTaggedRegistry(), AsyncTimelockService.class, () -> createRawAsyncTimelockService(client, rawTimestampServiceSupplier), client); asyncOrLegacyTimelockService = AsyncOrLegacyTimelockService.createFromAsyncTimelock( new AsyncTimelockResource(lockLog, asyncTimelockService)); LockService lockService = instrumentInLeadershipProxy( metricsManager.getTaggedRegistry(), LockService.class, asyncLockConfiguration.disableLegacySafetyChecksWarningPotentialDataCorruption() ? rawLockServiceSupplier : JavaSuppliers.compose(NonTransactionalLockService::new, rawLockServiceSupplier), client); leadershipCreator.executeWhenLostLeadership(() -> metricsManager.deregisterTaggedMetrics(withTagIsCurrentSuspectedLeader(true))); leadershipCreator.executeWhenGainedLeadership(() -> metricsManager.deregisterTaggedMetrics(withTagIsCurrentSuspectedLeader(false))); return TimeLockServices.create( asyncTimelockService, lockService, asyncOrLegacyTimelockService, asyncTimelockService); }
Source:
<code>private void providerList(final Date date, FetchListener listener) { fetchListener = listener; HashMap<String, String> params = new HashMap<>(); if (date != null) { params.put(SEConstants.KEY_FROM_DATE, SEDateTools.parseDateToShortString(date)); } if (providerArray == null || providerArray.isEmpty()) { providerArray = new ArrayList<>(); } sendGETRequest(SEConstants.PROVIDERS_URL.concat(nextPageId), params, "", new SEHTTPResponseHandler(new SEHTTPResponseHandler.RestAPIListener() { @Override public void onFailureResponse(int statusCode, JSONObject errorResponse) { onFail(errorResponse); } @Override public void onSuccessResponse(int statusCode, JSONObject response) { Gson gson = new Gson(); String providerArrayString = SEJSONTools.getArray(response, SEConstants.KEY_DATA).toString(); for (SEProvider entry : gson.fromJson(providerArrayString, SEProvider[].class)) { providerArray.add(entry); } <START> nextPageId = paginationAvailable(response); <END> if (nextPageId.isEmpty()) { providerArray.clear(); onSuccess(providerArray); } else { providerList(date, fetchListener); } } })); }</code><technical_language>rename method</technical_language>

Target:
private void providerList(final Date date, FetchListener listener) { fetchListener = listener; HashMap<String, String> params = new HashMap<>(); if (date != null) { params.put(SEConstants.KEY_FROM_DATE, SEDateTools.parseDateToShortString(date)); } if (providerArray == null || nextPageId.isEmpty()) { providerArray = new ArrayList<>(); } sendGETRequest(SEConstants.PROVIDERS_URL.concat(nextPageId), params, "", new SEHTTPResponseHandler(new SEHTTPResponseHandler.RestAPIListener() { @Override public void onFailureResponse(int statusCode, JSONObject errorResponse) { onFail(errorResponse); } @Override public void onSuccessResponse(int statusCode, JSONObject response) { Gson gson = new Gson(); String providerArrayString = SEJSONTools.getArray(response, SEConstants.KEY_DATA).toString(); providerArray.addAll(Arrays.asList(gson.fromJson(providerArrayString, SEProvider[].class))); String pageId = getNextPageId(response); nextPageId = pageId.equals(nextPageId) ? "" : pageId; if (nextPageId.isEmpty()) { onSuccess(providerArray); } else { providerList(date, fetchListener); } } })); }
Source:
<code>public void stop() { if (isRunning()) { <START> LOGGER.info("Kill interpreter process for interpreter group: " + getInterpreterGroupId()); <END> try { callRemoteFunction(new RemoteFunction<Void>() { @Override public Void call(RemoteInterpreterService.Client client) throws Exception { client.shutdown(); return null; } }); } catch (Exception e) { LOGGER.warn("ignore the exception when shutting down", e); } shutdown(); this.interpreterProcessLauncher.stop(); this.interpreterProcessLauncher = null; LOGGER.info("Remote process of interpreter group: " + getInterpreterGroupId() + " is terminated"); } }</code><technical_language>avoid creation of objects if a logging level is disabled. String concatenation creates a new String object. This line change LOGGER.info("Kill interpreter process for interpreter group: {}", getInterpreterGroupId());</technical_language>

Target:
public void stop() { if (isRunning()) { LOGGER.info("Kill interpreter process for interpreter group: {}", getInterpreterGroupId()); try { callRemoteFunction(new RemoteFunction<Void>() { @Override public Void call(RemoteInterpreterService.Client client) throws Exception { client.shutdown(); return null; } }); } catch (Exception e) { LOGGER.warn("ignore the exception when shutting down", e); } shutdown(); this.interpreterProcessLauncher.stop(); this.interpreterProcessLauncher = null; LOGGER.info("Remote process of interpreter group: is terminated", getInterpreterGroupId()); } }
Source:
<code>protected boolean canReplaceBiome(int biomeId) { Biome biome = Biome.getBiomeForId(biomeId); if (biome == null) { if (BCLib.DEV) <START> BCLog.logger.warn("Couldn't find a biome with an ID of " + biomeId); <END> return false; } return BiomeDictionary.getTypes(biome).containsAll(REQUIRED_TYPES); }</code><technical_language>removing log fine actually, for in dev</technical_language>

Target:
protected boolean canReplaceBiome(int biomeId) { Biome biome = Biome.getBiomeForId(biomeId); if (biome == null) { return false; } return BiomeDictionary.getTypes(biome).containsAll(REQUIRED_TYPES); }
Source:
<code>@Test public void responseConverterFactorySkippedNoMatchThrows() { Type type = String.class; Annotation[] annotations = new Annotation[0]; NonMatchingConverterFactory nonMatchingFactory1 = new NonMatchingConverterFactory(); NonMatchingConverterFactory nonMatchingFactory2 = new NonMatchingConverterFactory(); Retrofit retrofit = new Retrofit.Builder() .baseUrl("<LINK_0>") .addConverterFactory(nonMatchingFactory1) .addConverterFactory(nonMatchingFactory2) .build(); try { retrofit.nextResponseBodyConverter(nonMatchingFactory1, type, annotations); <START> } catch (IllegalArgumentException e) { <END> assertThat(e).hasMessage("" + "Could not locate ResponseBody converter for class java.lang.String.\n" + " Skipped:\n" + " * retrofit2.BuiltInConverters\n" + " * retrofit2.helpers.NonMatchingConverterFactory\n" + " Tried:\n" + " * retrofit2.helpers.NonMatchingConverterFactory"); } assertThat(nonMatchingFactory1.called).isFalse(); assertThat(nonMatchingFactory2.called).isTrue(); }</code><technical_language>fail</technical_language>

Target:
@Test public void responseConverterFactorySkippedNoMatchThrows() { Type type = String.class; Annotation[] annotations = new Annotation[0]; NonMatchingConverterFactory nonMatchingFactory1 = new NonMatchingConverterFactory(); NonMatchingConverterFactory nonMatchingFactory2 = new NonMatchingConverterFactory(); Retrofit retrofit = new Retrofit.Builder() .baseUrl("<LINK_0>") .addConverterFactory(nonMatchingFactory1) .addConverterFactory(nonMatchingFactory2) .build(); try { retrofit.nextResponseBodyConverter(nonMatchingFactory1, type, annotations); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("" + "Could not locate ResponseBody converter for class java.lang.String.\n" + " Skipped:\n" + " * retrofit2.BuiltInConverters\n" + " * retrofit2.helpers.NonMatchingConverterFactory\n" + " Tried:\n" + " * retrofit2.helpers.NonMatchingConverterFactory"); } assertThat(nonMatchingFactory1.called).isFalse(); assertThat(nonMatchingFactory2.called).isTrue(); }
Source:
<code>public void joinWithSelfThrowsException() throws Exception { StreamApplication app = new StreamApplication() { @Override public void init(StreamGraph graph, Config config) { IntegerSerde integerSerde = new IntegerSerde(); KVSerde<Integer, Integer> kvSerde = KVSerde.of(integerSerde, integerSerde); MessageStream<KV<Integer, Integer>> inStream = graph.getInputStream("instream", kvSerde); SystemStream outputSystemStream = new SystemStream("outputSystem", "outputStream"); inStream <START> .join(inStream, new TestJoinFunction(), integerSerde, kvSerde, kvSerde, JOIN_TTL, "join") <END> .sink((m, mc, tc) -> mc.send(new OutgoingMessageEnvelope(outputSystemStream, m))); } }; createStreamOperatorTask(new SystemClock(), app); }</code><technical_language>minor: sink is unnecessary for this test</technical_language>

Target:
public void joinWithSelfThrowsException() throws Exception { StreamApplication app = new StreamApplication() { @Override public void init(StreamGraph graph, Config config) { IntegerSerde integerSerde = new IntegerSerde(); KVSerde<Integer, Integer> kvSerde = KVSerde.of(integerSerde, integerSerde); MessageStream<KV<Integer, Integer>> inStream = graph.getInputStream("instream", kvSerde); inStream.join(inStream, new TestJoinFunction(), integerSerde, kvSerde, kvSerde, JOIN_TTL, "join"); } }; createStreamOperatorTask(new SystemClock(), app); }
Source:
<code>public void call() { if (that.isDone()) { handleDone(subscriber); return; } <START> long currentTime = Schedulers.computation().now(); <END> if (expireAfter > 0 && currentTime > expireAfter) { handleTimeout(subscriber); return; } long delayBy = Math.min(Math.max(INITIAL_DELAY_MICRO_SEC, (currentTime - startTime) * 1000), MAX_DELAY_MICRO_SEC); worker.schedule(this, delayBy, TimeUnit.MICROSECONDS); }</code><technical_language>This call Schedulers.computation() directly, Scheduler passed in, virtual time is possible. This is currently calling System.getTimeInMillis() is hardcoded a Scheduler</technical_language>

Target:
public void call() { if (that.isDone()) { handleDone(subscriber); return; } long currentTime = scheduler.now(); if (expireAfter > 0 && currentTime > expireAfter) { handleTimeout(subscriber); return; } long delayBy = Math.min(Math.max(INITIAL_DELAY_MICRO_SEC, (currentTime - startTime) * 1000), MAX_DELAY_MICRO_SEC); Subscription newSubscription = worker.schedule(this, delayBy, TimeUnit.MICROSECONDS); taskSubscription.set(newSubscription); }