auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public boolean allowRetry(int retryCount, long elapsedTimeMs, RetrySleeper sleeper) { try { sleeper.sleepFor(retryIntervalMs, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { <START> log.warn("Error occurred while sleeping", e); <END> } return true; }</code><technical_language>catching InterrptedException, reset state via: java Thread.currentThread().interrupt();</technical_language>

Target:
public boolean allowRetry(int retryCount, long elapsedTimeMs, RetrySleeper sleeper) { try { sleeper.sleepFor(retryIntervalMs, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { log.warn("Error occurred while sleeping", e); Thread.currentThread().interrupt(); } return true; }
Source:
<code>private Expression simplifyExpression(Session session, Expression predicate, TypeProvider types) { Map<NodeRef<Expression>, Type> expressionTypes = getExpressionTypes(session, predicate, types); ExpressionInterpreter interpreter = ExpressionInterpreter.expressionOptimizer(predicate, metadata, session, expressionTypes); Object value = interpreter.optimize(NoOpSymbolResolver.INSTANCE); <START> if (value instanceof Expression) { <END> return (Expression) value; } if (value == null) { value = false; } return literalEncoder.toExpression(value, BOOLEAN); }</code><technical_language>literalEncoder.toExpression() returns Expression if is instanceof Expression, a NullLiteral if equals null. I get rid of if statements return literalEncoder.toExpression(value,BOOLEAN). add a visitNullLiteral FilterExpressionStatsCalculatingVisitor</technical_language>

Target:
private Expression simplifyExpression(Session session, Expression predicate, TypeProvider types) { Map<NodeRef<Expression>, Type> expressionTypes = getExpressionTypes(session, predicate, types); ExpressionInterpreter interpreter = ExpressionInterpreter.expressionOptimizer(predicate, metadata, session, expressionTypes); Object value = interpreter.optimize(NoOpSymbolResolver.INSTANCE); if (value == null) { value = false; } return literalEncoder.toExpression(value, BOOLEAN); }
Source:
<code>public T remove(int index) { try { T removedObject = super.remove(index); comparingSet.remove(removedObject); return removedObject; <START> } catch (IndexOutOfBoundsException ioobException) { <END> throw new IndexOutOfBoundsException(); } }</code><technical_language>again. please throw original exception</technical_language>

Target:
public T remove(int index) { try { T removedObject = super.remove(index); comparingSet.remove(removedObject); return removedObject; } catch (IndexOutOfBoundsException ioobException) { throw ioobException; } }
Source:
<code>private void useRegistryForConfigIfNecessary() { registries.stream().filter(RegistryConfig::isZookeeperProtocol).findFirst().ifPresent(rc -> { Environment.getInstance().getDynamicConfiguration().orElseGet(() -> { ConfigManager configManager = ConfigManager.getInstance(); ConfigCenterConfig cc = configManager.getConfigCenter().orElse(new ConfigCenterConfig()); if (StringUtils.isNotEmpty(rc.getClient())) { Map<String, String> newParametersMap = cc.getParameters() != null ? cc.getParameters() : new HashMap<>(); newParametersMap.put(CLIENT_KEY, rc.getClient()); cc.setParameters(newParametersMap); } cc.setProtocol(rc.getProtocol()); cc.setAddress(rc.getAddress()); <START> cc.setHighestPriority(false); <END> setConfigCenter(cc); startConfigCenter(); return null; }); }); }</code><technical_language>java if (StringUtils.isNotEmpty(rc.getClient())) { Map<String, String> parameters = cc.getParameters(); if(parameters == null) { parameters = new HashMap<>(); cc.setParameters(parameters); } parameters.putIfAbsent(CLIENT_KEY, rc.getClient()); }</technical_language>

Target:
private void useRegistryForConfigIfNecessary() { registries.stream().filter(RegistryConfig::isZookeeperProtocol).findFirst().ifPresent(rc -> { Environment.getInstance().getDynamicConfiguration().orElseGet(() -> { ConfigManager configManager = ConfigManager.getInstance(); ConfigCenterConfig cc = configManager.getConfigCenter().orElse(new ConfigCenterConfig()); if (StringUtils.isNotEmpty(rc.getClient())) { Map<String, String> parameters = cc.getParameters(); if (parameters == null) { parameters = new HashMap<>(); cc.setParameters(parameters); } parameters.putIfAbsent(CLIENT_KEY, rc.getClient()); } cc.setProtocol(rc.getProtocol()); cc.setAddress(rc.getAddress()); cc.setHighestPriority(false); setConfigCenter(cc); startConfigCenter(); return null; }); }); }
Source:
<code>public JMenuItem[] getMenuItemsAtLocation(MENU_LOCATION location) { <START> if (location == MENU_LOCATION.TOOLS) { <END> JMenuItem menuItemIC = new JMenuItem(JMeterUtils.getResString("generate_report_ui.html_report_menu"), KeyEvent.VK_UNDEFINED); menuItemIC.setName(ActionNames.HTML_REPORT); menuItemIC.setActionCommand(ActionNames.HTML_REPORT); menuItemIC.setAccelerator(null); menuItemIC.addActionListener(ActionRouter.getInstance()); return new JMenuItem[] { menuItemIC }; } return new JMenuItem[0]; }</code><technical_language>invert this if a guard clause location != MENU_LOCATION.TOOLS</technical_language>

Target:
public JMenuItem[] getMenuItemsAtLocation(MENU_LOCATION location) { if (location != MENU_LOCATION.TOOLS) { return new JMenuItem[0]; } JMenuItem menuItem = new JMenuItem(JMeterUtils.getResString("generate_report_ui.html_report_menu"), KeyEvent.VK_UNDEFINED); menuItem.setName(ActionNames.HTML_REPORT); menuItem.setActionCommand(ActionNames.HTML_REPORT); menuItem.setAccelerator(null); menuItem.addActionListener(ActionRouter.getInstance()); return new JMenuItem[] { menuItem }; }
Source:
<code>private String buildHashedPayload(HttpRequest request) { String hashedPayload = ""; try { byte[] unhashedBytes = request.getPayload() == null ? "".getBytes() : ByteStreams.toByteArray(request .getPayload().getInput()); <START> hashedPayload = sha256(unhashedBytes); <END> } catch (IOException e) { throw new HttpException("Error signing request", e); } return hashedPayload; }</code><technical_language>Return result of sha256 instead of local variable</technical_language>

Target:
private static String buildHashedPayload(HttpRequest request) { try { byte[] unhashedBytes = request.getPayload() == null ? "".getBytes() : ByteStreams.toByteArray(request .getPayload().getInput()); return sha256(unhashedBytes); } catch (IOException e) { throw new HttpException("Error signing request", e); } }
Source:
<code>protected void runJob() { JNodeCache nodeCache = cache.getNodeCache(); final TextSearchIndex index = new TextSearchIndex(nodeCache); final CodeUsageInfo usageInfo = new CodeUsageInfo(nodeCache); cache.setTextIndex(index); cache.setUsageInfo(usageInfo); final boolean alwaysIndex = !wrapper.getSettings().isSkipClassIndexingIfLowMemory(); for (final JavaClass cls : wrapper.getIncludedClasses()) { addTask(new Runnable() { @Override public void run() { try { index.indexNames(cls); CodeLinesInfo linesInfo = new CodeLinesInfo(cls); List<StringRef> lines = splitLines(cls); usageInfo.processClass(cls, linesInfo, lines); <START> if (alwaysIndex || Utils.isFreeMemoryAvailable()) { <END> index.indexCode(cls, linesInfo, lines); } else { index.classCodeIndexSkipped(cls); } } catch (Exception e) { LOG.error("Index error in class: {}", cls.getFullName(), e); } } }); } }</code><technical_language>add option SkipClassIndexingIfLowMemory? If alwaysIndex ==true free memory left jadx hang GC eat CPU. purpose of this option</technical_language>

Target:
protected void runJob() { JNodeCache nodeCache = cache.getNodeCache(); final TextSearchIndex index = new TextSearchIndex(nodeCache); final CodeUsageInfo usageInfo = new CodeUsageInfo(nodeCache); cache.setTextIndex(index); cache.setUsageInfo(usageInfo); for (final JavaClass cls : wrapper.getIncludedClasses()) { addTask(new Runnable() { @Override public void run() { try { index.indexNames(cls); CodeLinesInfo linesInfo = new CodeLinesInfo(cls); List<StringRef> lines = splitLines(cls); usageInfo.processClass(cls, linesInfo, lines); if (Utils.isFreeMemoryAvailable()) { index.indexCode(cls, linesInfo, lines); } else { index.classCodeIndexSkipped(cls); } } catch (Exception e) { LOG.error("Index error in class: {}", cls.getFullName(), e); } } }); } }
Source:
<code><START> public static String map(org.ovirt.engine.core.common.businessentities.gluster.GlusterHookContentType hookContentType, <END> String template) { switch (hookContentType) { case BINARY: return org.ovirt.engine.core.common.businessentities.gluster.GlusterHookContentType.BINARY.toString(); case TEXT: return org.ovirt.engine.core.common.businessentities.gluster.GlusterHookContentType.TEXT.toString(); default: return null; } }</code><technical_language>this mapping happen public enum mapping backend enum string</technical_language>

Target:
public static String map(org.ovirt.engine.core.common.businessentities.gluster.GlusterHookContentType hookContentType, String template) { switch (hookContentType) { case BINARY: return HookContentType.BINARY.toString(); case TEXT: return HookContentType.TEXT.toString(); default: return null; } }
Source:
<code>@Override public void unparseCall(SqlWriter writer, SqlCall call, int leftPrec, int rightPrec) { switch (call.getKind()) { case FLOOR: if (call.operandCount() != 2) { super.unparseCall(writer, call, leftPrec, rightPrec); return; } unparseFloor(writer, call); break; case ROW: <START> unparseRow(writer, call); <END> break; default: super.unparseCall(writer, call, leftPrec, rightPrec); } }</code><technical_language>Thanks for fix @quxiucheng, i this patch promoted a little, move this logic parent class SqlDialect, get SqlConformance dialect decide if generates ROW keyword based method SqlConformance#allowExplicitRowValueConstructor . [1] <LINK_0></technical_language>

Target:
@Override public void unparseCall(SqlWriter writer, SqlCall call, int leftPrec, int rightPrec) { switch (call.getKind()) { case FLOOR: if (call.operandCount() != 2) { super.unparseCall(writer, call, leftPrec, rightPrec); return; } unparseFloor(writer, call); break; default: super.unparseCall(writer, call, leftPrec, rightPrec); } }
Source:
<code><START> public static synchronized void stop() { <END> if (recoveryManager != null) { recoveryManager.terminate(); recoveryManager = null; } }</code><technical_language>unbind JNDI? remove datasources</technical_language>

Target:
public static synchronized void stop() { if (!initialized) return; if (recoveryManager != null) { recoveryManager.terminate(); recoveryManager = null; } unregisterJndiBindings(); try { DriverManager.deregisterDriver(new TransactionalDriver()); } catch (SQLException e) { if (tsLogger.logger.isInfoEnabled()) tsLogger.logger.debug("Unable to deregister TransactionalDriver: " + e.getMessage(), e); } if (replacedJndiProperties) jdbcPropertyManager.getJDBCEnvironmentBean().setJndiProperties(null); initialized = false; }
Source:
<code>private List<List<String>> readCSVFile(File csvFile) throws IOException { List<List<String>> rows = new ArrayList<>(); try (BufferedReader buffer = new BufferedReader(new FileReader(csvFile))) { String lineString; while ((lineString = buffer.readLine()) != null) { <START> String[] columns = lineString.split(DELIMITER); <END> rows.add(Arrays.asList(columns)); } } return rows; }</code><technical_language>I thought easy parse a CSV . if : 35, 1456, "mytext", 89000, "other,text", 45 I text encloser " " allow DELIMITER text</technical_language>

Target:
private List<List<String>> readCSVFile(File csvFile) throws IOException { List<List<String>> rows = new ArrayList<>(); try (BufferedReader buffer = new BufferedReader(new FileReader(csvFile))) { String lineString; while ((lineString = buffer.readLine()) != null) { String[] columns = lineString.split(DELIMITER); String[] columnsWithoutAppName = Arrays.copyOfRange(columns,1,columns.length ); rows.add(Arrays.asList(columnsWithoutAppName)); } } return rows; }
Source:
<code>public void render(Graphics g, float x, float y, float width, float height) { g.drawNinePatch(ninePatch, x, y, width, height); <START> g.drawLineSegment(x, 0, x, g.getWindowHeight()); <END> g.drawLineSegment(0, y, g.getWindowWidth(), y); g.drawLineSegment(x + width, 0, x + width, g.getWindowHeight()); g.drawLineSegment(0, y + height, g.getWindowWidth(), y + height); }</code><technical_language>lines here</technical_language>

Target:
public void render(Graphics g, float x, float y, float width, float height) { g.drawNinePatch(ninePatch, x, y, width, height); }
Source:
<code>public void initializeStore() { final File stateDir = TestUtils.tempDirectory(); metrics = new Metrics(); <START> final StreamsMetricsImpl metrics = new StreamsMetricsImpl(KStreamSessionWindowAggregateProcessorTest.this.metrics, "test", StreamsConfig.METRICS_LATEST); <END> context = new InternalMockProcessorContext( stateDir, Serdes.String(), Serdes.String(), metrics, new StreamsConfig(StreamsTestUtils.getStreamsConfig()), NoOpRecordCollector::new, new ThreadCache(new LogContext("testCache "), 100000, metrics) ) { @Override public <K, V> void forward(final K key, final V value, final To to) { toInternal.update(to); results.add(new KeyValueTimestamp<>(key, value, toInternal.timestamp())); } }; initStore(true); processor.init(context); }</code><technical_language>req: please rename StreamsMetricsImpl metrics StreamsMetricsImpl streamsMetrics format code this final StreamsMetricsImpl streamsMetrics = new StreamsMetricsImpl(metrics, "test", StreamsConfig.METRICS_LATEST);</technical_language>

Target:
public void initializeStore() { final File stateDir = TestUtils.tempDirectory(); metrics = new Metrics(); final StreamsMetricsImpl streamsMetrics = new StreamsMetricsImpl(metrics, "test", StreamsConfig.METRICS_LATEST); context = new InternalMockProcessorContext( stateDir, Serdes.String(), Serdes.String(), streamsMetrics, new StreamsConfig(StreamsTestUtils.getStreamsConfig()), NoOpRecordCollector::new, new ThreadCache(new LogContext("testCache "), 100000, streamsMetrics) ) { @Override public <K, V> void forward(final K key, final V value, final To to) { toInternal.update(to); results.add(new KeyValueTimestamp<>(key, value, toInternal.timestamp())); } }; initStore(true); processor.init(context); }
Source:
<code>void submit(Request request) { Object target = request.getTarget(); if (target == null) return; cancelExistingRequest(target, request.uri); targetsToRequests.put(target, request); <START> requestSparseArray.put(request.getTargetRef().hashCode(), request); <END> request.future = service.submit(request); }</code><technical_language>this is sketchy. Hash codes unique</technical_language>

Target:
void submit(Request request) { Object target = request.getTarget(); if (target == null) return; cancelExistingRequest(target, request.uri); targetsToRequests.put(target, request); request.future = service.submit(request); }
Source:
<code>public CaseSensitiveMappedSchemaTableName(String schemaName, String tableName) { <START> if (schemaName == null) { <END> throw new NullPointerException("schemaName is null"); } if (schemaName.isEmpty()) { throw new IllegalArgumentException("schemaName is empty"); } this.schemaName = schemaName; this.schemaNameLower = schemaName.toLowerCase(ENGLISH); if (tableName == null) { throw new NullPointerException("tableName is null"); } if (tableName.isEmpty()) { throw new IllegalArgumentException("tableName is empty"); } this.tableName = tableName; this.tableNameLower = tableName.toLowerCase(ENGLISH); }</code><technical_language>Presto do this appears requireNonNull(schemaName, "schemaName is null");</technical_language>

Target:
public CaseSensitiveMappedSchemaTableName(String schemaName, String tableName) { this.schemaName = requireNonNull(schemaName, "schemaName is null"); if (schemaName.isEmpty()) { throw new IllegalArgumentException("schemaName is empty"); } this.schemaNameLower = schemaName.toLowerCase(ENGLISH); this.tableName = requireNonNull(tableName, "tableName is null"); if (tableName.isEmpty()) { throw new IllegalArgumentException("tableName is empty"); } this.tableNameLower = tableName.toLowerCase(ENGLISH); }
Source:
<code>public List<DataSample> getData() { <START> return data; <END> }</code><technical_language>Add "this" qualifier</technical_language>

Target:
public List<DataSample> getData() { return this.data; }
Source:
<code>private boolean flowControl(int size) { boolean flowWorked = replicatingChannel.getConnection().blockUntilWritable(size, timeout); if (!flowWorked) { try { ActiveMQServerLogger.LOGGER.slowReplicationResponse(); stop(); } catch (Exception e) { <START> ActiveMQServerLogger.LOGGER.failedToStopReplicationServer(e); <END> } } return flowWorked; }</code><technical_language>I log warn.. need for special logger</technical_language>

Target:
private boolean flowControl(int size) { boolean flowWorked = replicatingChannel.getConnection().blockUntilWritable(size, timeout); if (!flowWorked) { try { ActiveMQServerLogger.LOGGER.slowReplicationResponse(); stop(); } catch (Exception e) { logger.warn(e.getMessage(), e); } } return flowWorked; }
Source:
<code>static <E, T> Validation<E, T> invalid(E error) { <START> Objects.requireNonNull(error, "errors is null"); <END> return new Invalid<>(error); }</code><technical_language>dito - search/replaceAll ;)</technical_language>

Target:
static <E, T> Validation<E, T> invalid(E error) { Objects.requireNonNull(error, "error is null"); return new Invalid<>(error); }
Source:
<code>private String getApplicationLabel(ComponentName componentName) { final PackageManager pm = getPackageManager(); ApplicationInfo info = null; try { <START> info = pm.getApplicationInfo(componentName.getPackageName(), 0); <END> } catch (PackageManager.NameNotFoundException e) { Log.w(TAG, "Application info not found for packageName " + componentName .getPackageName()); } if (info == null) { return componentName.getPackageName(); } else { return info.loadLabel(pm).toString(); } }</code><technical_language>able do: ApplicationInfo info = pm.getApplicationInfo(packageName, 0); return pm.getApplicationLabel(info);</technical_language>

Target:
private String getApplicationLabel(ComponentName componentName) { final PackageManager pm = getPackageManager(); try { ApplicationInfo info = pm.getApplicationInfo(componentName.getPackageName(), 0); return pm.getApplicationLabel(info).toString(); } catch (PackageManager.NameNotFoundException e) { Log.w(TAG, "Application info not found for packageName " + componentName .getPackageName()); } return componentName.getPackageName(); }
Source:
<code>protected Node visitShowTables(ShowTables showTables, Void context) { CatalogSchemaName schema = createCatalogSchemaName(session, showTables, showTables.getSchema()); accessControl.checkCanShowTablesMetadata(session.getRequiredTransactionId(), session.getIdentity(), schema); if (!metadata.catalogExists(session, schema.getCatalogName())) { <START> throw new SemanticException(MISSING_SCHEMA, showTables, "Catalog '%s' does not exist", schema.getCatalogName()); <END> } if (!metadata.schemaExists(session, schema)) { throw new SemanticException(MISSING_SCHEMA, showTables, "Schema '%s' does not exist", schema.getSchemaName()); } Expression predicate = equal(identifier("table_schema"), new StringLiteral(schema.getSchemaName())); Optional<String> likePattern = showTables.getLikePattern(); if (likePattern.isPresent()) { Expression likePredicate = new LikePredicate(identifier("table_name"), new StringLiteral(likePattern.get()), null); predicate = logicalAnd(predicate, likePredicate); } return simpleQuery( selectList(aliasedName("table_name", "Table")), from(schema.getCatalogName(), TABLE_TABLES), predicate, ordering(ascending("table_name"))); }</code><technical_language>This MISSING_CATALOG, is causing test fail</technical_language>

Target:
protected Node visitShowTables(ShowTables showTables, Void context) { CatalogSchemaName schema = createCatalogSchemaName(session, showTables, showTables.getSchema()); accessControl.checkCanShowTablesMetadata(session.getRequiredTransactionId(), session.getIdentity(), schema); if (!metadata.catalogExists(session, schema.getCatalogName())) { throw new SemanticException(MISSING_CATALOG, showTables, "Catalog '%s' does not exist", schema.getCatalogName()); } if (!metadata.schemaExists(session, schema)) { throw new SemanticException(MISSING_SCHEMA, showTables, "Schema '%s' does not exist", schema.getSchemaName()); } Expression predicate = equal(identifier("table_schema"), new StringLiteral(schema.getSchemaName())); Optional<String> likePattern = showTables.getLikePattern(); if (likePattern.isPresent()) { Expression likePredicate = new LikePredicate(identifier("table_name"), new StringLiteral(likePattern.get()), null); predicate = logicalAnd(predicate, likePredicate); } return simpleQuery( selectList(aliasedName("table_name", "Table")), from(schema.getCatalogName(), TABLE_TABLES), predicate, ordering(ascending("table_name"))); }
Source:
<code>public ClientCnxn( String chrootPath, HostProvider hostProvider, int sessionTimeout, ZKClientConfig clientConfig, Watcher defaultWatcher, ClientCnxnSocket clientCnxnSocket, boolean canBeReadOnly ) { this( chrootPath, hostProvider, sessionTimeout, clientConfig, <START> defaultWatcher, <END> clientCnxnSocket, 0, new byte[16], canBeReadOnly); }</code><technical_language>this is major concern. is true changing high level API, ClientCnxn is internal class applications directly. is probable frameworks Curator (ping @Randgalt ) do tricks this stuff. This change is a big refactor touches internals of client handle care. get wrong, I this work is awesome I hope land master someday. opinion, if other reviewer wants sponsor this change</technical_language>

Target:
public ClientCnxn( String chrootPath, HostProvider hostProvider, int sessionTimeout, ZKClientConfig clientConfig, Watcher defaultWatcher, ClientCnxnSocket clientCnxnSocket, boolean canBeReadOnly ) throws IOException { this( chrootPath, hostProvider, sessionTimeout, clientConfig, defaultWatcher, clientCnxnSocket, 0, new byte[16], canBeReadOnly); }
Source:
<code>private String getColumnContent(Card c, String key){ switch (key){ case "lapses": return Integer.toString(c.getLapses()); case "note": return c.model().optString("name"); case "question": return formatQA(c.q()); case "reviews": return Integer.toString(c.getReps()); case "answer": Map<String, String> qa = c._getQA(true, true); String q = qa.get("q"); String a = qa.get("a"); if (a.startsWith(q)) { a = a.replaceFirst(Pattern.quote(q), ""); } return formatQA(c.a()); case "tags": return c.note().stringTags(); <START> case "sfld": <END> return c.note().getSFld(); case "deck": try { return getCol().getDecks().get(c.getDid()).getString("name"); } catch (JSONException e) { throw new RuntimeException(e); } case "flags": return new Integer(c.getUserFlag()).toString(); case "id": return new Long(c.getId()).toString(); case "interval": int type = c.getType(); if (type == 0) { return getBaseContext().getString(R.string.card_browser_interval_new_card); } else if (type == 1) { return getBaseContext().getString(R.string.card_browser_interval_learning_card); } else { return Utils.timeSpan(getBaseContext(), c.getIvl()*86400); } case "card": return c.template().optString("name"); default: return ""; } }</code><technical_language>Please add braces create a scope defining new variables case</technical_language>

Target:
private String getColumnContent(Card c, String key){ c.loadIfRequired(); switch (key){ case "lapses": return Integer.toString(c.getLapses()); case "note": return c.model().optString("name"); case "question": return formatQA(c.q()); case "reviews": return Integer.toString(c.getReps()); case "answer": { Map<String, String> qa = c._getQA(true, true); String q = qa.get("q"); String a = qa.get("a"); if (a.startsWith(q)) { a = a.replaceFirst(Pattern.quote(q), ""); } return formatQA(c.a()); } case "tags": return c.note().stringTags(); case "sfld": return c.note().getSFld(); case "deck": try { return getCol().getDecks().get(c.getDid()).getString("name"); } catch (JSONException e) { throw new RuntimeException(e); } case "flags": return new Integer(c.getUserFlag()).toString(); case "id": return new Long(c.getId()).toString(); case "interval": { int type = c.getType(); if (type == 0) { return getBaseContext().getString(R.string.card_browser_interval_new_card); } else if (type == 1) { return getBaseContext().getString(R.string.card_browser_interval_learning_card); } else { return Utils.timeSpan(getBaseContext(), c.getIvl()*86400); } } case "card": return c.template().optString("name"); default: return ""; } }
Source:
<code>private RunResult invokeAllTests(TestsToRun testsToRun) { RunResult runResult; ReporterFactory reporterFactory = parameters.getReporterFactory(); try { RunListener runListener = reporterFactory.createReporter(); <START> ConsoleOutputCapture.startCapture((ConsoleOutputReceiver) runListener); <END> launcher.registerTestExecutionListeners(new RunListenerAdapter(runListener)); for (Class<?> testClass : testsToRun) { invokeSingleClass(testClass, runListener); } } finally { runResult = reporterFactory.close(); } return runResult; }</code><technical_language>startCapture() calls System.setOut() System.setErr() tests reset test run. try org.apache.maven.surefire.booter.ProviderFactory.invoke() instead of calling invoke() implementation directly</technical_language>

Target:
private RunResult invokeAllTests(TestsToRun testsToRun) { RunResult runResult; ReporterFactory reporterFactory = parameters.getReporterFactory(); try { RunListener runListener = reporterFactory.createReporter(); ConsoleOutputCapture.startCapture((ConsoleOutputReceiver) runListener); for (Class<?> testClass : testsToRun) { invokeSingleClass(testClass, runListener); } } finally { runResult = reporterFactory.close(); } return runResult; }
Source:
<code>public static void main(String[] args) throws Exception { try { SpringApplication.run(ModuleLauncherApplication.class, args); <START> } catch (Exception e) { <END> log.error("Couldn't launch module: ", e); } }</code><technical_language>a new line closing curly brace ;)</technical_language>

Target:
public static void main(String[] args) throws Exception { try { SpringApplication.run(ModuleLauncherApplication.class, args); } catch (Exception e) { log.error("Failed to launch module ", e); } }
Source:
<code><START> public void onDebugLogToggle() { Level logLevel = Level.DEBUG; final LoggerContext loggerContext = ((Logger) LoggerFactory.getLogger(MethodHandles.lookup().lookupClass())).getLoggerContext(); loggerContext.getLoggerList() .stream() .filter(logger -> logger.getName().startsWith("com.faforever")) .forEach(logger -> ((Logger) LoggerFactory.getLogger(logger.getName())).setLevel(logLevel)); log.info("Switching FA Forever logging configuration to {}", logLevel.levelStr); } <END></code><technical_language>Business logic in a service</technical_language>

Target:
public void onDebugLogToggle() { preferencesService.startDebugLogging(); }
Source:
<code>public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } <START> if (getClass() != obj.getClass()) { <END> return false; } VmGuestAgentInterface other = (VmGuestAgentInterface) obj; if (getInterfaceName() == null) { if (other.getInterfaceName() != null) { return false; } } else if (!getInterfaceName().equals(other.getInterfaceName())) { return false; } if (getIpv4Addresses() == null) { if (other.getIpv4Addresses() != null) { return false; } } else if (!getIpv4Addresses().equals(other.getIpv4Addresses())) { return false; } if (getIpv6Addresses() == null) { if (other.getIpv6Addresses() != null) { return false; } } else if (!getIpv6Addresses().equals(other.getIpv6Addresses())) { return false; } if (getMacAddress() == null) { if (other.getMacAddress() != null) { return false; } } else if (!getMacAddress().equals(other.getMacAddress())) { return false; } if (getVmId() == null) { if (other.getVmId() != null) { return false; } } else if (!getVmId().equals(other.getVmId())) { return false; } return true; }</code><technical_language>instanceof more suitable</technical_language>

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof VmGuestAgentInterface)) { return false; } VmGuestAgentInterface other = (VmGuestAgentInterface) obj; if (getInterfaceName() == null) { if (other.getInterfaceName() != null) { return false; } } else if (!getInterfaceName().equals(other.getInterfaceName())) { return false; } if (getIpv4Addresses() == null) { if (other.getIpv4Addresses() != null) { return false; } } else if (!getIpv4Addresses().equals(other.getIpv4Addresses())) { return false; } if (getIpv6Addresses() == null) { if (other.getIpv6Addresses() != null) { return false; } } else if (!getIpv6Addresses().equals(other.getIpv6Addresses())) { return false; } if (getMacAddress() == null) { if (other.getMacAddress() != null) { return false; } } else if (!getMacAddress().equals(other.getMacAddress())) { return false; } if (getVmId() == null) { if (other.getVmId() != null) { return false; } } else if (!getVmId().equals(other.getVmId())) { return false; } return true; }
Source:
<code>public void setLicenses(LicenseConfiguration[] licenses) { <START> this.licenses = licenses; <END> }</code><technical_language>This is checking if is license, in getLicenseName() method below. validation occur set, get (because late)</technical_language>

