auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> public static EnumActionResult onInteractEntityAt(EntityPlayer player, Entity entity, RayTraceResult ray, ItemStack stack, EnumHand hand) <END> { Vec3d vec3d = new Vec3d(ray.hitVec.xCoord - entity.posX, ray.hitVec.yCoord - entity.posY, ray.hitVec.zCoord - entity.posZ); return onInteractEntityAt(player, entity, vec3d, stack, hand); }</code><technical_language>This breaks binary compatibility mod calls functions. stated this NEEDs fixed</technical_language>

Target:
public static boolean onInteractEntityAt(EntityPlayer player, Entity entity, RayTraceResult ray, ItemStack stack, EnumHand hand) { return onInteractEntityAtAction(player, entity, ray, stack, hand) != null; }
Source:
<code>default EventStream<PlainTextChange> plainChanges() { return richChanges() .filter(c -> c.insertedLength() != 0 || c.removedLength() != 0) .map(c -> new PlainTextChange(c.position, c.removed.getText(), c.inserted.getText())); <START> } <END></code><technical_language>If is a rich-text change, insertedLength removedLength is non-zero already. want map filter out plain-text changes removed.equals(inserted)</technical_language>

Target:
default EventStream<PlainTextChange> plainChanges() { return richChanges() .map(c -> new PlainTextChange(c.position, c.removed.getText(), c.inserted.getText())) .filter(pc -> !pc.removed.equals(pc.inserted)); }
Source:
<code>public static byte[] convertIP6Address(String fullFormIP6Address) throws KuraException { if (fullFormIP6Address == null) { throw new KuraException(KuraErrorCode.INVALID_PARAMETER); } byte[] retVal = new byte[16]; String[] ip6Split = fullFormIP6Address.split(":"); if (ip6Split.length != 8) { throw new KuraException(KuraErrorCode.INVALID_PARAMETER); } for (int i = 0; i < 8; i++) { try { String octet = ip6Split[i]; int value = Integer.parseInt(octet, 16); if ((value < 0) || (value > 0xFFFF)) { throw new KuraException(KuraErrorCode.INVALID_PARAMETER); <START> } <END> int k = i * 2; retVal[k] = (byte) ((value >>> 8) & 0xFF); retVal[k + 1] = (byte) (value & 0xFF); } catch (NumberFormatException e) { throw new KuraException(KuraErrorCode.INVALID_PARAMETER); } } return retVal; }</code><technical_language>a runtime exception</technical_language>

Target:
public static byte[] convertIP6Address(String fullFormIP6Address) { if (fullFormIP6Address == null) { throw new IllegalArgumentException("fullFormIP6Address is null"); } byte[] retVal = new byte[16]; String[] ip6Split = fullFormIP6Address.split(":"); if (ip6Split.length != 8) { throw new IllegalArgumentException("fullFormIP6Address is invalid: " + fullFormIP6Address); } for (int i = 0; i < 8; i++) { try { String octet = ip6Split[i]; int value = Integer.parseInt(octet, 16); if ((value < 0) || (value > 0xFFFF)) { throw new IllegalArgumentException("fullFormIP6Address is invalid: " + fullFormIP6Address); } int k = i * 2; retVal[k] = (byte) ((value >>> 8) & 0xFF); retVal[k + 1] = (byte) (value & 0xFF); } catch (NumberFormatException e) { throw new IllegalArgumentException("fullFormIP6Address is invalid: " + fullFormIP6Address, e); } } return retVal; }
Source:
<code>private void runInProtocolStage(final Runnable task) { <START> <END> synchronized(executor) { if (executor == null || executor.isShutdown()) { LOGGER.log(Level.WARNING, "Trying to use already shutdown executor. Replacing it with default"); initDefaultExecutor(); } executor.execute(new Runnable() { public void run() { try { task.run(); } catch (Throwable t) { LOGGER.log(Level.SEVERE, "Exception in protocol stage thread: "+t.getMessage(), t); } } }); } }</code><technical_language>sure, that, if a endpoint is shutdown, executor restarted. If depends executor, this troubles. So, I prefer, if write, californium, a shutdown of executor issues</technical_language>

Target:
private void runInProtocolStage(final Runnable task) { executor.execute(new Runnable() { public void run() { try { task.run(); } catch (Throwable t) { LOGGER.log(Level.SEVERE, "Exception in protocol stage thread: "+t.getMessage(), t); } } }); }
Source:
<code>private String getQueryForGroup() { return "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<request>\n" + <START> "<skupina_clenove reqid=\"5\">\n" + <END> "<skupina_id></skupina_id>\n" + "<pracoviste_id>" + getAttributes().get("workplaceId") + "</pracoviste_id>\n" + "<zkratka>" + getAttributes().get("groupName") + "</zkratka>\n" + "<operace>INF</operace>\n" + "</skupina_clenove>\n" + "</request>"; }</code><technical_language>Please generate a random reqid code log Perun logs. If error IS side, tag error reqid</technical_language>

Target:
private String getQueryForGroup() throws InternalErrorException { log.debug("RequestID for ISXML ExtSource group " + workplace + ":" + groupName + " = " + requestID); return "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<request>\n" + "<skupina_clenove reqid=\"" + requestID + "\">\n" + "<skupina_id></skupina_id>\n" + "<pracoviste_id>" + workplace + "</pracoviste_id>\n" + "<zkratka>" + groupName + "</zkratka>\n" + "<operace>INF</operace>\n" + "</skupina_clenove>\n" + "</request>"; }
Source:
<code>private String appendPrefix(String prefix, String key) { if (prefix.isEmpty()) { return key; } else { <START> return prefix.concat(".".concat(key)); <END> } }</code><technical_language>+ operators easier read (and perform a bit better). Also, inline this prefix.isEmpty() ? key : prefix + "." + key caller save a method dispatch</technical_language>

