auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testMapperParametersFromEnv() throws Exception { String authKeyUrlParam = "myAuthKeyParams"; String filterName = "testAuthKeyParams2"; AuthenticationKeyFilterConfig config = new AuthenticationKeyFilterConfig(); <START> config.setAllowEnvParametrization(true); <END> config.setClassName(GeoServerAuthenticationKeyFilter.class.getName()); config.setName(filterName); config.setUserGroupServiceName("ug1"); config.setAuthKeyParamName(authKeyUrlParam); config.setAuthKeyMapperName("fakeMapper"); final GeoServerEnvironment gsEnvironment = GeoServerExtensions.bean(GeoServerEnvironment.class); System.setProperty("authkey_param1", "value1"); System.setProperty("authkey_param2", "value2"); try { Map<String, String> mapperParams = new HashMap<String, String>(); mapperParams.put("param1", "${authkey_param1}"); mapperParams.put("param2", "${authkey_param2}"); config.setMapperParameters(mapperParams); getSecurityManager().saveFilter(config); GeoServerAuthenticationKeyFilter filter = (GeoServerAuthenticationKeyFilter) getSecurityManager().loadFilter(filterName); assertTrue(filter.getMapper() instanceof FakeMapper); FakeMapper fakeMapper = (FakeMapper) filter.getMapper(); assertEquals("value1", fakeMapper.getMapperParameter("param1")); assertEquals("value2", fakeMapper.getMapperParameter("param2")); } finally { System.clearProperty("authkey_param1"); System.clearProperty("authkey_param2"); } }</code><technical_language>above, system variable set in a @Before reset in a @After</technical_language>

Target:
public void testMapperParametersFromEnv() throws Exception { String authKeyUrlParam = "myAuthKeyParams"; String filterName = "testAuthKeyParams2"; AuthenticationKeyFilterConfig config = new AuthenticationKeyFilterConfig(); config.setClassName(GeoServerAuthenticationKeyFilter.class.getName()); config.setName(filterName); config.setUserGroupServiceName("ug1"); config.setAuthKeyParamName(authKeyUrlParam); config.setAuthKeyMapperName("fakeMapper"); final GeoServerEnvironment gsEnvironment = GeoServerExtensions.bean(GeoServerEnvironment.class); System.setProperty("authkey_param1", "value1"); System.setProperty("authkey_param2", "value2"); try { Map<String, String> mapperParams = new HashMap<String, String>(); mapperParams.put("param1", "${authkey_param1}"); mapperParams.put("param2", "${authkey_param2}"); config.setMapperParameters(mapperParams); getSecurityManager().saveFilter(config); GeoServerAuthenticationKeyFilter filter = (GeoServerAuthenticationKeyFilter) getSecurityManager().loadFilter(filterName); assertTrue(filter.getMapper() instanceof FakeMapper); FakeMapper fakeMapper = (FakeMapper) filter.getMapper(); assertEquals("value1", fakeMapper.getMapperParameter("param1")); assertEquals("value2", fakeMapper.getMapperParameter("param2")); } finally { System.clearProperty("authkey_param1"); System.clearProperty("authkey_param2"); } }
Source:
<code>public static void addTypesToConnection(PGConnection connection) throws SQLException { <START> Iterator it = TYPES.entrySet().iterator(); <END> while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); connection.addDataType((String) pair.getValue(), (Class) pair.getKey()); } }</code><technical_language>modern iteration here: TYPES.forEach((clazz, name) -> connection.addDataType(name, clazz));</technical_language>

Target:
void addTypesToConnection(PGConnection connection) { types.forEach((clazz, type) -> Unchecked.<String, Class>biConsumer(connection::addDataType).accept(type, clazz)); }
Source:
<code>public AccessResult checkAccess(final String inPkg, final String forImport) { final AccessResult result; final AccessResult returnValue = localCheckAccess(inPkg, forImport); if (returnValue != AccessResult.UNKNOWN) { result = returnValue; } else if (parent == null) { <START> if (strategyOnMismatch != null && <END> strategyOnMismatch.equals(ImportControlOption.ALLOWED)) { result = AccessResult.ALLOWED; } else { result = AccessResult.DISALLOWED; } } else { if (strategyOnMismatch == null) { result = parent.checkAccess(inPkg, forImport); } else { switch (strategyOnMismatch) { case ALLOWED: result = AccessResult.ALLOWED; break; case DISALLOWED: result = AccessResult.DISALLOWED; break; default: result = parent.checkAccess(inPkg, forImport); break; } } } return result; }</code><technical_language>need null-check if change strategyOnMismatch.equals(ImportControlOption.ALLOWED) -> ImportControlOption.ALLOWED.equals(strategyOnMismatch). reason enum constant left side of equals comparison is avoid possibility of exception if enum constant compared is null</technical_language>

Target:
public AccessResult checkAccess(final String inPkg, final String forImport) { final AccessResult result; final AccessResult returnValue = localCheckAccess(inPkg, forImport); if (returnValue != AccessResult.UNKNOWN) { result = returnValue; } else if (parent == null) { if (strategyOnMismatch == MismatchStrategy.ALLOWED) { result = AccessResult.ALLOWED; } else { result = AccessResult.DISALLOWED; } } else { if (strategyOnMismatch == MismatchStrategy.ALLOWED) { result = AccessResult.ALLOWED; } else if (strategyOnMismatch == MismatchStrategy.DISALLOWED) { result = AccessResult.DISALLOWED; } else { result = parent.checkAccess(inPkg, forImport); } } return result; }
Source:
<code>public double calculateMagicPower() { <START> return calculateWoodMagicFactor() * calculateWoodMagicFactor() * this.getLengthInches(); <END> }</code><technical_language>consistent this for instance methods all. I prefer if required</technical_language>