Target:
public void setLicenses(LicenseConfiguration[] licenses) throws IOException { if (!ArrayUtils.isEmpty(licenses)) { if (licenses.length > 1) { throw new IOException("PyPi doesn't support multiple licenses!"); } } this.licenses = licenses; }
Source:
<code>public void delete() throws IOException { File rootDir = getRootDir(); if (!rootDir.isDirectory()) { LOGGER.warning(String.format( "%s: %s looks to have already been deleted, assuming build dir was already cleaned up", this, rootDir )); RunListener.fireDeleted(this); synchronized (this) { removeRunFromParent(); } return; } RunListener.fireDeleted(this); if (artifactManager != null) { deleteArtifacts(); } synchronized (this) { File tmp = new File(rootDir.getParentFile(),'.'+rootDir.getName()); if (tmp.exists()) { Util.deleteRecursive(tmp); } boolean renamingSucceeded = true; try { <START> Path path = Files.move(rootDir.toPath(), tmp.toPath(), StandardCopyOption.ATOMIC_MOVE); <END> } catch (UnsupportedOperationException | IOException | SecurityException ex) { renamingSucceeded = rootDir.renameTo(tmp); } Util.deleteRecursive(tmp); if (tmp.exists()) { tmp.deleteOnExit(); } if (!renamingSucceeded) { throw new IOException(rootDir + " is in use"); } LOGGER.log(FINE, "{0}: {1} successfully deleted", new Object[] {this, rootDir}); removeRunFromParent(); } }</code><technical_language>InvalidPathException is handled here. I recommend Util#fileToPath() instead. <LINK_0> suggestion Path path = Files.move(rootDir.toPath(), Util.fileToPath(), StandardCopyOption.ATOMIC_MOVE);</technical_language>