Target:
private String appendPrefix(String prefix, String key) { return prefix.isEmpty() ? key : prefix + "." + key; }
Source:
<code>private Response tryAuth(Request authRequest) throws IOException { return okClient .newBuilder() .authenticator(new Authenticator() { @Override public Request authenticate(Route route, Response response) throws IOException { if(StringUtils.isNotBlank(response.request().header(AUTH_ATTEMPTS))) { return null; } if(StringUtils.isNotBlank(response.header(IHttpConstants.PROPERTY_WWW_AUTHENTICATE))) { <START> for (IChallangeHandler challangeHandler : challangeHandlers) { <END> if(!challangeHandler.canHandle(response.headers())) { Builder requestBuilder = response.request().newBuilder() .header(AUTH_ATTEMPTS, "1"); return challangeHandler.handleChallange(requestBuilder).build(); } } } return null; } }) .build() .newCall(authRequest).execute(); }</code><technical_language>want extract iterating handlers checking if handle required auth method some metod called #getChallengeHandler(requestHeaders)</technical_language>

Target:
private Response tryAuth(Request authRequest) throws IOException { return okClient .newBuilder() .authenticator(new Authenticator() { @Override public Request authenticate(Route route, Response response) throws IOException { if(StringUtils.isNotBlank(response.request().header(AUTH_ATTEMPTS))) { return null; } if(StringUtils.isNotBlank(response.header(IHttpConstants.PROPERTY_WWW_AUTHENTICATE))) { for (IChallangeHandler challangeHandler : challangeHandlers) { if(!challangeHandler.canHandle(response.headers())) { Builder requestBuilder = response.request().newBuilder() .header(AUTH_ATTEMPTS, "1"); return challangeHandler.handleChallange(requestBuilder).build(); } } } return null; } }) .followRedirects(false) .followRedirects(false) .build() .newCall(authRequest).execute(); }
Source:
<code>private static void autoDetectConvertersInternally(DataContext dataContext, Table table, List<Column> columns, int sampleSize, Map<Column, TypeConverter<?, ?>> result) { if (columns == null || columns.size() == 0) { return; } Map<Column, ColumnTypeDetector> detectors = new HashMap<Column, ColumnTypeDetector>(); for (Column column : columns) { detectors.put(column, new ColumnTypeDetector()); } <START> Query query = dataContext.query().from(table).select(columns.toArray(new Column[columns.size()])).toQuery(); <END> if (sampleSize > 0 && sampleSize != Integer.MAX_VALUE) { query.setMaxRows(sampleSize); } DataSet dataSet = dataContext.executeQuery(query); try { while (dataSet.next()) { Row row = dataSet.getRow(); for (Column column : columns) { String stringValue = (String) row.getValue(column); ColumnTypeDetector detector = detectors.get(column); detector.registerValue(stringValue); } } } finally { dataSet.close(); } for (Column column : columns) { ColumnTypeDetector detector = detectors.get(column); TypeConverter<?, ?> converter = detector.createConverter(); if (converter != null) { result.put(column, converter); } } }</code><technical_language>extra toArray (just marking in case right avoid them)</technical_language>

Target:
private static void autoDetectConvertersInternally(DataContext dataContext, Table table, List<Column> columns, int sampleSize, Map<Column, TypeConverter<?, ?>> result) { if (columns == null || columns.size() == 0) { return; } Map<Column, ColumnTypeDetector> detectors = new HashMap<Column, ColumnTypeDetector>(); for (Column column : columns) { detectors.put(column, new ColumnTypeDetector()); } Query query = dataContext.query().from(table).select(columns).toQuery(); if (sampleSize > 0 && sampleSize != Integer.MAX_VALUE) { query.setMaxRows(sampleSize); } DataSet dataSet = dataContext.executeQuery(query); try { while (dataSet.next()) { Row row = dataSet.getRow(); for (Column column : columns) { String stringValue = (String) row.getValue(column); ColumnTypeDetector detector = detectors.get(column); detector.registerValue(stringValue); } } } finally { dataSet.close(); } for (Column column : columns) { ColumnTypeDetector detector = detectors.get(column); TypeConverter<?, ?> converter = detector.createConverter(); if (converter != null) { result.put(column, converter); } } }
Source:
<code>public void testMakeWriterForBamExtension() throws IOException { <START> final File tmpFile = File.createTempFile("testMakeWriterForBamExtension", ".bam"); <END> tmpFile.deleteOnExit(); final SAMFileWriter samFileWriter = new SAMFileWriterFactory().makeWriter(new SAMFileHeader(), true, tmpFile, null); samFileWriter.close(); Assert.assertTrue(SamStreams.isBAMFile(new BufferedInputStream (new SeekableFileStream(tmpFile)))); }</code><technical_language>Ditto: SamReader.Type.BAM_TYPE.fileExtension()</technical_language>

Target:
public void testMakeWriterForBamExtension() throws IOException { final File tmpFile = File.createTempFile("testMakeWriterForBamExtension", "." + BAM_TYPE.fileExtension()); tmpFile.deleteOnExit(); try (SAMFileWriter samFileWriter = new SAMFileWriterFactory().makeWriter(new SAMFileHeader(), true, tmpFile, null)) Assert.assertTrue(SamStreams.isBAMFile(new BufferedInputStream(new SeekableFileStream(tmpFile)))); }
Source:
<code>public Responder makeResponder(Request request) throws InstantiationException, IOException { String resource = request.getResource(); String responderKey = getResponderKey(request); <START> Responder responder=matchResponder(resource); <END> if (responder==null) { if (usingResponderKey(responderKey)) { responder = wrapWithFilters(responderKey, lookupResponder(responderKey)); } else if (resource.startsWith("files/") || resource.equals("files")) { responder = wrapWithFilters("files", new FileResponder()); } else if (StringUtils.isBlank(resource) || PathParser.parse(resource) != null) { responder = wrapWithFilters("wiki", new WikiPageResponder()); } else { responder = new NotFoundResponder(); } } return responder; }</code><technical_language>suggestion Responder responder = matchResponder(resource);</technical_language>