Target:
public double calculateMagicPower() { return calculateWoodMagicFactor() * calculateWoodMagicFactor() * getLengthInches(); }
Source:
<code>public void load() { OptionBuilder<DatasetRepository> builder = new URIBuilder(); Registration.register( new URIPattern("file:/*path?absolute=true"), new URIPattern("file:/*path/:namespace/:dataset?absolute=true"), builder); Registration.register( new URIPattern("file:*path"), new URIPattern("file:*path/:namespace/:dataset"), builder); Registration.register( new URIPattern("hdfs:/*path?absolute=true"), new URIPattern("hdfs:/*path/:namespace/:dataset?absolute=true"), builder ); Registration.register( new URIPattern("hdfs:*path"), new URIPattern("hdfs:*path/:namespace/:dataset"), builder); Registration.register( new URIPattern("webhdfs:/*path?absolute=true"), new URIPattern("webhdfs:/*path/:namespace/:dataset?absolute=true"), builder ); <START> Registration.register( <END> new URIPattern("webhdfs:*path"), new URIPattern("webhdfs:*path/:namespace/:dataset"), builder); }</code><technical_language>wondering if support relative URIs for other file systems. for webhdfs? Starting user's home directory? leave this out require absolute paths</technical_language>

Target:
public void load() { OptionBuilder<DatasetRepository> builder = new URIBuilder(); Registration.register( new URIPattern("file:/*path?absolute=true"), new URIPattern("file:/*path/:namespace/:dataset?absolute=true"), builder); Registration.register( new URIPattern("file:*path"), new URIPattern("file:*path/:namespace/:dataset"), builder); Registration.register( new URIPattern("hdfs:/*path?absolute=true"), new URIPattern("hdfs:/*path/:namespace/:dataset?absolute=true"), builder ); Registration.register( new URIPattern("hdfs:*path"), new URIPattern("hdfs:*path/:namespace/:dataset"), builder); Registration.register( new URIPattern("webhdfs:/*path?absolute=true"), new URIPattern("webhdfs:/*path/:namespace/:dataset?absolute=true"), builder ); }
Source:
<code>public SqlStatementParameterCustomizer createForParameter(Annotation annotation, Class<?> sqlObjectType, Method method, Parameter param, int index, Type type) { final BindList bindList = (BindList) annotation; final String name = ParameterUtil.findParameterName(bindList.value(), param) .orElseThrow(() -> new UnsupportedOperationException("A @BindList parameter was not given a name, " + "and parameter name data is not present in the class file, for: " + param.getDeclaringExecutable() + "::" + param)); return (stmt, arg) -> { if (arg == null || IterableLike.isEmpty(arg)) { switch (bindList.onEmpty()) { case VOID: stmt.define(name, ""); return; case NULL: stmt.define(name, "null"); return; case JAVA_NULL: <START> stmt.define(name, null); <END> return; case THROW: String msg = arg == null ? "argument is null; null was explicitly forbidden on this instance of BindList" : "argument is empty; emptiness was explicitly forbidden on this instance of BindList"; throw new IllegalArgumentException(msg); default: throw new IllegalStateException(VALUE_NOT_HANDLED_MESSAGE); } } stmt.bindList(name, IterableLike.toList(arg)); }; }</code><technical_language>consider simply no-op'ing right here</technical_language>

Target:
public SqlStatementParameterCustomizer createForParameter(Annotation annotation, Class<?> sqlObjectType, Method method, Parameter param, int index, Type type) { final BindList bindList = (BindList) annotation; final String name = ParameterUtil.findParameterName(bindList.value(), param) .orElseThrow(() -> new UnsupportedOperationException("A @BindList parameter was not given a name, " + "and parameter name data is not present in the class file, for: " + param.getDeclaringExecutable() + "::" + param)); return (stmt, arg) -> { if (arg == null || IterableLike.isEmpty(arg)) { bindList.onEmpty().define(stmt, name); } else { stmt.bindList(name, IterableLike.toList(arg)); } }; }
Source:
<code>private static String parseOrcSchema(String configuredSchema) { try { co.cask.cdap.api.data.schema.Schema schemaObj = co.cask.cdap.api.data.schema.Schema.parseJson(configuredSchema); StringBuilder builder = new StringBuilder(); HiveSchemaConverter.appendType(builder, schemaObj); return builder.toString(); } catch (IOException e) { <START> LOG.debug("{} is not a valid schema", configuredSchema, e); <END> throw new IllegalArgumentException(String.format("%s is not a valid schema", configuredSchema), e); } catch (UnsupportedTypeException e) { throw new IllegalArgumentException(String.format("Could not create hive schema from %s", configuredSchema), e); } }</code><technical_language>Unnecessary log</technical_language>

Target:
private static String parseOrcSchema(String configuredSchema) { try { co.cask.cdap.api.data.schema.Schema schemaObj = co.cask.cdap.api.data.schema.Schema.parseJson(configuredSchema); StringBuilder builder = new StringBuilder(); HiveSchemaConverter.appendType(builder, schemaObj); return builder.toString(); } catch (IOException e) { throw new IllegalArgumentException(String.format("%s is not a valid schema", configuredSchema), e); } catch (UnsupportedTypeException e) { throw new IllegalArgumentException(String.format("Could not create hive schema from %s", configuredSchema), e); } }
Source:
<code>private void testShhAuthenticationSuccessfull(String username, String host) throws IOException, UserAuthException { String sanitizedUserName = SanitizerUtil.sanitizeWorkloadUsername(username); SSHClient client = getSshClient(host); <START> client.authPassword(sanitizedUserName, MOCK_UMS_PASSWORD); <END> client.close(); }</code><technical_language>Please sanitizedUserName testShhAuthenticationFailure method well</technical_language>

Target:
private void testShhAuthenticationSuccessfull(String username, String host) throws IOException, UserAuthException { SSHClient client = getSshClient(host); client.authPassword(username, MOCK_UMS_PASSWORD); client.close(); }
Source:
<code>private synchronized void scheduleRefresh(long delay, Runnable uiTask) { <START> refreshUiJob.cancel(); refreshUiJob.uiTask.compareAndSet(null, uiTask); refreshUiJob.schedule(delay); <END> }</code><technical_language>mean, job starts if events coming in 200 ms (less 300 ms schedule delay)? alternative remember time job finished run, schedule next a delay of max(0, now-last_finish_time + 300). events defer jobs endlessly, run more 300 ms. if egit another project, discussed re-using job instances creating new job instances. I remember issue resulted setting a member prepare next scheduling, while job running previous schedule. creating a new job instance time a no-issue. Wondering if do here, too</technical_language>