Target:
public void delete() throws IOException { File rootDir = getRootDir(); if (!rootDir.isDirectory()) { LOGGER.warning(String.format( "%s: %s looks to have already been deleted, assuming build dir was already cleaned up", this, rootDir )); RunListener.fireDeleted(this); synchronized (this) { removeRunFromParent(); } return; } RunListener.fireDeleted(this); if (artifactManager != null) { deleteArtifacts(); } synchronized (this) { File tmp = new File(rootDir.getParentFile(),'.'+rootDir.getName()); if (tmp.exists()) { Util.deleteRecursive(tmp); } try { Files.move( Util.fileToPath(rootDir), Util.fileToPath(tmp), StandardCopyOption.ATOMIC_MOVE ); } catch (UnsupportedOperationException | SecurityException ex) { throw new IOException(rootDir + " is in use"); } Util.deleteRecursive(tmp); if (tmp.exists()) { tmp.deleteOnExit(); } LOGGER.log(FINE, "{0}: {1} successfully deleted", new Object[] {this, rootDir}); removeRunFromParent(); } }
Source:
<code>public List<RepositoryVO> getRepositoryVOList(Database db) throws ConstraintException, SystemException, Bug { String key = "repositoryVOList"; logger.info("key:" + key); List<RepositoryVO> cachedRepositoryVOList = (List<RepositoryVO>)CacheController.getCachedObject("repositoryCache", key); if(cachedRepositoryVOList != null) { logger.info("There was an cached repo list:" + cachedRepositoryVOList.size()); return cachedRepositoryVOList; } List<RepositoryVO> repositoryVOList = new ArrayList<RepositoryVO>(); String SQL = "SELECT r.repositoryId, r.name, r.description, r.dnsName, r.isDeleted from cmRepository r order by r.repositoryId"; logger.info("SQL:" + SQL); try { Connection conn = (Connection) db.getJdbcConnection(); PreparedStatement psmt = conn.prepareStatement(SQL.toString()); ResultSet rs = psmt.executeQuery(); while(rs.next()) { RepositoryVO repoVO = new RepositoryVO(); repoVO.setRepositoryId(new Integer(rs.getString(1))); repoVO.setName(rs.getString(2)); repoVO.setDescription(rs.getString(3)); repoVO.setDnsName(rs.getString(4)); repoVO.setIsDeleted(rs.getBoolean(5)); logger.info("Found:" + repoVO); repositoryVOList.add(repoVO); } <START> rs.close(); <END> psmt.close(); } catch(Exception e) { logger.error("Problem getting repo list: " + e.getMessage(), e); } CacheController.cacheObject("repositoryCache", key, repositoryVOList); return repositoryVOList; }</code><technical_language>close calls executed if exception is thrown. in a finally clause instead</technical_language>