Target:
public Responder makeResponder(Request request) throws InstantiationException, IOException { String resource = request.getResource(); String responderKey = getResponderKey(request); final Responder responder; if (usingResponderKey(responderKey)) { responder = wrapWithFilters(responderKey, lookupResponder(responderKey)); } else if (resource.startsWith("files/") || resource.equals("files")) { responder = wrapWithFilters("files", new FileResponder()); } else if (StringUtils.isBlank(resource) || PathParser.parse(resource) != null) { responder = wrapWithFilters("wiki", new WikiPageResponder()); } else { String urlResponderKey=findMatchKeyByUrl(resource); if (urlResponderKey != null) { responder = wrapWithFilters("url", lookupResponder(urlResponderKey)); } else { responder = new NotFoundResponder(); } } return responder; }
Source:
<code>public void afterPropertiesSet() { <START> taskScheduler = registrationTaskScheduler(); <END> }</code><technical_language>instantiate TaskScheduler in constructor afterPropertiesSet() of TaskScheduler invoked</technical_language>

Target:
public void afterPropertiesSet() { taskScheduler.afterPropertiesSet(); }
Source:
<code>protected int extractMax(String typeCode, String fieldName, Connection conn) { int id = 0; PreparedStatement stat = null; ResultSet res = null; try { if (null != typeCode) { <START> stat = conn.prepareStatement("SELECT MAX( ? ) FROM jpwebform_typeversions WHERE typecode = ?"); <END> stat.setString(1, fieldName); stat.setString(2, typeCode); } else { stat = conn.prepareStatement("SELECT MAX( ? ) FROM jpwebform_typeversions"); stat.setString(1, fieldName); } res = stat.executeQuery(); res.next(); id = res.getInt(1); } catch (Throwable t) { _logger.error("Error extracting max id", t); throw new RuntimeException("Error extracting max id", t); } finally { closeDaoResources(res, stat); } return id; }</code><technical_language>I do that. Prepared statement is for column values for colunn name</technical_language>

Target:
protected int extractMax(String typeCode, String fieldName, Connection conn) { int id = 0; PreparedStatement stat = null; ResultSet res = null; try { if (null != typeCode) { stat = conn.prepareStatement("SELECT MAX(fieldName) FROM jpwebform_typeversions WHERE typecode = ?"); stat.replace("fieldName", fieldName) stat.setString(1, typeCode); } else { stat = conn.prepareStatement("SELECT MAX(fieldName) FROM jpwebform_typeversions"); stat.replace("fieldName", fieldName) } res = stat.executeQuery(); res.next(); id = res.getInt(1); } catch (Throwable t) { _logger.error("Error extracting max id", t); throw new RuntimeException("Error extracting max id", t); } finally { closeDaoResources(res, stat); } return id; }
Source:
<code>protected void execute(final RebaseOperation rebase) throws ExecutionException { final Repository repository = rebase.getRepository(); if (repository == null) return; final RebaseCommand.Operation operation = rebase.getOperation(); if (operation == Operation.BEGIN) { try { <START> final org.eclipse.jgit.api.Status status = Git.wrap(repository) <END> .status().call(); if (!status.isClean()) { handleUncommittedChanges(rebase, repository, status); return; } } catch (NoWorkTreeException e) { Activator.logError(e.getMessage(), e); } catch (GitAPIException e) { Activator.logError(e.getMessage(), e); } } startRebaseJob(rebase, repository, operation); }</code><technical_language>I instead IndexDiff is updated incrementally feed staging view, I is need recompute this information</technical_language>

Target:
protected void execute(final RebaseOperation rebase) throws ExecutionException { final Repository repository = rebase.getRepository(); if (repository == null) return; final RebaseCommand.Operation operation = rebase.getOperation(); if (operation == Operation.BEGIN) { IndexDiffData indexDiffData = org.eclipse.egit.core.Activator .getDefault().getIndexDiffCache() .getIndexDiffCacheEntry(repository).getIndexDiff(); List<String> files = new ArrayList<String>(); files.addAll(indexDiffData.getAdded()); files.addAll(indexDiffData.getChanged()); files.addAll(indexDiffData.getModified()); files.addAll(indexDiffData.getRemoved()); files.addAll(indexDiffData.getConflicting()); if (!files.isEmpty()) { handleUncommittedChanges(rebase, repository, files); return; } } startRebaseJob(rebase, repository, operation); }
Source:
<code>public void notifyChanged(Notification notification) { super.notifyChanged(notification); Object object = notification.getNotifier(); NamedElement property = getUMLElement(); if (object == null || property == null) { return; } <START> if (UMLPackage.eINSTANCE.getLiteralInteger_Value().equals(notification.getFeature())) { <END> refreshDisplay(); } else if (UMLPackage.eINSTANCE.getLiteralUnlimitedNatural_Value().equals(notification.getFeature())) { refreshDisplay(); } if (object.equals(property)) { notifyNamedElementChanged(property, notification); } if (isMaskManagedAnnotation(object)) { refreshDisplay(); } if (isRemovedMaskManagedLabelAnnotation(object, notification)) { refreshDisplay(); } }</code><technical_language>Yep, consequence of new stereotype notifications design. :-) be, e.g., if (notification.getFeature() == UMLPackage.Literals.LITERAL_INTEGER__VALUE)</technical_language>

Target:
public void notifyChanged(Notification notification) { super.notifyChanged(notification); Object object = notification.getNotifier(); NamedElement property = getUMLElement(); Object feature = notification.getFeature(); if (object == null || property == null || feature == null) { return; } if (feature == UMLPackage.eINSTANCE.getLiteralInteger_Value()) { refreshDisplay(); } else if (feature == UMLPackage.eINSTANCE.getLiteralUnlimitedNatural_Value()) { refreshDisplay(); } if (object.equals(property)) { notifyNamedElementChanged(property, notification); } if (isMaskManagedAnnotation(object)) { refreshDisplay(); } if (isRemovedMaskManagedLabelAnnotation(object, notification)) { refreshDisplay(); } }
Source:
<code>private Intent getClickIntentForAccount(Context context) { <START> Account account = (Account) getAccount(context); <END> if (K9.FOLDER_NONE.equals(account.getAutoExpandFolderName())) { return FolderList.actionHandleAccountIntent(context, account, false); } LocalSearch search = new LocalSearch(account.getAutoExpandFolderName()); search.addAllowedFolder(account.getAutoExpandFolderName()); search.addAccountUuid(account.getUuid()); return MessageList.intentDisplaySearch(context, search, false, true, true); }</code><technical_language>this point a regular account. Preferences.getAccount() avoid unnecessary work in this class's getAccount() unsafe type cast. in method below</technical_language>