Target:
private synchronized void scheduleRefresh(long delay, Runnable uiTask) { System.out.println( "t=" + System.currentTimeMillis() + " scheduling " + delay); refreshUiJob.uiTask.compareAndSet(null, uiTask); refreshUiJob.schedule(delay); }
Source:
<code>public void handle(StateContext state, RootCollectionRelationshipContext ctx) { EntityDictionary dictionary = state.getRequestScope().getDictionary(); String entityName = ctx.entity().term().getText(); String id = ctx.entity().id().getText(); Class<?> entityClass = dictionary.getEntityClass(entityName); if (entityClass == null || !dictionary.isRoot(entityClass)) { <START> throw new ForbiddenEntityException(); <END> } PersistentResource record = PersistentResource.loadRecord(entityClass, id, state.getRequestScope()); String relationName = ctx.relationship().term().getText(); try { Optional<FilterExpression> filterExpression = state.getRequestScope().getExpressionForRelation(record, relationName); record.getRelationCheckedFiltered(relationName, filterExpression, Optional.empty(), Optional.empty()); } catch (InvalidAttributeException e) { throw new InvalidCollectionException(relationName); } state.setState(new RelationshipTerminalState(record, relationName)); }</code><technical_language>throwing ForbiddenAccessException in process of fetching a relationship</technical_language>

Target:
public void handle(StateContext state, RootCollectionRelationshipContext ctx) { EntityDictionary dictionary = state.getRequestScope().getDictionary(); String entityName = ctx.entity().term().getText(); String id = ctx.entity().id().getText(); Class<?> entityClass = dictionary.getEntityClass(entityName); if (entityClass == null || !dictionary.isRoot(entityClass)) { throw new ForbiddenAccessException(entityName); } PersistentResource record = PersistentResource.loadRecord(entityClass, id, state.getRequestScope()); String relationName = ctx.relationship().term().getText(); try { Optional<FilterExpression> filterExpression = state.getRequestScope().getExpressionForRelation(record, relationName); record.getRelationCheckedFiltered(relationName, filterExpression, Optional.empty(), Optional.empty()); } catch (InvalidAttributeException e) { throw new ForbiddenAccessException(entityName); } state.setState(new RelationshipTerminalState(record, relationName)); }
Source:
<code>Pair<Long, NavigableMap<String, Long>> getValidDataSizeByLogSegment(TimeRange timeRange) throws StoreException { ScanResults currentScanResults = scanResults.get(); Pair<Long, NavigableMap<String, Long>> retValue = null; long deleteAndExpirationRefTimeInMs = getLogSegmentRefTimeMs(currentScanResults, timeRange); if (deleteAndExpirationRefTimeInMs != -1) { retValue = currentScanResults.getValidSizePerLogSegment(deleteAndExpirationRefTimeInMs); } <START> if (retValue == null) { <END> if (isScanning) { deleteAndExpirationRefTimeInMs = getLogSegmentRefTimeMs(indexScanner.newScanResults, timeRange); if (deleteAndExpirationRefTimeInMs != -1) { synchronized (scanningLock) { while (isScanning) { try { scanningLock.wait(); } catch (InterruptedException e) { } } } retValue = getValidDataSizeByLogSegment(timeRange); } } if (retValue == null) { deleteAndExpirationRefTimeInMs = timeRange.getEndTimeInMs(); retValue = new Pair<>(deleteAndExpirationRefTimeInMs, collectValidDataSizeByLogSegment(deleteAndExpirationRefTimeInMs)); } } return retValue; }</code><technical_language>retValue null if currentScanResults.getValidSizePerLogSegment(deleteAndExpirationRefTimeInMs); called? If not, this part of else block</technical_language>

Target:
Pair<Long, NavigableMap<String, Long>> getValidDataSizeByLogSegment(TimeRange timeRange) throws StoreException { if (!enabled.get()) { throw new StoreException(String.format("BlobStoreStats is not enabled or closing for store %s", storeId), StoreErrorCodes.Store_Shutting_Down); } ScanResults currentScanResults = scanResults.get(); Pair<Long, NavigableMap<String, Long>> retValue = null; long referenceTimeInMs = getLogSegmentRefTimeMs(currentScanResults, timeRange); if (referenceTimeInMs != REF_TIME_OUT_OF_BOUNDS) { retValue = currentScanResults.getValidSizePerLogSegment(referenceTimeInMs); } else { if (isScanning && getLogSegmentRefTimeMs(indexScanner.newScanResults, timeRange) != REF_TIME_OUT_OF_BOUNDS) { scanLock.lock(); try { if (isScanning) { if (waitCondition.await(waitTimeoutInSecs, TimeUnit.SECONDS)) { currentScanResults = scanResults.get(); referenceTimeInMs = getLogSegmentRefTimeMs(currentScanResults, timeRange); if (referenceTimeInMs != REF_TIME_OUT_OF_BOUNDS) { retValue = currentScanResults.getValidSizePerLogSegment(referenceTimeInMs); } } else { metrics.blobStoreStatsIndexScannerErrorCount.inc(); logger.error("Timed out while waiting for BlobStoreStats index scan to complete for store {}", storeId); } } else { currentScanResults = scanResults.get(); referenceTimeInMs = getLogSegmentRefTimeMs(currentScanResults, timeRange); if (referenceTimeInMs != REF_TIME_OUT_OF_BOUNDS) { retValue = currentScanResults.getValidSizePerLogSegment(referenceTimeInMs); } } } catch (InterruptedException e) { metrics.blobStoreStatsIndexScannerErrorCount.inc(); throw new IllegalStateException( String.format("Illegal state, wait for scan to complete is interrupted for store %s", storeId), e); } finally { scanLock.unlock(); } } if (retValue == null) { referenceTimeInMs = timeRange.getEndTimeInMs(); retValue = new Pair<>(referenceTimeInMs, collectValidDataSizeByLogSegment(referenceTimeInMs)); } } return retValue; }
Source:
<code>public CoverageOverlay(final Context aContext, final String coverageUrl, MapView mapView) { super(aContext); final ITileSource coverageTileSource = new XYTileSource("Mozilla Location Service Coverage Map", null, <START> 12, 13, AbstractMapOverlay.TILE_PIXEL_SIZE, <END> ".png", new String[] { coverageUrl }); this.setLoadingBackgroundColor(Color.TRANSPARENT); mTileProvider.setTileRequestCompleteHandler(new SimpleInvalidationHandler(mapView)); mTileProvider.setTileSource(coverageTileSource); }</code><technical_language>magic numbers for zoom level. Pull out 12 13 MIN MAX zoom level constants</technical_language>