Target:
public List<RepositoryVO> getRepositoryVOList(Database db) throws ConstraintException, SystemException, Bug { String key = "repositoryVOList"; logger.info("key:" + key); List<RepositoryVO> cachedRepositoryVOList = (List<RepositoryVO>)CacheController.getCachedObject("repositoryCache", key); if(cachedRepositoryVOList != null) { logger.info("There was an cached repo list:" + cachedRepositoryVOList.size()); return cachedRepositoryVOList; } List<RepositoryVO> repositoryVOList = new ArrayList<RepositoryVO>(); String SQL = "SELECT r.repositoryId, r.name, r.description, r.dnsName, r.isDeleted from cmRepository r order by r.repositoryId"; logger.info("SQL:" + SQL); PreparedStatement psmt = null; ResultSet rs = null; try { Connection conn = (Connection) db.getJdbcConnection(); psmt = conn.prepareStatement(SQL.toString()); rs = psmt.executeQuery(); while(rs.next()) { RepositoryVO repoVO = new RepositoryVO(); repoVO.setRepositoryId(new Integer(rs.getString(1))); repoVO.setName(rs.getString(2)); repoVO.setDescription(rs.getString(3)); repoVO.setDnsName(rs.getString(4)); repoVO.setIsDeleted(rs.getBoolean(5)); logger.info("Found:" + repoVO); repositoryVOList.add(repoVO); } CacheController.cacheObject("repositoryCache", key, repositoryVOList); } catch(Exception e) { logger.error("Problem getting repo list: " + e.getMessage(), e); } finally { try { rs.close(); psmt.close(); } catch(Exception e) { logger.error("Problem getting repo list: " + e.getMessage(), e); } } return repositoryVOList; }
Source:
<code>public synchronized List<LookupBean> pullExistingSnapshot() { List<LookupBean> lookupBeanList; try { if (!persistFile.isFile()) { LOGGER.warn("could not find any snapshot file under working directory [%s]", persistDirectory); return Collections.emptyList(); } else if( persistFile.length() == 0){ LOGGER.warn("found empty file no lookups to load from [%s]", persistFile.getAbsolutePath()); return Collections.emptyList(); } <START> lookupBeanList = objectMapper.reader(new TypeReference<List<LookupBean>>() <END> { }).readValue(persistFile); return lookupBeanList; } catch (IOException e) { throw new ISE(e, "Exception during reading lookups from [%s]", persistFile.getAbsolutePath()); } }</code><technical_language>places in druid objectMapper.readValue(persistFile, new TypeReference<List<LookupBean>>(){})</technical_language>