Target:
private Intent getClickIntentForAccount(Context context) { Account account = Preferences.getPreferences(context).getAccount(accountUuid); if (K9.FOLDER_NONE.equals(account.getAutoExpandFolderName())) { return FolderList.actionHandleAccountIntent(context, account, false); } LocalSearch search = new LocalSearch(account.getAutoExpandFolderName()); search.addAllowedFolder(account.getAutoExpandFolderName()); search.addAccountUuid(account.getUuid()); return MessageList.intentDisplaySearch(context, search, false, true, true); }
Source:
<code>public void logMetricsSize() { <START> log.debug("corfu server metrics size " + MetricsUtils.sizeOf.deepSizeOf(ServerContext.getMetrics ())); <END> }</code><technical_language>* getMetrics()</technical_language>

Target:
public void logMetricsSize() { log.debug("corfu server metrics size {}.", MetricsUtils.sizeOf.deepSizeOf(ServerContext.getMetrics())); }
Source:
<code>public FileOpenCloseEventListener(final Provider<EditorAgent> editorAgentProvider, final DeletedFilesController deletedFilesController, final EventBus eventBus) { Log.debug(getClass(), "Adding file event listener"); eventBus.addHandler(FileEvent.TYPE, new FileEvent.FileEventHandler() { @Override public void onFileOperation(FileEvent event) { final Path path = event.getFile().getLocation(); final EditorAgent editorAgent = editorAgentProvider.get(); switch (event.getOperationType()) { case OPEN: { if (editorAgent.getOpenedEditor(path) == null) { <START> Log.info(getClass(), "Subscribe file for event handling"); END> processFileOpen(path); } break; } case CLOSE: { final EditorPartPresenter closingEditor = event.getEditorTab().getRelativeEditorPart(); final List<EditorPartPresenter> openedEditors = editorAgent.getOpenedEditors(); processFileClose(closingEditor, openedEditors, path); break; } } } private void processFileOpen(Path path) { eventBus.fireEvent(newFileTrackingStartEvent(path.toString())); } private void processFileClose(EditorPartPresenter closingEditor, List<EditorPartPresenter> openedEditors, Path path) { for (final EditorPartPresenter editor : openedEditors) { final Path editorFilePath = editor.getEditorInput().getFile().getLocation(); if (Objects.equals(path, editorFilePath) && closingEditor != editor) { return; } } eventBus.fireEvent(newFileTrackingStopEvent(path.toString())); } }); }</code><technical_language>Log.debug ??</technical_language>

Target:
public FileOpenCloseEventListener(final Provider<EditorAgent> editorAgentProvider, final DeletedFilesController deletedFilesController, final EventBus eventBus) { Log.debug(getClass(), "Adding file event listener"); eventBus.addHandler(FileEvent.TYPE, new FileEvent.FileEventHandler() { @Override public void onFileOperation(FileEvent event) { final Path path = event.getFile().getLocation(); final EditorAgent editorAgent = editorAgentProvider.get(); switch (event.getOperationType()) { case OPEN: { if (editorAgent.getOpenedEditor(path) == null) { Log.debug(getClass(), "Subscribe file for event handling"); processFileOpen(path); } break; } case CLOSE: { final EditorPartPresenter closingEditor = event.getEditorTab().getRelativeEditorPart(); final List<EditorPartPresenter> openedEditors = editorAgent.getOpenedEditors(); processFileClose(closingEditor, openedEditors, path); break; } } } private void processFileOpen(Path path) { eventBus.fireEvent(newFileTrackingStartEvent(path.toString())); } private void processFileClose(EditorPartPresenter closingEditor, List<EditorPartPresenter> openedEditors, Path path) { for (final EditorPartPresenter editor : openedEditors) { final Path editorFilePath = editor.getEditorInput().getFile().getLocation(); if (Objects.equals(path, editorFilePath) && closingEditor != editor) { return; } } eventBus.fireEvent(newFileTrackingStopEvent(path.toString())); } }); }
Source:
<code>public static double betaCdf( @SqlType(StandardTypes.DOUBLE) double a, @SqlType(StandardTypes.DOUBLE) double b, @SqlType(StandardTypes.DOUBLE) double value) { checkCondition(value >= 0 && value <= 1, INVALID_FUNCTION_ARGUMENT, "value must be 0 >= v >= 1"); checkCondition(a > 0 && b > 0, INVALID_FUNCTION_ARGUMENT, "a, b must be > 0"); <START> BetaDistribution dist = new BetaDistribution(a, b); <END> return dist.cumulativeProbability(value); }</code><technical_language>abbreviate variable names</technical_language>

Target:
public static double betaCdf( @SqlType(StandardTypes.DOUBLE) double a, @SqlType(StandardTypes.DOUBLE) double b, @SqlType(StandardTypes.DOUBLE) double value) { checkCondition(value >= 0 && value <= 1, INVALID_FUNCTION_ARGUMENT, "value must be in the interval [0, 1]"); checkCondition(a > 0, INVALID_FUNCTION_ARGUMENT, "a must be > 0"); checkCondition(b > 0, INVALID_FUNCTION_ARGUMENT, "b must be > 0"); BetaDistribution distribution = new BetaDistribution(null, a, b, BetaDistribution.DEFAULT_INVERSE_ABSOLUTE_ACCURACY); return distribution.cumulativeProbability(value); }
Source:
<code>R apply(T t) throws Exception; default Function<T, R> orElseThrow() { return t -> { try { return apply(t); } catch (RuntimeException e) { throw e; } catch (Exception e) { <START> throw new RuntimeException(e); <END> } }; }</code><technical_language>duck throwsUnchecked methods need moved this interface (where public methods) some class in this package package private. code this duck method</technical_language>

Target:
R apply(T t) throws Exception; default Function<T, R> orElseThrow() { return t -> { try { return apply(t); } catch (Throwable e) { throw Exceptions.duck(e); } }; }
Source:
<code>public void onResume() { super.onResume(); onPositionObserverUpdate(); <START> new Thread(() -> controller.init()).start(); <END> }</code><technical_language>Do do heavy lifting needs happen in background? If so, do do controller.init() in connectToPlaybackService() is executed UI thread</technical_language>