Target:
public CoverageOverlay(final Context aContext, final String coverageUrl, MapView mapView) { super(aContext); final ITileSource coverageTileSource = new XYTileSource("Mozilla Location Service Coverage Map", null, MIN_ZOOM_LEVEL_OF_MAP, MIN_ZOOM_LEVEL_OF_MAP, AbstractMapOverlay.TILE_PIXEL_SIZE, ".png", new String[] { coverageUrl }); this.setLoadingBackgroundColor(Color.TRANSPARENT); mTileProvider.setTileRequestCompleteHandler(new SimpleInvalidationHandler(mapView)); mTileProvider.setTileSource(coverageTileSource); }
Source:
<code>public void onNeutralClicked(@NonNull String instanceTag) { switch (instanceTag) { case TAG_QUICK_START_DIALOG: AppPrefs.setQuickStartDisabled(true); <START> AnalyticsTracker.track(AnalyticsTracker.Stat.QUICK_START_REQUEST_NEUTRAL_TAPPED); <END> break; default: AppLog.e(T.EDITOR, "Dialog instanceTag is not recognized"); throw new UnsupportedOperationException("Dialog instanceTag is not recognized"); } }</code><technical_language>remove unnecessary AnalyticsTracker qualification AnalyticsTracker.Stat.QUICK_START_REQUEST_NEUTRAL_TAPPED produce AnalyticsTracker.track(Stat.QUICK_START_REQUEST_NEUTRAL_TAPPED); for simplicity</technical_language>

Target:
public void onNeutralClicked(@NonNull String instanceTag) { switch (instanceTag) { case TAG_QUICK_START_DIALOG: AppPrefs.setQuickStartDisabled(true); AnalyticsTracker.track(Stat.QUICK_START_REQUEST_DIALOG_NEUTRAL_TAPPED); break; default: AppLog.e(T.EDITOR, "Dialog instanceTag is not recognized"); throw new UnsupportedOperationException("Dialog instanceTag is not recognized"); } }
Source:
<code>public LogCSVWriter(String filename, String dirname) throws FileNotFoundException, RuntimeException { try{ File sdCard = Environment.getExternalStorageDirectory(); File dir = new File(sdCard.getAbsolutePath() + File.separator + dirname); if (!dir.exists()) dir.mkdirs(); Log.d(TAG, "Path is " + sdCard.getAbsolutePath() + File.separator + dirname); File file = new File(dir, filename); FileOutputStream fos = new FileOutputStream(file); OutputStreamWriter osw = new OutputStreamWriter(fos); this.buf = new BufferedWriter(osw); this.isFirstLine = true; Log.d(TAG, "Constructed the LogCSVWriter"); } catch (Exception e) { <START> e.printStackTrace(); <END> } }</code><technical_language>This is do it, Log.e</technical_language>

Target:
public LogCSVWriter(String filename, String dirname) throws FileNotFoundException, RuntimeException { try{ File sdCard = Environment.getExternalStorageDirectory(); File dir = new File(sdCard.getAbsolutePath() + File.separator + dirname); if (!dir.exists()) dir.mkdirs(); Log.d(TAG, "Path is " + sdCard.getAbsolutePath() + File.separator + dirname); File file = new File(dir, filename); FileOutputStream fos = new FileOutputStream(file); OutputStreamWriter osw = new OutputStreamWriter(fos); this.buf = new BufferedWriter(osw); this.isFirstLine = true; Log.d(TAG, "Constructed the LogCSVWriter"); } catch (Exception e) { Log.e(TAG, "LogCSVWriter constructor failed"); } }
Source:
<code>private boolean addImageTicketToDaemon(Guid imagedTicketId, String <START> imagePath) { <END> if (getParameters().getTransferType() == TransferType.Upload && !setVolumeLegalityInStorage(ILLEGAL_IMAGE)) { return false; } ImageTicket imageTicket = buildImageTicket(imagedTicketId, imagePath); AddImageTicketVDSCommandParameters transferCommandParams = new AddImageTicketVDSCommandParameters(getVdsId(), imageTicket); VDSReturnValue vdsRetVal; try { vdsRetVal = vdsBroker.runVdsCommand(VDSCommandType.AddImageTicket, transferCommandParams); } catch (RuntimeException e) { log.error("Failed to start image transfer session: {}", e.getMessage(), e); return false; } if (!vdsRetVal.getSucceeded()) { log.error("Failed to start image transfer session"); return false; } log.info("Started transfer session with ticket id {}, timeout seconds", imagedTicketId.toString(), imageTicket.getTimeout()); return true; }</code><technical_language>This is a path a URL: (e.g. "file:///path/to/image" "nbd:unix:/path/to/socket"). In a future patch need fix name match reality</technical_language>

Target:
private boolean addImageTicketToDaemon(Guid imagedTicketId, String imagePath) { if (getParameters().getTransferType() == TransferType.Upload && !setVolumeLegalityInStorage(ILLEGAL_IMAGE)) { return false; } ImageTicket ticket = buildImageTicket(imagedTicketId, imagePath); AddImageTicketVDSCommandParameters transferCommandParams = new AddImageTicketVDSCommandParameters(getVdsId(), ticket); VDSReturnValue vdsRetVal; try { vdsRetVal = vdsBroker.runVdsCommand(VDSCommandType.AddImageTicket, transferCommandParams); } catch (RuntimeException e) { log.error("Failed to start image transfer session: {}", e.getMessage(), e); return false; } if (!vdsRetVal.getSucceeded()) { log.error("Failed to start image transfer session"); return false; } log.info("Started transfer session with ticket id {}, timeout seconds", imagedTicketId.toString(), ticket.getTimeout()); return true; }
Source:
<code>private void createHandlerLocationControls(Composite parent) { handlerComposite = new Composite(parent, SWT.NONE); GridLayoutFactory.fillDefaults().numColumns(2).applyTo(handlerComposite); GridDataFactory.fillDefaults().grab(true, false).applyTo(handlerComposite); WidgetFactory.label(SWT.NONE).text(UrlHandlerPreferencePage_Handler_Label).create(handlerComposite); handlerLocation = WidgetFactory.text(SWT.READ_ONLY | SWT.BORDER) <START> .supplyLayoutData(() -> new GridData(SWT.FILL, SWT.CENTER, true, false)).create(handlerComposite); <END> handlerComposite.setVisible(false); }</code><technical_language>calling .layoutData(new GridData(......)).create... ok here, correct? changed supplier layoutData in addFiller()</technical_language>