Target:
public synchronized List<LookupBean> pullExistingSnapshot() { List<LookupBean> lookupBeanList; try { if (!persistFile.isFile()) { LOGGER.warn("could not find any snapshot file under working directory [%s]", persistDirectory); return Collections.emptyList(); } else if( persistFile.length() == 0){ LOGGER.warn("found empty file no lookups to load from [%s]", persistFile.getAbsolutePath()); return Collections.emptyList(); } lookupBeanList = objectMapper.readValue(persistFile, new TypeReference<List<LookupBean>>(){}); return lookupBeanList; } catch (IOException e) { throw new ISE(e, "Exception during reading lookups from [%s]", persistFile.getAbsolutePath()); } }
Source:
<code>public NewExternalSubnetModel(NetworkView network, SearchableListModel sourceModel) { this.sourceModel = sourceModel; setName(new EntityModel<String>()); setCidr(new EntityModel<String>()); setNetwork(new ListModel<NetworkView>()); setIpVersion(new ListModel<IpVersion>()); getIpVersion().setItems(AsyncDataProvider.getExternalSubnetIpVerionList()); getNetwork().setItems(Arrays.asList(network)); getNetwork().setSelectedItem(network); <START> getNetwork().setIsChangable(false); <END> setHashName("new_external_subnet"); initCommands(); }</code><technical_language>If widget is turned a label member EntityModel, lines replaced setEntity()</technical_language>