Target:
public void onResume() { super.onResume(); onPositionObserverUpdate(); controller.init(); }
Source:
<code>public void setDefaultConfiguration() { <START> Realm.removeDefaultConfiguration(); <END> Realm.setDefaultConfiguration(defaultConfig); realm = Realm.getDefaultInstance(); assertEquals(realm.getPath(), defaultConfig.getPath()); }</code><technical_language>need call this call setDefaultConfiguation right after</technical_language>

Target:
public void setDefaultConfiguration() { Realm.setDefaultConfiguration(defaultConfig); realm = Realm.getDefaultInstance(); assertEquals(defaultConfig, realm.getConfiguration()); }
Source:
<code>public Map<String, List<String>> getTopologyMap() { <START> return getTopologyUnderDomain(new HashMap<>()); <END> }</code><technical_language>nit, Collections.EMPTY_MAP</technical_language>

Target:
public Map<String, List<String>> getTopologyMap() { return getTopologyUnderDomain(Collections.emptyMap()); }
Source:
<code>public String stripProtocolAndBranch(String uri) { <START> return uri.replaceFirst("^[A-Za-z]+://([^@]+@)?", ""); <END> }</code><technical_language>nice new methods unit tested. String#replaceFirst is calling Pattern.compile internally. Based expected call this method, sense pre-compile pattern in private static final field of this class</technical_language>

Target:
public String stripProtocolAndBranch(String uri) { return protocolAndBranch.matcher(uri).replaceFirst(""); }
Source:
<code>private String resolveProjectName(String artifactId, String owa) { if (artifactId != null) { return artifactId; } <START> else if (projectType == ProjectType.OWA) { <END> if (owa != null) { return adjustProjectNameIfPrefixMissing(owa, OpenmrsBintray.OPENMRS_OWA_PREFIX); } else { return askForBintrayProjectName(); } } else { return wizard.promptForValueIfMissing(artifactId, "artifactId"); } }</code><technical_language>100% this I cleaner ProjectType.OWA.equals(projecttype)</technical_language>

Target:
private String resolveProjectName(String artifactId, String owa) { if (StringUtils.isNotBlank(artifactId)) { return artifactId; } else if (ProjectType.OWA.equals(projectType)) { if (StringUtils.isNotBlank(owa)) { return adjustProjectNameIfPrefixMissing(owa, OpenmrsBintray.OPENMRS_OWA_PREFIX); } else { return askForBintrayProjectName(); } } else { return wizard.promptForValueIfMissing(artifactId, "artifactId"); } }
Source:
<code>public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException exception ) { String[] tokens = recognizer.getTokenNames(); final List<String> tokensAsList = Arrays.asList(tokens); <START> <END> final Iterator<Integer> tokenids = exception.getExpectedTokens().toList().iterator(); final StringBuilder expectedTokens = new StringBuilder(); while (tokenids.hasNext()) { expectedTokens.append(tokensAsList.get(tokenids.next())); if (!tokenids.hasNext()) { expectedTokens.append("."); break; } expectedTokens.append(", "); } final String errorTokens = expectedTokens.toString().replaceAll("'", ""); throw new QueryException("Wrong input at " + "'" + exception.getOffendingToken().getText() + "' at " + "Line " + line + " Char " + charPositionInLine + ", expected one of the following tokens " + errorTokens); }</code><technical_language>final List<String> tokensAsList = Arrays.asList(recognizer.getTokenNames()); Immutable</technical_language>

Target:
public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException exception ) { final ImmutableList<String> tokensAsList = ImmutableList.copyOf(recognizer.getTokenNames()); final Iterator<Integer> tokenids = exception.getExpectedTokens().toList().iterator(); final StringBuilder expectedTokens = new StringBuilder(); while (tokenids.hasNext()) { expectedTokens.append(tokensAsList.get(tokenids.next())); if (!tokenids.hasNext()) { expectedTokens.append("."); break; } expectedTokens.append(", "); } final String errorTokens = expectedTokens.toString().replaceAll("'", ""); throw new QueryException("Wrong input at " + "'" + exception.getOffendingToken().getText() + "' at " + "Line " + line + " Char " + charPositionInLine + ", expected one of the following tokens " + errorTokens); }
Source:
<code>private void updateThreadFolderSetting() { if (ChanSettings.saveBoardFolder.get()) { threadFolderSetting.setEnabled(true); <START> } else if (!ChanSettings.saveBoardFolder.get()) { <END> if (ChanSettings.saveThreadFolder.get()) { threadFolderSetting.onClick(threadFolderSetting.view); } threadFolderSetting.setEnabled(false); ChanSettings.saveThreadFolder.set(false); } }</code><technical_language>I convert this else</technical_language>

Target:
private void updateThreadFolderSetting() { if (ChanSettings.saveBoardFolder.get()) { threadFolderSetting.setEnabled(true); } else { if (ChanSettings.saveThreadFolder.get()) { threadFolderSetting.onClick(threadFolderSetting.view); } threadFolderSetting.setEnabled(false); ChanSettings.saveThreadFolder.set(false); } }
Source:
<code>private static void enable(SingletonService service) { try { service.enable(); } catch (RuntimeException e) { <START> e.printStackTrace(); <END> } }</code><technical_language>Friendly reminder log</technical_language>

Target:
private static void enable(SingletonService service) { try { service.enable(); } catch (RuntimeException e) { log.error("Failed to enable singleton service ", e); } }
Source:
<code>private String writePageHeader() { StringBuilder output = new StringBuilder(); String pageHeader = configPanel.getHeader(); if (pageHeader.isEmpty() == false) { <START> output.append("<p style=\"text-align: center\">") <END> .append(StringEscapeUtils.escapeHtml4(pageHeader)) .append("</p>\n"); } return output.toString(); }</code><technical_language>I kinda size of this text a bigger sounded Dmitry thought size section heading, if do I define size style stuff in CSS write lines 1130 for summary lines 915 for sections. "#headerFooter {width:100%; padding: 10px; line-height: 25px; text-align: center; font-size: 20px;}\n" in write page header write page footer code prepending "<div id=\"headerFooter\">" text appending "</div>\n" text</technical_language>