Target:
private void createHandlerLocationControls(Composite parent) { handlerComposite = new Composite(parent, SWT.NONE); GridLayoutFactory.fillDefaults().numColumns(2).applyTo(handlerComposite); GridDataFactory.fillDefaults().grab(true, false).applyTo(handlerComposite); WidgetFactory.label(SWT.NONE).text(UrlHandlerPreferencePage_Handler_Label).create(handlerComposite); handlerLocation = WidgetFactory.text(SWT.READ_ONLY | SWT.BORDER) .layoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)).create(handlerComposite); handlerComposite.setVisible(false); }
Source:
<code><START> public void start() throws XAException, SystemException, InvalidTransactionException, IllegalStateException, NamingException <END> { txbridgeLogger.logger.trace("InboundBridge.start(Xid="+xid+")"); Transaction tx = getTransaction(); TransactionManager.transactionManager(new InitialContext()).resume(tx); }</code><technical_language>This is changing a public interface deprecation rules apply</technical_language>

Target:
public void start() throws XAException, SystemException, InvalidTransactionException { txbridgeLogger.logger.trace("InboundBridge.start(Xid="+xid+")"); Transaction tx = getTransaction(); TransactionManager.transactionManager(ctx).resume(tx); }
Source:
<code>public void assertAll() { if (!m_errors.isEmpty()) { StringBuilder sb = new StringBuilder("The following asserts failed:"); boolean first = true; for (AssertionError error : m_errors.keySet()) { if (first) { first = false; } else { sb.append(","); } sb.append("\n\t"); sb.append(error.getMessage()); Throwable cause = error.getCause(); while (cause != null) { sb.append(" ").append(cause.getMessage()); cause = cause.getCause(); } <START> sb.append(StackTraceTools.formatByStackTrace(error.getStackTrace()[4])); <END> } throw new AssertionError(sb.toString()); } }</code><technical_language>arriving this number of 4</technical_language>

Target:
public void assertAll() { if (!m_errors.isEmpty()) { StringBuilder sb = new StringBuilder("The following asserts failed:"); boolean first = true; for (AssertionError error : m_errors.keySet()) { if (first) { first = false; } else { sb.append(","); } sb.append("\n\t"); sb.append(getErrorDetails(error)); } throw new AssertionError(sb.toString()); } }
Source:
<code>public static <START> final AbstractTextColumn<Disk> <END> getLogicalNameColumn(String sortBy) { AbstractTextColumn<Disk> column = new AbstractTextColumn<Disk>() { @Override public String getValue(Disk object) { if (object.getDiskVmElements().size() == 1) { return object.getDiskVmElements().iterator().next().getLogicalName(); } return null; } }; return makeSortable(column, sortBy); }</code><technical_language>skip final</technical_language>

Target:
public static AbstractTextColumn<Disk> getLogicalNameColumn(String sortBy) { AbstractTextColumn<Disk> column = new AbstractTextColumn<Disk>() { @Override public String getValue(Disk object) { if (object.getDiskVmElements().size() == 1) { return object.getDiskVmElements().iterator().next().getLogicalName(); } return null; } }; return makeSortable(column, sortBy); }
Source:
<code><START> private Font makeFont(Font font, String boldKey, String italicKey) <END> { IPreferenceStore store = TraditionalRenderingPlugin.getDefault().getPreferenceStore(); boolean bold = store.getBoolean(boldKey); boolean italic = store.getBoolean(italicKey); int style = SWT.NONE; if(bold) style |= SWT.BOLD; if(italic) style |= SWT.ITALIC; if(style == SWT.NONE) return font; Font modified = fonts.get(style); if(modified == null) { FontData fontData = font.getFontData()[0]; modified = new Font(font.getDevice(), fontData.getName(), fontData.getHeight(), fontData.getStyle() | style); fonts.put(style, modified); } return modified; }</code><technical_language>values for boldKey (and italicKey), change parameters a single boolean isEdit, removing duplication of references TraditionalRenderingPreferenceConstants</technical_language>

Target:
private Font makeFont(Font font, String boldKey, String italicKey) { IPreferenceStore store = TraditionalRenderingPlugin.getDefault().getPreferenceStore(); int style = SWT.NONE; if (store.getBoolean(boldKey)) style |= SWT.BOLD; if (store.getBoolean(italicKey)) style |= SWT.ITALIC; if (style == SWT.NONE) return font; Font modified = fonts.get(style); if (modified == null) { FontData fontData = font.getFontData()[0]; modified = new Font(font.getDevice(), fontData.getName(), fontData.getHeight(), fontData.getStyle() | style); fonts.put(style, modified); } return modified; }
Source:
<code>public void execute(Context context) throws SQLException { context.execute(new AddColumnsBuilder(getDialect(), "users") .addColumn(newVarcharColumnDefBuilder() .setColumnName("homepage_type") .setIsNullable(true) <START> .setLimit(40) <END> .build()) .addColumn(newVarcharColumnDefBuilder() .setColumnName("homepage_key") .setIsNullable(true) .setLimit(64) .build()) .build()); }</code><technical_language>40 a limit</technical_language>

Target:
public void execute(Context context) throws SQLException { context.execute(new AddColumnsBuilder(getDialect(), "users") .addColumn(newVarcharColumnDefBuilder() .setColumnName("homepage_type") .setIsNullable(true) .setLimit(40) .build()) .addColumn(newVarcharColumnDefBuilder() .setColumnName("homepage_value") .setIsNullable(true) .setLimit(40) .build()) .build()); }
Source:
<code>public boolean shouldInline(PushAttachmentsInline inlinePreference) { if (inlinePreference == PushAttachmentsInline.False || inlinePreference == PushAttachmentsInline.Small && this.isLarge()) { <START> logger.info("inline false"); <END> return false; } else { logger.info("inline true"); return true; } }</code><technical_language>"finer" log message more useful</technical_language>