Target:
public NewExternalSubnetModel(NetworkView network, SearchableListModel sourceModel) { this.sourceModel = sourceModel; setName(new EntityModel<String>()); setCidr(new EntityModel<String>()); setNetwork(new ListModel<NetworkView>()); setIpVersion(new ListModel<IpVersion>()); getIpVersion().setItems(AsyncDataProvider.getExternalSubnetIpVerionList()); getNetwork().setEntity(network); setTitle(ConstantsManager.getInstance().getConstants().newExternalSubnetTitle()); setHashName("new_external_subnet"); initCommands(); }
Source:
<code>public void loadKeyOpenSSH() throws IOException, GeneralSecurityException { File file = new File(this.getClass().getResource("openssh").getFile()); <START> assertkeyPair(file, null); <END> }</code><technical_language>suggestion assertKeyPair(file, null);</technical_language>

Target:
public void loadKeyOpenSSH() throws IOException, GeneralSecurityException { File file = new File(this.getClass().getResource("openssh").getFile()); assertKeyPairNotNull(file, null); }
Source:
<code>private void testUiConsistencyForNewQuestion() { ______TS("CONSTSUM-option after CONSTSUM-recipient: Check ui consistency success case"); feedbackEditPage.clickNewQuestionButton(); feedbackEditPage.selectNewQuestionType("CONSTSUM_RECIPIENT"); feedbackEditPage.clickDiscardChangesLinkForNewQuestion(); feedbackEditPage.waitForConfirmationModalAndClickOk(); feedbackEditPage.clickNewQuestionButton(); feedbackEditPage.selectNewQuestionType("CONSTSUM_OPTION"); assertTrue(feedbackEditPage.isElementVisible(By.id("constSumPoints--1"))); <START> assertTrue(feedbackEditPage.isElementVisible(By.id("constSumPointsForEachOption--1"))); <END> assertFalse(feedbackEditPage.isElementVisible(By.id("constSumOption_Recipient--1"))); feedbackEditPage.clickDiscardChangesLinkForNewQuestion(); feedbackEditPage.waitForConfirmationModalAndClickOk(); }</code><technical_language>main bug element of id constSumOption_Option--1 is hidden **must** assertion check for that. add important assertion check, is if constSumOption_Option--1 is visible not</technical_language>