Target:
private String writePageHeader() { StringBuilder output = new StringBuilder(); String pageHeader = configPanel.getHeader(); if (pageHeader.isEmpty() == false) { output.append("<div id=\"pageHeaderFooter\">") .append(StringEscapeUtils.escapeHtml4(pageHeader)) .append("</div>\n"); } return output.toString(); }
Source:
<code>static public SAMFileHeader makeDefaultHeader(final SAMFileHeader.SortOrder sortOrder, final int contigLength, final boolean addReadGroup) { final List<SAMSequenceRecord> sequences = new ArrayList<>(); for (final String chrom : chroms) { final SAMSequenceRecord sequenceRecord = new SAMSequenceRecord(chrom, contigLength); sequences.add(sequenceRecord); } final SAMFileHeader header = new SAMFileHeader(); header.setSequenceDictionary(new SAMSequenceDictionary(sequences)); header.setSortOrder(sortOrder); if (addReadGroup) { final SAMReadGroupRecord readGroupRecord = new SAMReadGroupRecord(READ_GROUP_ID); readGroupRecord.setSample(SAMPLE); readGroupRecord.setPlatform("ILLUMINA"); final List<SAMReadGroupRecord> readGroups = new ArrayList<>(); <START> readGroups.add(readGroupRecord); <END> header.setReadGroups(readGroups); } return header; }</code><technical_language>~should new ArrayList<>(readGroupRecord)~ SingletonList(readGroupRecord)</technical_language>

Target:
static public SAMFileHeader makeDefaultHeader(final SAMFileHeader.SortOrder sortOrder, final int contigLength, final boolean addReadGroup) { final List<SAMSequenceRecord> sequences = new ArrayList<>(); for (final String chrom : chroms) { final SAMSequenceRecord sequenceRecord = new SAMSequenceRecord(chrom, contigLength); sequences.add(sequenceRecord); } final SAMFileHeader header = new SAMFileHeader(); header.setSequenceDictionary(new SAMSequenceDictionary(sequences)); header.setSortOrder(sortOrder); if (addReadGroup) { final SAMReadGroupRecord readGroupRecord = new SAMReadGroupRecord(READ_GROUP_ID); readGroupRecord.setSample(SAMPLE); readGroupRecord.setPlatform(PlatformValue.ILLUMINA.name()); final List<SAMReadGroupRecord> readGroups = Collections.singletonList(readGroupRecord); header.setReadGroups(readGroups); } return header; }
Source:
<code>public LoopbackExportDecoder(AdvertisedDataSource source) { super(source); if (m_rejectedDH != null) { m_rejs = Suppliers.memoize(new Supplier<CSVWriter>() { @Override public CSVWriter get() { String fileFN = String.format( <START> "rejected-%d-%s.tsv", source.partitionId <END> ); File rejectedFH = new File(m_rejectedDH, fileFN); LOG.warn("writing failed invocations parameters to " + rejectedFH); try { OutputStreamWriter osw = new OutputStreamWriter( new FileOutputStream(rejectedFH, false), "UTF-8"); CSVWriter wrtr = CSVWriter.getStrictTSVWriter(new BufferedWriter(osw, 4096 * 4)); m_wrote = true; return wrtr; } catch (UnsupportedEncodingException | FileNotFoundException e) { LOG.error("failed to create TSV writer for " + rejectedFH, e); throw new LoopbackExportException("failed to create TSV writer for %s", e, rejectedFH); } } }); } else { m_rejs = null; } final String tmpl = "yyyy-MM-dd'T'HH:mm:ss.SSS"; CSVWriterDecoder.Builder builder = new CSVWriterDecoder.Builder(); builder .dateFormatter(tmpl) .skipInternalFields(true) ; m_csvWriterDecoder = builder.build(); m_es = CoreUtils.getListeningSingleThreadExecutor( "Loopback Export decoder for partition " + source.partitionId, CoreUtils.MEDIUM_STACK_SIZE); m_user = getVoltDB().getCatalogContext().authSystem.getImporterUser(); m_invoker = getVoltDB().getClientInterface().getInternalConnectionHandler(); m_shouldContinue = (x) -> !m_es.isShutdown(); }</code><technical_language>Missing a parameter</technical_language>

Target:
public LoopbackExportDecoder(AdvertisedDataSource source) { super(source); if (m_rejectedDH != null) { m_rejs = Suppliers.memoize(new Supplier<CSVWriter>() { @Override public CSVWriter get() { String fileFN = String.format( "rejected-%s-%d.tsv", source.tableName, source.partitionId ); File rejectedFH = new File(m_rejectedDH, fileFN); LOG.warn("writing failed invocations parameters to " + rejectedFH); try { OutputStreamWriter osw = new OutputStreamWriter( new FileOutputStream(rejectedFH, false), "UTF-8"); CSVWriter wrtr = CSVWriter.getStrictTSVWriter(new BufferedWriter(osw, 4096 * 4)); m_wrote = true; return wrtr; } catch (UnsupportedEncodingException | FileNotFoundException e) { LOG.error("failed to create TSV writer for " + rejectedFH, e); throw new LoopbackExportException("failed to create TSV writer for %s", e, rejectedFH); } } }); } else { m_rejs = null; } final String tmpl = "yyyy-MM-dd'T'HH:mm:ss.SSS"; CSVWriterDecoder.Builder builder = new CSVWriterDecoder.Builder(); builder .dateFormatter(tmpl) .skipInternalFields(true) ; m_csvWriterDecoder = builder.build(); m_es = CoreUtils.getListeningSingleThreadExecutor( "Loopback Export decoder for partition " + source.partitionId, CoreUtils.MEDIUM_STACK_SIZE); m_user = getVoltDB().getCatalogContext().authSystem.getImporterUser(); m_invoker = getVoltDB().getClientInterface().getInternalConnectionHandler(); m_shouldContinue = (x) -> !m_es.isShutdown(); }
Source:
<code>public boolean shouldValidateBean(final Validator validator, final Class<?> clazz) { <START> return types.computeIfAbsent(clazz, it -> validator.getConstraintsForClass(it).hasConstraints()); <END> }</code><technical_language>check for isBeanConstrained cache that</technical_language>