Target:
public boolean shouldInline(PushAttachmentsInline inlinePreference) { if (inlinePreference == PushAttachmentsInline.False || inlinePreference == PushAttachmentsInline.Small && this.isLarge()) { logger.finer("inline false"); return false; } else { logger.finer("inline true"); return true; } }
Source:
<code>public void EditAccount_001_closeAccount() { WikiBasePageObject base = new WikiBasePageObject(driver); base.logInCookie(credentials.userNameStaff, credentials.passwordStaff, wikiURL); EditAccount editAccount = new EditAccount(driver, testedWiki, credentials.userNameClosedAccount); <START> editAccount.closeAccount(PageContent.caption); <END> }</code><technical_language>add verifying step</technical_language>

Target:
public void EditAccount_001_closeAccount() { WikiBasePageObject base = new WikiBasePageObject(driver); base.logInCookie(credentials.userNameStaff, credentials.passwordStaff, wikiURL); EditAccount editAccount = new EditAccount(driver, testedWiki, credentials.userNameClosedAccount); editAccount.closeAccount(PageContent.caption); editAccount.verifyAccountClosedMessage(); }
Source:
<code>public void testWriteAndReadAsyncVCFHeaderless() throws IOException { final File fakeVCFFile = VariantBaseTest.createTempFile("testWriteAndReadAsyncVCFHeaderless.", ".vcf"); Tribble.indexFile(fakeVCFFile).deleteOnExit(); Set<VCFHeaderLine> metaData = new HashSet<VCFHeaderLine>(); Set<String> additionalColumns = new HashSet<String>(); final SAMSequenceDictionary sequenceDict = createArtificialSequenceDictionary(); final VCFHeader header = createFakeHeader(metaData, additionalColumns, sequenceDict); try (final VariantContextWriter writer = new VariantContextWriterBuilder() .setOutputFile(fakeVCFFile).setReferenceDictionary(sequenceDict) .setOptions(EnumSet.of(Options.ALLOW_MISSING_FIELDS_IN_HEADER, Options.INDEX_ON_THE_FLY, Options.USE_ASYNC_IO)) .build()) { writer.setVCFHeader(header); writer.add(createVC(header)); writer.add(createVC(header)); } final VCFCodec codec = new VCFCodec(); codec.setVCFHeader(header, VCFHeaderVersion.VCF4_2); try (FileInputStream fis = new FileInputStream(fakeVCFFile)) { AsciiLineReaderIterator iterator; <START> iterator = new AsciiLineReaderIterator(new AsciiLineReader(fis)); <END> int counter = 0; while (iterator.hasNext()) { VariantContext context = codec.decode(iterator.next()); counter++; } Assert.assertEquals(counter, 2); } }</code><technical_language>Please combine lines 96 98 line</technical_language>

Target:
public void testWriteAndReadAsyncVCFHeaderless() throws IOException { final File fakeVCFFile = VariantBaseTest.createTempFile("testWriteAndReadAsyncVCFHeaderless.", ".vcf"); fakeVCFFile.deleteOnExit(); Tribble.indexFile(fakeVCFFile).deleteOnExit(); final Set<VCFHeaderLine> metaData = new HashSet<>(); final Set<String> additionalColumns = new HashSet<>(); final SAMSequenceDictionary sequenceDict = createArtificialSequenceDictionary(); final VCFHeader header = createFakeHeader(metaData, additionalColumns, sequenceDict); try (final VariantContextWriter writer = new VariantContextWriterBuilder() .setOutputFile(fakeVCFFile).setReferenceDictionary(sequenceDict) .setOptions(EnumSet.of(Options.ALLOW_MISSING_FIELDS_IN_HEADER, Options.INDEX_ON_THE_FLY, Options.USE_ASYNC_IO)) .build()) { writer.setVCFHeader(header); writer.add(createVC(header)); writer.add(createVC(header)); } final VCFCodec codec = new VCFCodec(); codec.setVCFHeader(header, VCFHeaderVersion.VCF4_2); try (final FileInputStream fis = new FileInputStream(fakeVCFFile)) { final AsciiLineReaderIterator iterator = new AsciiLineReaderIterator(new AsciiLineReader(fis)); int counter = 0; while (iterator.hasNext()) { VariantContext context = codec.decode(iterator.next()); counter++; } Assert.assertEquals(counter, 2); } }
Source:
<code>public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof DirectoryV3DevicesPostResponse)) return false; DirectoryV3DevicesPostResponse that = (DirectoryV3DevicesPostResponse) o; return Objects.equals(getCode(), that.getCode()) && <START> Objects.equals(qrcode, that.qrcode) && <END> Objects.equals(getDeviceId(), that.getDeviceId()); }</code><technical_language>qrcode a getter</technical_language>

Target:
public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof DirectoryV3DevicesPostResponse)) return false; DirectoryV3DevicesPostResponse that = (DirectoryV3DevicesPostResponse) o; return Objects.equals(getCode(), that.getCode()) && Objects.equals(getQRCode(), that.getQRCode()) && Objects.equals(getDeviceId(), that.getDeviceId()); }
Source:
<code>public void testConnectingToRM() throws Exception { conf.set(YarnConfiguration.CLIENT_FAILOVER_NO_HA_PROXY_PROVIDER, AutoRefreshNoHARMFailoverProxyProvider.class.getName()); MiniYARNCluster cluster = new MiniYARNCluster( "testRestartedRMNegative", NODE_MANAGER_COUNT, 1, 1); <START> YarnClient rmClient = null; <END> try { cluster.init(conf); cluster.start(); final Configuration yarnConf = cluster.getConfig(); rmClient = YarnClient.createYarnClient(); rmClient.init(yarnConf); rmClient.start(); List<NodeReport> nodeReports = rmClient.getNodeReports(); Assert.assertEquals( "The proxy didn't get expected number of node reports", NODE_MANAGER_COUNT, nodeReports.size()); } finally { if (rmClient != null) { rmClient.stop(); } cluster.stop(); } }</code><technical_language>try. Potentially part of @After</technical_language>