Target:
private void testUiConsistencyForNewQuestion() { ______TS("CONSTSUM-option after CONSTSUM-recipient: Check ui consistency success case"); feedbackEditPage.clickNewQuestionButton(); feedbackEditPage.selectNewQuestionType("CONSTSUM_RECIPIENT"); feedbackEditPage.clickDiscardChangesLinkForNewQuestion(); feedbackEditPage.waitForConfirmationModalAndClickOk(); feedbackEditPage.clickNewQuestionButton(); feedbackEditPage.selectNewQuestionType("CONSTSUM_OPTION"); assertTrue(feedbackEditPage.isElementVisible(By.id("constSumPointsTotal--1"))); assertTrue(feedbackEditPage.isElementVisible(By.id("constSumOption_Option--1"))); assertFalse(feedbackEditPage.isElementVisible(By.id("constSumOption_Recipient--1"))); feedbackEditPage.clickDiscardChangesLinkForNewQuestion(); feedbackEditPage.waitForConfirmationModalAndClickOk(); }
Source:
<code><START> protected boolean hasChanges() { <END> return hasChanges; }</code><technical_language>this protected? override if is public</technical_language>

Target:
public boolean hasChanges() { return hasChanges; }
Source:
<code><START> public long length() { <END> return length; }</code><technical_language>@Override this line</technical_language>

Target:
@Override public long length() { return length; }
Source:
<code>public void remove(String regName) { MetricRegistry mreg = registries.remove(regName); if (mreg != null) notifyListeners(mreg, metricRegRemoveLsnrs, log); metaLock.writeLock().lock(); try { for (Metric m : mreg) { if (m instanceof HitRateMetric) <START> metastorage.remove(metricName(HITRATE_CFG_PREFIX, m.name())); <END> else if (m instanceof HistogramMetric) metastorage.remove(metricName(HISTOGRAM_CFG_PREFIX, m.name())); } } catch (IgniteCheckedException e) { throw new IgniteException(e); } finally { metaLock.writeLock().unlock(); } }</code><technical_language>I suggest adding "removeAsync" API wait for future here, this speed this method</technical_language>

Target:
public void remove(String regName) { MetricRegistry mreg = registries.remove(regName); if (mreg == null) return; notifyListeners(mreg, metricRegRemoveLsnrs, log); try { GridCompoundFuture opsFut = new GridCompoundFuture<>(); for (Metric m : mreg) { if (m instanceof HitRateMetric) opsFut.add(metastorage.removeAsync(metricName(HITRATE_CFG_PREFIX, m.name()))); else if (m instanceof HistogramMetric) opsFut.add(metastorage.removeAsync(metricName(HISTOGRAM_CFG_PREFIX, m.name()))); } opsFut.markInitialized(); opsFut.get(); } catch (IgniteCheckedException e) { throw new IgniteException(e); } }
Source:
<code><START> public SocketAddress localAddress() { <END> SocketAddress address = localAddress; if (address == null) { java.net.SocketAddress addr = chctx.channel().hasAttr(LOCAL_ADDRESS_OVERRIDE) ? chctx.channel().attr(LOCAL_ADDRESS_OVERRIDE).getAndSet(null) : chctx.channel().localAddress(); if (addr != null) { address = vertx.transport().convert(addr); localAddress = address; } } return address; }</code><technical_language>yes, I forgot this</technical_language>