Target:
public boolean shouldValidateBean(final Validator validator, final Class<?> clazz) { return types.computeIfAbsent(clazz, it -> validator.getConstraintsForClass(it).isBeanConstrained()); }
Source:
<code>public DelegatingResourceDescription getRepresentationDescription(Representation rep) { if (rep instanceof DefaultRepresentation) { DelegatingResourceDescription description = new DelegatingResourceDescription(); description.addProperty("uuid"); description.addProperty("name"); description.addProperty("frequencyPerDay"); description.addProperty("retired"); description.addSelfLink(); description.addLink("full", ".?v=" + RestConstants.REPRESENTATION_FULL); return description; } else if (rep instanceof FullRepresentation) { DelegatingResourceDescription description = new DelegatingResourceDescription(); description.addProperty("uuid"); description.addProperty("name"); description.addProperty("frequencyPerDay"); description.addProperty("retired"); description.addProperty("concept", Representation.DEFAULT); description.addSelfLink(); <START> return description; <END> } return null; }</code><technical_language>need include audit info for full rep</technical_language>

Target:
public DelegatingResourceDescription getRepresentationDescription(Representation rep) { if (rep instanceof DefaultRepresentation) { DelegatingResourceDescription description = new DelegatingResourceDescription(); description.addProperty("uuid"); description.addProperty("name"); description.addProperty("frequencyPerDay"); description.addProperty("retired"); description.addProperty("concept", Representation.REF); description.addSelfLink(); description.addLink("full", ".?v=" + RestConstants.REPRESENTATION_FULL); return description; } else if (rep instanceof FullRepresentation) { DelegatingResourceDescription description = new DelegatingResourceDescription(); description.addProperty("uuid"); description.addProperty("name"); description.addProperty("frequencyPerDay"); description.addProperty("concept", Representation.DEFAULT); description.addProperty("retired"); description.addSelfLink(); description.addProperty("auditInfo", findMethod("getAuditInfo")); return description; } return null; }
Source:
<code>public DataOutputStream getChunkDataOutputStream(int x, int z) { checkBounds(x, z); <START> return new DataOutputStream(new BufferedOutputStream(new DeflaterOutputStream(new ChunkBuffer(x, z)))); <END> }</code><technical_language><LINK_0></technical_language>

Target:
public DataOutputStream getChunkDataOutputStream(int x, int z) { checkBounds(x, z); return new DataOutputStream(new BufferedOutputStream(new DeflaterOutputStream(new ChunkBuffer(x, z), new Deflater(), 2048))); }
Source:
<code>public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RowProcessingStream other = (RowProcessingStream) obj; if (_analysisJob == null) { if (other._analysisJob != null) return false; } else if (!_analysisJob.equals(other._analysisJob)) return false; if (_table == null) { if (other._table != null) return false; } else if (!_table.equals(other._table)) return false; return true; <START> } <END></code><technical_language>like: if (this == object) { return true; } else if (obj == null || !(obj instanceof RowProcessingStream)) { return false; } else { return Objects.equals(_analysisJob, other._analysisJob && Objects.equals(_table, other._table) } a bit more readable me</technical_language>

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || !(obj instanceof RowProcessingStream)) { return false; } final RowProcessingStream other = (RowProcessingStream) obj; return Objects.equals(_analysisJob, other._analysisJob) && Objects.equals(_table, other._table); }
Source:
<code>public FinalizingFieldAccessPostAggregator decorate(final Map<String, AggregatorFactory> aggregators) { <START> return new FinalizingFieldAccessPostAggregator(name, fieldName) { <END> @Override public Object compute(Map<String, Object> combinedAggregators) { if (aggregators != null && aggregators.containsKey(fieldName)) { return aggregators.get(fieldName).finalizeComputation( combinedAggregators.get(fieldName) ); } else { return combinedAggregators.get(fieldName); } } }; }</code><technical_language>This override getComparator too, post-aggregator sorted on. This comparator of aggregators.get(fieldName).getComparator() if exists, Ordering.natural().nullsFirst() (hoping for best)</technical_language>

Target:
public FinalizingFieldAccessPostAggregator decorate(final Map<String, AggregatorFactory> aggregators) { return new FinalizingFieldAccessPostAggregator(name, fieldName) { @Override public Comparator getComparator() { if (aggregators != null && aggregators.containsKey(fieldName)) { return aggregators.get(fieldName).getComparator(); } else { return Ordering.natural().nullsFirst(); } } @Override public Object compute(Map<String, Object> combinedAggregators) { if (aggregators != null && aggregators.containsKey(fieldName)) { return aggregators.get(fieldName).finalizeComputation( combinedAggregators.get(fieldName) ); } else { return combinedAggregators.get(fieldName); } } }; }
Source:
<code>public void VisualEditorMultiplePublish_001() { WikiBasePageObject base = new WikiBasePageObject(driver); base.logInCookie(credentials.userName, credentials.password, wikiURL); VisualEditorPageObject ve = base.openNewArticleEditModeVisual(wikiURL); String targetText = PageContent.articleText; String articleName = PageContent.articleNamePrefix + ve.getTimeStamp(); <START> ve.gotoArticleEditModeVisual(wikiURL,articleName); <END> ve.typeTextArea(PageContent.articleText); VisualEditorSaveChangesDialog save = ve.clickPublishButton(); ArticlePageObject article = save.savePage(); article.verifyFormattingFromVE(Formatting.PARAGRAPH, targetText); targetText = PageContent.articleTextEdit + targetText; ve.gotoArticleEditModeVisual(wikiURL,articleName); ve.typeTextArea(PageContent.articleTextEdit); save = ve.clickPublishButton(); article = save.savePage(); article.verifyFormattingFromVE(Formatting.PARAGRAPH, targetText); targetText = PageContent.articleTextSecondEdit + targetText; ve.gotoArticleEditModeVisual(wikiURL,articleName); ve.typeTextArea(PageContent.articleTextSecondEdit); save = ve.clickPublishButton(); article = save.savePage(); article.verifyFormattingFromVE(Formatting.PARAGRAPH, targetText); }</code><technical_language>please rename method gotoArticleEditModeVisual() navigateTo...()</technical_language>