Target:
public void testConnectingToRM() throws Exception { conf.setClass(YarnConfiguration.CLIENT_FAILOVER_NO_HA_PROXY_PROVIDER, AutoRefreshNoHARMFailoverProxyProvider.class, RMFailoverProxyProvider.class); MiniYARNCluster cluster = new MiniYARNCluster("testRestartedRMNegative", NUMNODEMANAGERS, 1, 1); YarnClient rmClient = null; try { cluster.init(conf); cluster.start(); final Configuration yarnConf = cluster.getConfig(); rmClient = YarnClient.createYarnClient(); rmClient.init(yarnConf); rmClient.start(); List <NodeReport> nodeReports = rmClient.getNodeReports(); assertEquals( "The proxy didn't get expected number of node reports", NUMNODEMANAGERS, nodeReports.size()); } finally { if (rmClient != null) { rmClient.stop(); } cluster.stop(); } }
Source:
<code>private void mockRequestBody(String json) throws IOException { <START> ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(json.getBytes()); <END> when(mockServletInputStream.read(Matchers.any(), anyInt(), anyInt())).thenAnswer(invocationOnMock -> { Object[] args = invocationOnMock.getArguments(); byte[] output = (byte[]) args[0]; int offset = (int) args[1]; int length = (int) args[2]; return byteArrayInputStream.read(output, offset, length); }); when(request.getInputStream()).thenReturn(mockServletInputStream); }</code><technical_language>this in a try resources</technical_language>

Target:
private void mockRequestBody(String json) throws IOException { try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(json.getBytes())) { when(mockServletInputStream.read(Matchers.any(), anyInt(), anyInt())).thenAnswer(invocationOnMock -> { Object[] args = invocationOnMock.getArguments(); byte[] output = (byte[]) args[0]; int offset = (int) args[1]; int length = (int) args[2]; return byteArrayInputStream.read(output, offset, length); }); when(request.getInputStream()).thenReturn(mockServletInputStream); } }
Source:
<code><START> private int getStatusCode(HttpURLConnection connection) throws IOException { <END> int statusCode = HttpURLConnection.HTTP_BAD_REQUEST; try { statusCode = connection.getResponseCode(); } catch (IOException ex) { if (Build.VERSION.SDK_INT < 16) { if (ex.getMessage().equals(UNAUTHORIZED_ERROR_MESSAGE_PRE18)) { statusCode = HttpURLConnection.HTTP_UNAUTHORIZED; } } else { statusCode = connection.getResponseCode(); } if (statusCode != HttpURLConnection.HTTP_OK && statusCode != HttpURLConnection.HTTP_UNAUTHORIZED) { throw ex; } } Logger.v(TAG, "Status code:" + statusCode); return statusCode; }</code><technical_language>static now</technical_language>

Target:
private static int getStatusCode(HttpURLConnection connection) throws IOException { int statusCode = HttpURLConnection.HTTP_BAD_REQUEST; try { statusCode = connection.getResponseCode(); } catch (IOException ex) { if (Build.VERSION.SDK_INT < 16) { if (ex.getMessage().equals(UNAUTHORIZED_ERROR_MESSAGE_PRE18)) { statusCode = HttpURLConnection.HTTP_UNAUTHORIZED; } } else { statusCode = connection.getResponseCode(); } if (statusCode != HttpURLConnection.HTTP_OK && statusCode != HttpURLConnection.HTTP_UNAUTHORIZED) { throw ex; } } Logger.v(TAG, "Status code:" + statusCode); return statusCode; }
Source:
<code>private PersonFunction getDelegateFunction(ExecutionYear executionYear, final Person person) { PersonFunction delegateFunction = null; if (person.hasStudent()) { final Student student = person.getStudent(); List<Registration> activeRegistrations = new ArrayList<Registration>(student.getActiveRegistrations()); Collections.sort(activeRegistrations, Registration.COMPARATOR_BY_START_DATE); for (Registration registration : activeRegistrations) { delegateFunction = registration.getDegree().getMostSignificantDelegateFunctionForStudent(student, executionYear); if (delegateFunction != null && delegateFunction.isActive()) { break; } <START> delegateFunction = null; <END> } } else { delegateFunction = person.getActiveGGAEDelegatePersonFunction(); } return delegateFunction; }</code><technical_language>unnecessary code</technical_language>

Target:
private PersonFunction getDelegateFunction(ExecutionYear executionYear, final Person person) { PersonFunction delegateFunction = null; if (person.hasStudent()) { final Student student = person.getStudent(); List<Registration> activeRegistrations = new ArrayList<Registration>(student.getActiveRegistrations()); Collections.sort(activeRegistrations, Registration.COMPARATOR_BY_START_DATE); for (Registration registration : activeRegistrations) { delegateFunction = registration.getDegree().getMostSignificantDelegateFunctionForStudent(student, executionYear); if (delegateFunction != null && delegateFunction.isActive()) { return delegateFunction; } } } else { return person.getActiveGGAEDelegatePersonFunction(); } return null; }
Source:
<code>public void testDefaultJobName() { StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); <START> env.fromCollection(new DummySplittableIterator<>(), BasicTypeInfo.INT_TYPE_INFO).addSink(new DiscardingSink<>()); <END> StreamGraph streamGraph = env.getStreamGraph(); assertEquals(StreamExecutionEnvironment.DEFAULT_JOB_NAME, streamGraph.getJobName()); }</code><technical_language>nit: simplify test env.fromElements(1, 2, 3).print()</technical_language>

Target:
public void testDefaultJobName() { StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); testJobName(StreamExecutionEnvironment.DEFAULT_JOB_NAME, env); }
Source:
<code>public void testSerializeVersionHeader() throws IOException, ClassNotFoundException { <START> VersionHeader versionHeader = new VersionHeader(); <END> versionHeader.setVersionedItem("SomeThing"); versionHeader.setVersionString("1.0.1"); VersionHeader deserialized = TestUtil.serializeAndDeserialize(versionHeader); Assert.assertEquals(deserialized, versionHeader); }</code><technical_language>add final</technical_language>