Target:
public SocketAddress localAddress() { SocketAddress address = localAddress; if (address == null) { if (chctx.channel().hasAttr(LOCAL_ADDRESS_OVERRIDE)) { address = chctx.channel().attr(LOCAL_ADDRESS_OVERRIDE).getAndSet(null); } else { java.net.SocketAddress addr = chctx.channel().localAddress(); if (addr != null) { address = vertx.transport().convert(addr); } } if (address != null) localAddress = address; } return address; }
Source:
<code>public PostMessageField(String title, String value) { this.title = title; <START> this.value = value; <END> }</code><technical_language>In this case isShortwill a default of false - I assume is OK? a common pattern for multiple constructors is call "full" passing in defaults for missing values: PostMessageField(String title, String value) { self(title, value, false) }</technical_language>

Target:
public PostMessageField(String title, String value) { this(title, value, false); }
Source:
<code>public void onPartitionsAssigned(Collection<TopicPartition> partitions) { _consumerMetrics.updateRebalanceRate(1); _logger.info("Partition ownership assigned for {}.", partitions); <START> _consumerAssignment = Sets.newHashSet(partitions); <END> _taskUpdates.add(DatastreamConstants.UpdateType.PAUSE_RESUME_PARTITIONS); }</code><technical_language>Is this method called partition is removed assignment? If not, need changes in partitionRevoked method too</technical_language>

Target:
public void onPartitionsAssigned(Collection<TopicPartition> partitions) { _consumerMetrics.updateRebalanceRate(1); _logger.info("Partition ownership assigned for {}.", partitions); _consumerAssignment = Sets.newHashSet(partitions); _logger.info("Current assignment is {}", _consumerAssignment); _taskUpdates.add(DatastreamConstants.UpdateType.PAUSE_RESUME_PARTITIONS); }
Source:
<code>@Override public V remove(int key) { lock.writeLock().lock(); try { <START> if (entries.length != INITIAL_CAPACITY && (int)(COMPACT_LOAD_FACTOR * (entries.length >> 1)) > size) <END> resize(false); int idx = find(key); if (idx < 0) return null; size--; V tmp = entries[idx].val; for (int i = 0; i < entries.length; i++) { int curIdx = (idx + i) & (entries.length - 1); int nextIdx = (idx + i + 1) & (entries.length - 1); Entry<V> nextEntry = entries[nextIdx]; if (nextEntry == null || distance(nextIdx, nextEntry.key) == 0) { entries[curIdx] = null; return tmp; } entries[curIdx] = entries[nextIdx]; } throw new IllegalStateException("Unreachable state exception. Backward shift has a problem. " + "Removing key: " + key + " map state: " + toString()); } finally { lock.writeLock().unlock(); } }</code><technical_language>I sounds picky please store calculated threshold in fields (like regular HashMap does)</technical_language>

Target:
@Override public V remove(int key) { if (entries.length != INITIAL_CAPACITY && compactThreshold > size) resize(false); int idx = find(key); if (idx < 0) return null; size--; V tmp = entries[idx].val; for (int i = 0; i < entries.length; i++) { int curIdx = (idx + i) & (entries.length - 1); int nextIdx = (idx + i + 1) & (entries.length - 1); Entry<V> nextEntry = entries[nextIdx]; if (nextEntry == null || distance(nextIdx, nextEntry.key) == 0) { entries[curIdx] = null; return tmp; } entries[curIdx] = nextEntry; } throw new IllegalStateException("Unreachable state exception. Backward shift has a problem. " + "Removing key: " + key + " map state: " + toString()); }
Source:
<code>private String generateDeclarations(List<SourceFile> sourceFiles, List<SourceFile> externs) throws AssertionError { Compiler compiler = new Compiler(); compiler.disableThreads(); CompilerOptions compilerOptions = opts.getCompilerOptions(); compiler.setPassConfig(new DefaultPassConfig(compilerOptions)); compiler.setErrorManager(new BasicErrorManager() { @Override public void println(CheckLevel level, JSError error) @Override protected void printSummary() }); if (externs.isEmpty()) { <START> externs = opts.skipParseExterns ? Collections.<SourceFile>emptyList() : getDefaultExterns(); <END> } Result compilationResult = compiler.compile(externs, sourceFiles, compilerOptions); if (compiler.hasErrors()) { throw new AssertionError("Compile failed: " + Arrays.toString(compilationResult.errors)); } return produceDts(compiler); }</code><technical_language>throw if externs explicitly passed skipParseExterns is true (or set all)</technical_language>

Target:
private String generateDeclarations(List<SourceFile> sourceFiles, List<SourceFile> externs) throws AssertionError { Compiler compiler = new Compiler(); compiler.disableThreads(); CompilerOptions compilerOptions = opts.getCompilerOptions(); compiler.setPassConfig(new DefaultPassConfig(compilerOptions)); compiler.setErrorManager(new BasicErrorManager() { @Override public void println(CheckLevel level, JSError error) @Override protected void printSummary() }); if (externs.isEmpty()) { externs = opts.skipParseExterns ? Collections.<SourceFile>emptyList() : getDefaultExterns(); } else { Preconditions.checkArgument(!opts.skipParseExterns); } Result compilationResult = compiler.compile(externs, sourceFiles, compilerOptions); if (compiler.hasErrors()) { throw new AssertionError("Compile failed: " + Arrays.toString(compilationResult.errors)); } return produceDts(compiler); }
Source:
<code>public SmartImportRootWizardPage(SmartImportWizard wizard, File initialSelection, Set<IWorkingSet> initialWorkingSets) { super(SmartImportRootWizardPage.class.getName()); <START> this.potentialProjects = Collections.emptyMap(); <END> this.selection = initialSelection; this.workingSets = initialWorkingSets; if (this.workingSets == null) { this.workingSets = new HashSet<>(); } setWizard(wizard); }</code><technical_language>general initialization field declaration, lost adding another constructor</technical_language>

Target:
public SmartImportRootWizardPage(SmartImportWizard wizard, File initialSelection, Set<IWorkingSet> initialWorkingSets) { super(SmartImportRootWizardPage.class.getName()); this.selection = initialSelection; this.workingSets = initialWorkingSets; if (this.workingSets == null) { this.workingSets = new HashSet<>(); } setWizard(wizard); }
Source:
<code>protected void addField(String fieldName, String value) { <START> output.append("\"").append(value).append("\","); <END> }</code><technical_language>I suggest org.apache.commons.lang.StringEscapeUtils.escapeCSV() here</technical_language>

Target:
protected void addField(String fieldName, String value) { output .append(StringEscapeUtils.escapeCsv(value)) .append(","); }