Target:
public void VisualEditorMultiplePublish_001() { String targetText = PageContent.articleText; String articleName = base.getNameForArticle(); article = base.openArticleByName(wikiURL, articleName); ve = article.navigateToArticleEditModeVisual(wikiURL, articleName); article = ve.clickVEEditAndPublish(wikiURL, articleName, targetText); article.verifyFormattingFromVE(Formatting.PARAGRAPH, targetText); targetText = PageContent.articleTextEdit + targetText; ve = article.navigateToArticleEditModeVisual(wikiURL, articleName); article = ve.clickVEEditAndPublish(wikiURL, articleName, PageContent.articleTextEdit); article.verifyFormattingFromVE(Formatting.PARAGRAPH, targetText); targetText = PageContent.articleTextSecondEdit + targetText; ve = article.navigateToArticleEditModeVisual(wikiURL, articleName); article = ve.clickVEEditAndPublish(wikiURL, articleName, PageContent.articleTextSecondEdit); article.verifyFormattingFromVE(Formatting.PARAGRAPH, targetText); }
Source:
<code>public RevCommit cherryPick(AnyObjectId id) throws Exception { RevCommit commit = pool.parseCommit(id); pool.parseBody(commit); if (commit.getParentCount() != 1) throw new IOException(String.format( "Expected 1 parent for %s, found: %s", id.name(), Arrays.asList(commit.getParents()))); RevCommit parent = commit.getParent(0); pool.parseHeaders(parent); Ref headRef = db.getRef(Constants.HEAD); if (headRef == null) throw new IOException("Missing HEAD"); RevCommit head = pool.parseCommit(headRef.getObjectId()); ThreeWayMerger merger = MergeStrategy.RECURSIVE.newMerger(db, true); merger.setBase(parent.getTree()); if (merger.merge(head, commit)) { if (AnyObjectId.equals(head.getTree(), merger.getResultTreeId())) return null; <START> tick(1); <END> org.eclipse.jgit.lib.CommitBuilder b = new org.eclipse.jgit.lib.CommitBuilder(); b.setParentId(head); b.setTreeId(merger.getResultTreeId()); b.setAuthor(commit.getAuthorIdent()); b.setCommitter(new PersonIdent(commit.getCommitterIdent(), new Date(now))); b.setMessage(commit.getFullMessage()); ObjectId result; try (ObjectInserter ins = inserter) { result = ins.insert(b); ins.flush(); } update(Constants.HEAD, result); return pool.parseCommit(result); } else { throw new IOException("Merge conflict"); } }</code><technical_language>do tick here? consistent commit() is requirement I yet</technical_language>

Target:
public RevCommit cherryPick(AnyObjectId id) throws Exception { RevCommit commit = pool.parseCommit(id); pool.parseBody(commit); if (commit.getParentCount() != 1) throw new IOException(String.format( "Expected 1 parent for %s, found: %s", id.name(), Arrays.asList(commit.getParents()))); RevCommit parent = commit.getParent(0); pool.parseHeaders(parent); Ref headRef = db.getRef(Constants.HEAD); if (headRef == null) throw new IOException("Missing HEAD"); RevCommit head = pool.parseCommit(headRef.getObjectId()); ThreeWayMerger merger = MergeStrategy.RECURSIVE.newMerger(db, true); merger.setBase(parent.getTree()); if (merger.merge(head, commit)) { if (AnyObjectId.equals(head.getTree(), merger.getResultTreeId())) return null; tick(1); org.eclipse.jgit.lib.CommitBuilder b = new org.eclipse.jgit.lib.CommitBuilder(); b.setParentId(head); b.setTreeId(merger.getResultTreeId()); b.setAuthor(commit.getAuthorIdent()); b.setCommitter(new PersonIdent(defaultCommitter, new Date(now))); b.setMessage(commit.getFullMessage()); ObjectId result; try (ObjectInserter ins = inserter) { result = ins.insert(b); ins.flush(); } update(Constants.HEAD, result); return pool.parseCommit(result); } else { throw new IOException("Merge conflict"); } }
Source:
<code>public void validateArguments(List<Expr> args) { <START> if (!(args.size() > 0)) { <END> throw new IAE("Function[%s] needs at least 1 argument", name()); } }</code><technical_language>simplify to: java if (args.isEmpty()) {</technical_language>

Target:
public void validateArguments(List<Expr> args) { if (args.isEmpty()) { throw new IAE("Function[%s] needs at least 1 argument", name()); } }
Source:
<code>public Set<String> getDefinitions(final String label) { final Set<String> ids = definitionsByLabel.get(label); if (null == ids) { return Collections.emptySet(); } <START> return ids; <END> }</code><technical_language>shortened line, this more question, if of performance: java return Optional.ofNullable(definitionsByLabel.get(label)).orElse(Collections.emptySet());</technical_language>

Target:
public Set<String> getDefinitions(final String label) { final Set<String> ids = definitionsByLabel.get(label); return null != ids ? ids : Collections.emptySet(); }
Source:
<code>public Observable<BufferingState> forInterest(final Interest<T> interest) { return Observable.create(new OnSubscribe<BufferingState>() { @Override public void call(Subscriber<? super BufferingState> subscriber) { updatesSubject.pause(); try { BufferingState current = shouldBatch(interest); if (current != BufferingState.FinishBuffering) { subscriber.onNext(current); } updatesSubject.map(new Func1<Boolean, BufferingState>() { @Override public BufferingState call(Boolean tick) { <START> return shouldBatch(interest); <END> } }).subscribe(subscriber); } finally { updatesSubject.resume(); } } }).distinctUntilChanged(); }</code><technical_language>care true/false emits of updatesSubject, emit is a "tick". bother emit a boolean in updatesSubject? simpler ignore boolean logic</technical_language>

Target:
public Observable<BufferState> forInterest(final Interest<T> interest) { return Observable.create(new OnSubscribe<BufferState>() { @Override public void call(Subscriber<? super BufferState> subscriber) { updatesSubject.pause(); try { BufferState current = shouldBatch(interest); if (current != BufferState.BufferEnd) { subscriber.onNext(current); } updatesSubject.map(new Func1<Boolean, BufferState>() { @Override public BufferState call(Boolean tick) { return shouldBatch(interest); } }).subscribe(subscriber); } finally { updatesSubject.resume(); } } }).distinctUntilChanged(); }