Target:
public void testSerializeVersionHeader() throws IOException, ClassNotFoundException { final VersionHeader versionHeader = new VersionHeader(); versionHeader.setVersionedItem("SomeThing"); versionHeader.setVersionString("1.0.1"); final VersionHeader deserialized = TestUtil.serializeAndDeserialize(versionHeader); Assert.assertEquals(deserialized, versionHeader); }
Source:
<code><START> protected DataContainer waitUntilDataContainerWillBeIteratedOn(final Cache<?, ?> cache, final CheckPoint checkPoint) { <END> DataContainer dataContainer = TestingUtil.extractComponent(cache, DataContainer.class); final Answer<Object> forwardedAnswer = AdditionalAnswers.delegatesTo(dataContainer); DataContainer mocaContainer = mock(DataContainer.class, withSettings().defaultAnswer(forwardedAnswer)); final AtomicInteger invocationCount = new AtomicInteger(); doAnswer(invocation -> { boolean waiting = false; if (invocationCount.getAndIncrement() == 0) { waiting = true; checkPoint.trigger("pre_iterator_invoked"); checkPoint.awaitStrict("pre_iterator_released", 10, TimeUnit.SECONDS); } try { return forwardedAnswer.answer(invocation); } finally { invocationCount.getAndDecrement(); if (waiting) { checkPoint.trigger("post_iterator_invoked"); checkPoint.awaitStrict("post_iterator_released", 10, TimeUnit.SECONDS); } } }).when(mocaContainer).iterator(); TestingUtil.replaceComponent(cache, DataContainer.class, mocaContainer, true); return dataContainer; }</code><technical_language>void</technical_language>

Target:
protected void waitUntilDataContainerWillBeIteratedOn(final Cache<?, ?> cache, final CheckPoint checkPoint) { DataContainer dataContainer = TestingUtil.extractComponent(cache, DataContainer.class); final Answer<Object> forwardedAnswer = AdditionalAnswers.delegatesTo(dataContainer); DataContainer mocaContainer = mock(DataContainer.class, withSettings().defaultAnswer(forwardedAnswer)); final AtomicInteger invocationCount = new AtomicInteger(); doAnswer(invocation -> { boolean waiting = false; if (invocationCount.getAndIncrement() == 0) { waiting = true; checkPoint.trigger("pre_iterator_invoked"); checkPoint.awaitStrict("pre_iterator_released", 10, TimeUnit.SECONDS); } try { return forwardedAnswer.answer(invocation); } finally { invocationCount.getAndDecrement(); if (waiting) { checkPoint.trigger("post_iterator_invoked"); checkPoint.awaitStrict("post_iterator_released", 10, TimeUnit.SECONDS); } } }).when(mocaContainer).iterator(); TestingUtil.replaceComponent(cache, DataContainer.class, mocaContainer, true); }
Source:
<code>private NetworkVO getDefaultNetwork (long vmId) { NicVO defaultNic = _nicDao.findDefaultNicForVM(vmId); <START> if (defaultNic != null ) return _networkDao.findById(_nicDao.findById(defaultNic.getId()).getNetworkId()); <END> return null; }</code><technical_language>necessary fetch nic DB twice</technical_language>

Target:
private Long getDefaultNetwork(long vmId) { NicVO defaultNic = _nicDao.findDefaultNicForVM(vmId); if (defaultNic != null) { return defaultNic.getNetworkId(); } return null; }
Source:
<code>public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext extensionContext) { Optional<Method> testMethod = extensionContext.getTestMethod(); if (!testMethod.isPresent()) { return enabled(""); } Class<?> testClass = extensionContext.getRequiredTestClass(); Optional<RequiredFeatures> methodRequires = testMethod.map(method -> method.getAnnotation(RequiredFeatures.class)); List<RequiredFeatures> classRequires = getClassRequiredFeatures(testMethod.get().getDeclaringClass()); Optional<SupportedFeatures> classSupports = Optional.ofNullable(testClass.getAnnotation(SupportedFeatures.class)); Set<ConnectorFeature> requiredFeatures = Stream.concat( streamOfRequired(methodRequires), classRequires.stream().flatMap(r -> Arrays.stream(r.value()))) .distinct() .collect(Collectors.toCollection(HashSet::new)); Set<ConnectorFeature> supportedFeatures = streamOfSupported(classSupports) .distinct() .collect(toImmutableSet()); <START> requiredFeatures.removeAll(supportedFeatures); <END> return requiredFeatures.isEmpty() ? enabled("All required features present") : disabled("Missing required features: " + Joiner.on(", ").join(requiredFeatures)); }</code><technical_language>Do modify requiredFeatures here. Assign difference Set<ConnectorFeature> missingFeatures. Sets.difference method compute difference</technical_language>

Target:
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext extensionContext) { Optional<Method> testMethod = extensionContext.getTestMethod(); if (!testMethod.isPresent()) { return enabled(""); } Class<?> testClass = extensionContext.getRequiredTestClass(); List<ConnectorFeature> classRequires = getClassRequiredFeatures(testMethod.get().getDeclaringClass()); Stream<ConnectorFeature> classSupports = streamOfSupported(testClass); Set<ConnectorFeature> requiredFeatures = Stream.concat( streamOfRequired(testMethod.get()), classRequires.stream()) .distinct() .collect(toImmutableSet()); Set<ConnectorFeature> supportedFeatures = streamOfSupported(testClass) .distinct() .collect(toImmutableSet()); Set<ConnectorFeature> missingFeatures = Sets.difference(requiredFeatures, supportedFeatures); return missingFeatures.isEmpty() ? enabled("All required features present") : disabled("Missing required features: " + Joiner.on(", ").join(missingFeatures)); }
Source:
<code>public void addsCookieToResponse() throws IOException { MatcherAssert.assertThat( new RsPrint( new PsCookie( new CcPlain(), "foo", 1L <START> ).exit(new RsEmpty(), PsCookieTest.identity) <END> ).print(), Matchers.containsString( "Set-Cookie: foo=urn%3Atest%3A99;Path=/;HttpOnly;" ) ); }</code><technical_language>@danff input data for test remove constant</technical_language>

Target:
public void addsCookieToResponse() throws IOException { MatcherAssert.assertThat( new RsPrint( new PsCookie( new CcPlain(), "foo", 1L ).exit(new RsEmpty(), new Identity.Simple("urn:test:99")) ).print(), Matchers.containsString( "Set-Cookie: foo=urn%3Atest%3A99;Path=/;HttpOnly;" ) ); }