auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void stop() { if (System.getenv("ZEPPELIN_FORCE_STOP") != null) { if (isRunning()) { logger.info("Kill interpreter process of interpreter group: " + interpreterGroupId); try { callRemoteFunction(new RemoteFunction<Void>() { @Override public Void call(RemoteInterpreterService.Client client) throws Exception { client.shutdown(); return null; } }); } catch (Exception e) { logger.warn("ignore the exception when shutting down interpreter process.", e); } shutdown(); <START> logger.info("Remote process of interpreter group: " + getInterpreterGroupId() + " is terminated"); <END> } } }</code><technical_language>please logger 'public static final' avoid creation of objects if logger is disabled for INFO level ( LOGGER.info(String format, Object... arguments);)</technical_language>

Target:
public void stop() { if (System.getenv("ZEPPELIN_FORCE_STOP") != null) { if (isRunning()) { LOGGER.info("Kill interpreter process of interpreter group: {}", interpreterGroupId); try { callRemoteFunction(new RemoteFunction<Void>() { @Override public Void call(RemoteInterpreterService.Client client) throws Exception { client.shutdown(); return null; } }); } catch (Exception e) { LOGGER.warn("ignore the exception when shutting down interpreter process.", e); } shutdown(); LOGGER.info("Remote process of interpreter group: is terminated.", getInterpreterGroupId()); } } }
Source:
<code>private Optional<String> readFromProjectRoot(final String filePath) { try { final File f = new File(filePath); <START> final List<String> lines = IOUtils.readLines(new FileInputStream(f), Charsets.UTF_8); <END> return Optional.of(String.join("\n", lines)); } catch (final IOException e) { return Optional.empty(); } }</code><technical_language>suggestion final List<String> lines = Files.readAllLines(Paths.get(filePath), StandardCharsets.UTF_8);</technical_language>

Target:
private Optional<String> readFromProjectRoot(final String filePath) { try { final List<String> lines = Files.readAllLines(Paths.get(filePath), StandardCharsets.UTF_8); return Optional.of(String.join("\n", lines)); } catch (final IOException e) { return Optional.empty(); } }
Source:
<code>public void deleteWorkflowRequest(String workflowExtRef) throws APIManagementException { Connection connection = null; PreparedStatement prepStmt = null; String query = SQLConstants.DELETE_WORKFLOW_REQUEST_SQL; <START> try { connection = APIMgtDBUtil.getConnection(); connection.setAutoCommit(false); prepStmt = connection.prepareStatement(query); prepStmt.setString(1, workflowExtRef); prepStmt.executeUpdate(); connection.commit(); } catch (SQLException e) { handleException("Failed to delete the workflow request. ", e); } finally { APIMgtDBUtil.closeAllConnections(prepStmt, connection, null); } <END> }</code><technical_language>"try resources" possible. do functionality amount of code</technical_language>

Target:
public void deleteWorkflowRequest(String workflowExtRef) throws APIManagementException { String query = SQLConstants.DELETE_WORKFLOW_REQUEST_SQL; try (Connection connection = APIMgtDBUtil.getConnection(); PreparedStatement prepStmt = connection.prepareStatement(query)) { try { connection.setAutoCommit(false); prepStmt.setString(1, workflowExtRef); prepStmt.executeUpdate(); connection.commit(); } catch (SQLException e) { handleException("Failed to delete the workflow request. ", e); } finally { APIMgtDBUtil.closeAllConnections(prepStmt, connection, null); } } catch (SQLException e) { handleException("Failed to delete the workflow request. ", e); } }
Source:
<code><START> public boolean isEntitySetReady() { <END> return true; }</code><technical_language>"Called a call prepareEntities" worth adding a flag enforce this; guessing this unpleasant debug if manipulate entities ready</technical_language>

Target:
public final boolean isEntitySetReady() { synchronized(mPreparationLock) { if(!mEntitySetInitialized) { throw new RuntimeException("A Node Entity Factory was not prepared before usage. prepareEntities() must be called before a call to isEntitySetReady()"); } return isEntitySetReadyInternal(); } }
Source:
<code>private boolean match(final MethodNode methodNode, final String superClassName) { <START> firstIsLoadThis(methodNode); <END> nextIs(Opcodes.ALOAD); nextIs(Opcodes.ILOAD); nextIsInvokeSuper(superClassName, CONSTRUCTOR_DESC); nextIs(Opcodes.RETURN); return cursor != null; }</code><technical_language>+1 for this readable reader declaration ;)</technical_language>

Target:
private boolean match(final MethodNode methodNode, final String superClassName) { firstIsALoad0(methodNode); nextIs(Opcodes.ALOAD); nextIs(Opcodes.ILOAD); nextIsInvokeSuper(superClassName, CONSTRUCTOR_DESC); nextIs(Opcodes.RETURN); return cursor != null; }
Source:
<code>public void waitForInitialRemoteData_throwsOnTimeout() { <START> RealmLog.setLevel(LogLevel.DEBUG); <END> SyncUser user = UserFactory.createUniqueUser(Constants.AUTH_URL); SyncConfiguration syncConfiguration = configFactory .createSyncConfigurationBuilder(user, Constants.SYNC_SERVER_URL) .initialData(bgRealm -> { for (int i = 0; i < 100; i++) { bgRealm.createObject(AllTypes.class); } }) .waitForInitialRemoteData(1, TimeUnit.MILLISECONDS) .build(); try { Realm.getInstance(syncConfiguration); fail("This should have timed out"); } catch (DownloadingRealmInterruptedException ignore) { } looperThread.testComplete(); }</code><technical_language>Leftover for FIXME</technical_language>

Target:
public void waitForInitialRemoteData_throwsOnTimeout() { SyncUser user = UserFactory.createUniqueUser(Constants.AUTH_URL); SyncConfiguration syncConfiguration = configFactory .createSyncConfigurationBuilder(user, Constants.SYNC_SERVER_URL) .initialData(bgRealm -> { for (int i = 0; i < 100; i++) { bgRealm.createObject(AllTypes.class); } }) .waitForInitialRemoteData(1, TimeUnit.MILLISECONDS) .build(); try { Realm.getInstance(syncConfiguration); fail("This should have timed out"); } catch (DownloadingRealmInterruptedException ignore) { } looperThread.testComplete(); }
Source:
<code>public static Intent getLaunchIntent(Context context, BoxCollaborationItem collaborationItem, BoxSession session) { if (collaborationItem == null || SdkUtils.isBlank(collaborationItem.getId()) || SdkUtils.isBlank(collaborationItem.getType())) <START> throw new IllegalArgumentException("A valid folder must be provided for retrieving collaborations"); <END> if (session == null || session.getUser() == null || SdkUtils.isBlank(session.getUser().getId())) throw new IllegalArgumentException("A valid user must be provided for retrieving collaborations"); Intent collabIntent = new Intent(context, BoxCollaborationsActivity.class); collabIntent.putExtra(CollaborationUtils.EXTRA_ITEM, collaborationItem); collabIntent.putExtra(CollaborationUtils.EXTRA_USER_ID, session.getUser().getId()); return collabIntent; }</code><technical_language>Update error message more generic</technical_language>

Target:
public static Intent getLaunchIntent(Context context, BoxCollaborationItem collaborationItem, BoxSession session) { if (collaborationItem == null || SdkUtils.isBlank(collaborationItem.getId()) || SdkUtils.isBlank(collaborationItem.getType())) throw new IllegalArgumentException("A valid collaboration item must be provided for retrieving collaborations"); if (session == null || session.getUser() == null || SdkUtils.isBlank(session.getUser().getId())) throw new IllegalArgumentException("A valid user must be provided for retrieving collaborations"); Intent collabIntent = new Intent(context, BoxCollaborationsActivity.class); collabIntent.putExtra(CollaborationUtils.EXTRA_ITEM, collaborationItem); collabIntent.putExtra(CollaborationUtils.EXTRA_USER_ID, session.getUser().getId()); return collabIntent; }
Source:
<code>public void testSynchronousContinuationTokenAlreadyCancelled() { CancellationTokenSource cts = new CancellationTokenSource(); cts.cancel(); Task<Integer> first = Task.forResult(1); Task<Integer> second = first.continueWith(new Continuation<Integer, Integer>() { <START> public Integer then(Task<Integer> task) { <END> return 2; } }, cts.getToken()); assertTrue(first.isCompleted()); assertTrue(second.isCancelled()); }</code><technical_language>verify continuation block called</technical_language>

Target:
public void testSynchronousContinuationTokenAlreadyCancelled() { CancellationTokenSource cts = new CancellationTokenSource(); final Capture<Boolean> continuationRun = new Capture<>(false); cts.cancel(); Task<Integer> first = Task.forResult(1); Task<Integer> second = first.continueWith(new Continuation<Integer, Integer>() { public Integer then(Task<Integer> task) { continuationRun.set(true); return 2; } }, cts.getToken()); assertTrue(first.isCompleted()); assertTrue(second.isCancelled()); assertFalse(continuationRun.get()); }
Source:
<code>public boolean getLastLocation(Position position, Date deviceTime) { boolean found = false; if (position.getDeviceId() != 0) { position.setOutdated(true); Position last = identityManager.getLastPosition(position.getDeviceId()); if (last != null) { position.setFixTime(last.getFixTime()); position.setValid(last.getValid()); position.setLatitude(last.getLatitude()); position.setLongitude(last.getLongitude()); position.setAltitude(last.getAltitude()); position.setSpeed(last.getSpeed()); position.setCourse(last.getCourse()); position.setAccuracy(last.getAccuracy()); found = true; } else { position.setFixTime(new Date(0)); } if (deviceTime != null) { position.setDeviceTime(deviceTime); } else { position.setDeviceTime(new Date()); } } <START> return found; <END> }</code><technical_language>I need result here</technical_language>

Target:
public void getLastLocation(Position position, Date deviceTime) { if (position.getDeviceId() != 0) { position.setOutdated(true); Position last = identityManager.getLastPosition(position.getDeviceId()); if (last != null) { position.setFixTime(last.getFixTime()); position.setValid(last.getValid()); position.setLatitude(last.getLatitude()); position.setLongitude(last.getLongitude()); position.setAltitude(last.getAltitude()); position.setSpeed(last.getSpeed()); position.setCourse(last.getCourse()); position.setAccuracy(last.getAccuracy()); } else { position.setFixTime(new Date(0)); } if (deviceTime != null) { position.setDeviceTime(deviceTime); } else { position.setDeviceTime(new Date()); } } }
Source:
<code><START> public synchronized URL registerBlob(File file) { <END> URL url = null; for (BlobServer server: servers) { url = server.registerBlob(file); if (url != null) { break; } } if (url != null) { log.info("Registered URL \"" + url + "\" for blob \"" + file.getAbsolutePath() + "\"."); } else { log.warn("Can't generate URL for blob \"" + file.getAbsolutePath() + "\"."); } return url; }</code><technical_language>question before</technical_language>

Target:
public URL registerBlob(File file) { BlobServer server = serverReference.get(); if (server == null) { log.error("Can't generate URL for blob \"" + file.getAbsolutePath() + "\" because no server has been registered."); return null; } return server.registerBlob(file); }
Source:
<code>public void activate() { super.activate(); <START> setProperlyConfigured(true); <END> }</code><technical_language>call setter configuration (from updated()) called</technical_language>

Target:
public void activate() { super.activate(); }
Source:
<code><START> MimeBodyPart(MimeHeader header, Body body) throws MessagingException { <END> this(body); mHeader = header; }</code><technical_language>If other constructors call this one, mHeader final</technical_language>

Target:
MimeBodyPart(MimeHeader header, Body body) throws MessagingException { this(body, null, header); }
Source:
<code>public Printer(File inputFile, Severity maxSeverity, Formatter formatter) { this.inputFile = inputFile; this.maxSeverity = maxSeverity; this.formatter = formatter; <START> shouldPrintParseErrorMessage = false; <END> }</code><technical_language>initialize this field in declaration</technical_language>

Target:
public Printer(File inputFile, Severity maxSeverity, Formatter formatter) { this.inputFile = inputFile; this.maxSeverity = maxSeverity; this.formatter = formatter; }
Source:
<code>public HttpResponseStatus getProxiedOverlordScalingResponseStatus() { try { StatusResponseHolder response = makeRequest( HttpMethod.GET, StringUtils.format( "%s/druid/indexer/v1/scaling", coordinator ) ); return response.getStatus(); } catch (Exception e) { <START> throw Throwables.propagate(e); <END> } }</code><technical_language>Suggest throw new RE(e, "Unable get scaling status [%s]", coordinator)</technical_language>

Target:
public HttpResponseStatus getProxiedOverlordScalingResponseStatus() { try { StatusResponseHolder response = makeRequest( HttpMethod.GET, StringUtils.format( "%s/druid/indexer/v1/scaling", coordinator ) ); return response.getStatus(); } catch (Exception e) { throw new RE(e, "Unable to get scaling status from [%s]", coordinator); } }
Source:
<code>public void setCatalogVersion(long conglomerateNumber, String version) throws IOException { TableName tn = tableInfoFactory.getTableInfo(Long.toString(conglomerateNumber)); try { org.apache.hadoop.hbase.client.TableDescriptor td = admin.getDescriptor(tn); ((TableDescriptorBuilder.ModifyableTableDescriptor) td).setValue(SIConstants.CATALOG_VERSION_ATTR, version); boolean tableEnabled = admin.isTableEnabled(tn); if (tableEnabled) { admin.disableTable(tn); } admin.modifyTable(td); } finally { int wait = 0; if (tn != null && !admin.isTableEnabled(tn)) { admin.enableTable(tn); while (wait < 2000 && !admin.isTableEnabled(tn)) { try { Thread.sleep(100); wait++; } catch (InterruptedException e) { throw new IOException(e); } <START> } <END> } } }</code><technical_language>exiting while loop table is enabled (and throw exception if is not), wait could've reached 2000 retries loop exited table is enabled yet</technical_language>

Target:
public void setCatalogVersion(long conglomerateNumber, String version) throws IOException { TableName tn = tableInfoFactory.getTableInfo(Long.toString(conglomerateNumber)); try { org.apache.hadoop.hbase.client.TableDescriptor td = admin.getDescriptor(tn); ((TableDescriptorBuilder.ModifyableTableDescriptor) td).setValue(SIConstants.CATALOG_VERSION_ATTR, version); boolean tableEnabled = admin.isTableEnabled(tn); if (tableEnabled) { admin.disableTable(tn); } admin.modifyTable(td); } finally { int wait = 0; if (tn != null && !admin.isTableEnabled(tn)) { admin.enableTable(tn); while (wait < 2000 && !admin.isTableEnabled(tn)) { try { Thread.sleep(100); wait++; } catch (InterruptedException e) { throw new IOException(e); } } } if (!admin.isTableEnabled(tn)) { throw new IOException("Table " + tn.getNameAsString() + " is not enabled"); } } }
Source:
<code>public static void beforeClass() throws Exception { zapInstallDir = Files.createDirectory(tempDir.resolve("install")).toAbsolutePath().toString(); <START> Path xmlDir = Files.createDirectory(tempDir.resolve("install/xml")); <END> Files.createFile(xmlDir.resolve("log4j.properties")); zapHomeDir = Files.createDirectory(tempDir.resolve("home")).toAbsolutePath().toString(); }</code><technical_language>restore Path installDir = Files.createDirectory(tempDir.resolve("install")); too, e.g.: Java Path installDir = Files.createDirectory(tempDir.resolve("install")); Path xmlDir = Files.createDirectory(installDir.resolve("xml")); Files.createFile(xmlDir.resolve("log4j.properties")); zapInstallDir = installDir.toAbsolutePath().toString();</technical_language>

Target:
public static void beforeClass() throws Exception { Path installDir = Files.createDirectory(tempDir.resolve("install")); Path xmlDir = Files.createDirectory(installDir.resolve("xml")); Files.createFile(xmlDir.resolve("log4j.properties")); zapInstallDir = installDir.toAbsolutePath().toString(); zapHomeDir = Files.createDirectory(tempDir.resolve("home")).toAbsolutePath().toString(); }
Source:
<code>public int getMonth() { <START> return _calendar.getMonthValue(); <END> }</code><technical_language>Is precedent in library for underscores</technical_language>

Target:
public int getMonth() { return date.getMonthValue(); }
Source:
<code>public PackingPlan pack() { while (true) { try { PackingPlanBuilder planBuilder = newPackingPlanBuilder(null); planBuilder.updateNumContainers(numContainers); planBuilder = getResourceCompliantRRAllocation(planBuilder); return planBuilder.build(); } catch (ConstraintViolationException e) { LOG.finest(String.format( "%s Increasing the number of containers to %s and attempting to place again.", e.getMessage(), this.numContainers + 1)); increaseNumContainers(1); resetToFirstContainer(); int totalInstances = TopologyUtils.getTotalInstance(topology); <START> if (numContainers > totalInstances) { <END> throw new PackingException("Cannot add to that container"); } } } }</code><technical_language>this happen? shrink numContainers totalInstances</technical_language>

Target:
public PackingPlan pack() { while (true) { try { PackingPlanBuilder planBuilder = newPackingPlanBuilder(null); planBuilder.updateNumContainers(numContainers); planBuilder = getResourceCompliantRRAllocation(planBuilder); return planBuilder.build(); } catch (ConstraintViolationException e) { LOG.finest(String.format( "%s Increasing the number of containers to %s and attempting to place again.", e.getMessage(), this.numContainers + 1)); retryWithAdditionalContainer(); } } }
Source:
<code>public void thingAdded(Thing thing, ThingTrackerEvent thingTrackerEvent) { this.things.add(thing); logger.debug("Thing '{}' is tracked by ThingManager.", thing.getUID()); if ( storage != null <START> && storage.get(thing.getUID().getAsString()) != null <END> && !storage.get(thing.getUID().getAsString())) { setEnabled(thing.getUID(), false); } if (!isHandlerRegistered(thing)) { registerAndInitializeHandler(thing, getThingHandlerFactory(thing)); } else { logger.debug("Handler of tracked thing '{}' already registered.", thing.getUID()); } }</code><technical_language>speaking storage.containsKey(...)</technical_language>

Target:
public void thingAdded(Thing thing, ThingTrackerEvent thingTrackerEvent) { this.things.add(thing); logger.debug("Thing '{}' is tracked by ThingManager.", thing.getUID()); if (!isHandlerRegistered(thing)) { registerAndInitializeHandler(thing, getThingHandlerFactory(thing)); } else { logger.debug("Handler of tracked thing '{}' already registered.", thing.getUID()); } }
Source:
<code>public DocumentModel run(DocumentModel doc) throws OperationException, IOException { Property complexProperty = doc.getProperty(xpath); <START> ListType ltype = (ListType) complexProperty.getField().getType(); <END> if (!ltype.getFieldType().isComplexType()) { throw new OperationException("Property type is not supported by this operation"); } List<Object> newVals = ComplexTypeJSONDecoder.decodeList(ltype, ComplexJsonProperties); for (Object newVal : newVals) { complexProperty.addValue(newVal); } doc = session.saveDocument(doc); if (save) { session.save(); } return doc; }</code><technical_language>need abbreviate -> listType</technical_language>

Target:
public DocumentModel run(DocumentModel doc) throws OperationException, IOException { Property complexProperty = doc.getProperty(xpath); ListType listType = (ListType) complexProperty.getField().getType(); if (!listType.getFieldType().isComplexType()) { throw new OperationException("Property type " + listType.getFieldType().getClass().getName() + " is not supported by this operation"); } List<Object> newVals = ComplexTypeJSONDecoder.decodeList(listType, complexJsonProperties); for (Object newVal : newVals) { complexProperty.addValue(newVal); } doc = session.saveDocument(doc); if (save) { session.save(); } return doc; }
Source:
<code>public String toString() { String[] partitionIdStrings = partitions.stream().map(p -> String.valueOf(p.id)).toArray(String[]::new); <START> return String.format("Host %d sph:%d ha:%s (Partitions %s)", <END> id, haGroup, String.join(",", partitionIdStrings)); }</code><technical_language>Bug? format requires 4 params 3 provided</technical_language>

Target:
public String toString() { String[] partitionIdStrings = partitions.stream().map(p -> String.valueOf(p.id)).toArray(String[]::new); return String.format("Host %d ha:%s (Partitions %s)", id, haGroup, String.join(",", partitionIdStrings)); }
Source:
<code>private void executeFetchCommand(FetchNode node) { <START> CommonUtils.runCommand("org.eclipse.egit.ui.team.SimpleFetch", END> new StructuredSelection(node)); }</code><technical_language>ActionCommands.SIMPLE_FETCH_ACTION</technical_language>

Target:
private void executeFetchCommand(FetchNode node) { CommonUtils.runCommand(ActionCommands.SIMPLE_FETCH_ACTION, new StructuredSelection(node)); }
Source:
<code>public static String setGrade(final Connection conn, final String userId, final String classification, final String itemId, final SrlGrade grade) throws DatabaseAccessException { String result; final String query = "SELECT * FROM Grades WHERE UserID=? AND SchoolItemType=? AND SchoolItemID=?;"; try (PreparedStatement stmt = conn.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE)) { stmt.setString(1, userId); stmt.setString(2, classification); stmt.setString(3, itemId); try (final ResultSet rst = stmt.executeQuery()) { if (rst.next()) { <START> rst.updateFloat("Grade", grade.getGrade()); <END> rst.updateString("Comments", grade.getComment()); rst.updateRow(); result = "SET"; } else { rst.moveToInsertRow(); rst.updateString("UserID", userId); rst.updateString("SchoolItemType", classification); rst.updateString("SchoolItemID", itemId); rst.updateFloat("Grade", grade.getGrade()); rst.updateString("Comments", grade.getComment()); rst.insertRow(); rst.moveToCurrentRow(); result = "INSERT"; } } catch (SQLException e) { throw new DatabaseAccessException(e, false); } } catch (SQLException e) { throw new DatabaseAccessException(e, false); } return result; }</code><technical_language>database string constants instead of values</technical_language>

Target:
public static String setGrade(final Connection conn, final String userId, final String classification, final String itemId, final SrlGrade grade) throws DatabaseAccessException { String result; final String query = "SELECT * FROM Grades WHERE UserID=? AND SchoolItemType=? AND SchoolItemID=?;"; try (PreparedStatement stmt = conn.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE)) { stmt.setString(1, userId); stmt.setString(2, classification); stmt.setString(3, itemId); try (final ResultSet rst = stmt.executeQuery()) { if (rst.next()) { rst.updateFloat(DatabaseStringConstants.GRADE, grade.getGrade()); rst.updateString(DatabaseStringConstants.COMMENTS, grade.getComment()); rst.updateRow(); result = "SET"; } else { rst.moveToInsertRow(); rst.updateString(DatabaseStringConstants.USER_ID, userId); rst.updateString(DatabaseStringConstants.SCHOOLITEMTYPE, classification); rst.updateString(DatabaseStringConstants.SCHOOLITEMID, itemId); rst.updateFloat(DatabaseStringConstants.GRADE, grade.getGrade()); rst.updateString(DatabaseStringConstants.COMMENTS, grade.getComment()); rst.insertRow(); rst.moveToCurrentRow(); result = "INSERT"; } } catch (SQLException e) { throw new DatabaseAccessException(e, false); } } catch (SQLException e) { throw new DatabaseAccessException(e, false); } return result; }
Source:
<code><START> public static void afterClass() { <END> SWTBotUtils.deleteProject(TRACE_PROJECT_NAME, fBot); fBot.closeAllEditors(); fLogger.removeAllAppenders(); }</code><technical_language>safer set preference enabled here</technical_language>

Target:
public static void afterClass() { setTraceTypePreferences(CHECK_ALL); SWTBotUtils.deleteProject(TRACE_PROJECT_NAME, fBot); fBot.closeAllEditors(); fLogger.removeAllAppenders(); }
Source:
<code>private VideoAttributesType generateVideoAttributes(Encoding encoding) { VideoAttributesType videoAttributes = new VideoAttributesType(); videoAttributes.setHorizontalSize(Optional.fromNullable(encoding.getVideoHorizontalSize()) .or(DEFAULT_HORIZONTAL_SIZE)); videoAttributes.setVerticalSize(Optional.fromNullable(encoding.getVideoVerticalSize()) .or(DEFAULT_VERTICAL_SIZE)); AspectRatioType aspectRatio = new AspectRatioType(); <START> aspectRatio.setValue(Objects.firstNonNull(encoding.getVideoAspectRatio(), ASPECT_RATIO)); <END> videoAttributes.getAspectRatio().add(aspectRatio); return videoAttributes; }</code><technical_language>update this constant called DEFAULT_ASPECT_RATIO, set encoding</technical_language>

Target:
private VideoAttributesType generateVideoAttributes(Encoding encoding) { VideoAttributesType videoAttributes = new VideoAttributesType(); videoAttributes.setHorizontalSize(Objects.firstNonNull(encoding.getVideoHorizontalSize(), DEFAULT_HORIZONTAL_SIZE)); videoAttributes.setVerticalSize(Objects.firstNonNull(encoding.getVideoVerticalSize(), DEFAULT_VERTICAL_SIZE)); AspectRatioType aspectRatio = new AspectRatioType(); aspectRatio.setValue(Objects.firstNonNull(encoding.getVideoAspectRatio(), DEFAULT_ASPECT_RATIO)); videoAttributes.getAspectRatio().add(aspectRatio); return videoAttributes; }
Source:
<code>public void serve() { try { ITransportPlugin transportPlugin = AuthUtils.GetTransportPlugin(_storm_conf, _login_conf); _server = transportPlugin.getServer(_port, _processor); _server.serve(); } catch (Exception ex) { LOG.error("ThriftServer is being stopped due to: " + ex, ex); if (_server != null) _server.stop(); <START> System.exit(1); END> } }</code><technical_language>System.halt System.exit. Nimbus is fail fast aggressively suicide in case hits a bad situation. System.exit freeze exiting process process seriously messed (like memory issues)</technical_language>

Target:
public void serve() { try { ITransportPlugin transportPlugin = AuthUtils.GetTransportPlugin(_storm_conf, _login_conf); _server = transportPlugin.getServer(_port, _processor); _server.serve(); } catch (Exception ex) { LOG.error("ThriftServer is being stopped due to: " + ex, ex); if (_server != null) _server.stop(); Runtime.getRuntime().halt(1); } }
Source:
<code>public boolean isInodeIndexedArchived(String inode){ if (!UtilMethods.isSet(inode)) { Logger.warn(this, "Requested Inode is not indexed because Inode is not set"); } <START> return isInodeIndexedWithQuery("+inode:" + inode + String.format(" +deleted:%s",true)); <END> }</code><technical_language>I existing isInodeIndexedWithQuery call new isInodeIndexedArchived made</technical_language>

Target:
public boolean isInodeIndexedArchived(String inode){ return isInodeIndexedArchived(inode, -1); }
Source:
<code>public Map<String, IdealState> computeNewIdealStates(ResourceControllerDataProvider clusterData, Map<String, Resource> resourceMap, final CurrentStateOutput currentStateOutput) throws HelixRebalanceException, JMException { if (resourceMap.isEmpty()) { LOG.warn("There is no resource to be rebalanced by {}", this.getClass().getSimpleName()); return Collections.emptyMap(); } LOG.info("Start computing new ideal states for resources: {}", resourceMap.keySet().toString()); validateInput(clusterData, resourceMap); Map<String, IdealState> newIdealStates = computeBestPossibleStates(clusterData, resourceMap, currentStateOutput); for (IdealState is : newIdealStates.values()) { String resourceName = is.getResourceName(); ResourceAssignment finalAssignment = _mappingCalculator.computeBestPossiblePartitionState( clusterData, is, resourceMap.get(resourceName), currentStateOutput); is.getRecord().getMapFields().clear(); for (Partition partition : finalAssignment.getMappedPartitions()) { Map<String, String> newStateMap = finalAssignment.getReplicaMap(partition); is.setInstanceStateMap(partition.getPartitionName(), newStateMap == null ? Collections.emptyMap() : newStateMap); } } LOG.info("Finish computing new ideal states for resources: {}", resourceMap.keySet().toString()); <START> _metricCollector.register(); <END> return newIdealStates; }</code><technical_language>Considering future improvement, I constructing WAGED rebalance once, please register in constructor. earlier. pass registered _metricCollector WAGED rebalancer need register again. Another question is I assume metric data updated here, register data collected</technical_language>

Target:
public Map<String, IdealState> computeNewIdealStates(ResourceControllerDataProvider clusterData, Map<String, Resource> resourceMap, final CurrentStateOutput currentStateOutput) throws HelixRebalanceException { if (resourceMap.isEmpty()) { LOG.warn("There is no resource to be rebalanced by {}", this.getClass().getSimpleName()); return Collections.emptyMap(); } LOG.info("Start computing new ideal states for resources: {}", resourceMap.keySet().toString()); validateInput(clusterData, resourceMap); Map<String, IdealState> newIdealStates = computeBestPossibleStates(clusterData, resourceMap, currentStateOutput); for (IdealState is : newIdealStates.values()) { String resourceName = is.getResourceName(); ResourceAssignment finalAssignment = _mappingCalculator.computeBestPossiblePartitionState( clusterData, is, resourceMap.get(resourceName), currentStateOutput); is.getRecord().getMapFields().clear(); for (Partition partition : finalAssignment.getMappedPartitions()) { Map<String, String> newStateMap = finalAssignment.getReplicaMap(partition); is.setInstanceStateMap(partition.getPartitionName(), newStateMap == null ? Collections.emptyMap() : newStateMap); } } LOG.info("Finish computing new ideal states for resources: {}", resourceMap.keySet().toString()); return newIdealStates; }
Source:
<code>public static String localizeProvider(String name) { if (name==null) { Assert.isTrue(false); return null; <START> } <END> switch (name) { case DIRECT_PROVIDER: return Messages.ProxySelector_0; case ECLIPSE_PROVIDER: return Messages.ProxySelector_1; case NATIVE_PROVIDER: return Messages.ProxySelector_2; default: break; } Assert.isTrue(false); return null; }</code><technical_language>I this code duplication. if (name != null) { switch (name) { ... } } Assert.isTrue(false); return null;</technical_language>

Target:
public static String localizeProvider(String name) { if (name != null) { switch (name) { case DIRECT_PROVIDER: return Messages.ProxySelector_0; case ECLIPSE_PROVIDER: return Messages.ProxySelector_1; case NATIVE_PROVIDER: return Messages.ProxySelector_2; default: break; } } Assert.isTrue(false); return null; }
Source:
<code>public void onLoad(final InterstitialAd ad) { Log.d(TAG, "Interstitial mediation Ad loaded"); if (myTargetView != null) { <START> myTargetView.start(); <END> } listener.onAdLoaded(MyTargetAdapter.this); }</code><technical_language>I this needs in [MyTargetBannerListener](<LINK_0>'s onLoad callback above</technical_language>

Target:
public void onLoad(final InterstitialAd ad) { Log.d(TAG, "Interstitial mediation Ad loaded"); listener.onAdLoaded(MyTargetAdapter.this); }
Source:
<code>private static String branchToRef(String name) { <START> if (name.startsWith(Branch.R_HEADS)) <END> return Branch.R_HEADS + name; return name; }</code><technical_language>be: if (!name.startsWith(Branch.R_HEADS))</technical_language>

Target:
private static String branchToRef(String name) { if (!name.startsWith(Branch.R_HEADS)) return Branch.R_HEADS + name; return name; }
Source:
<code>private String xpath() { return String.format( <START> "/github/repos/repo[@coords='%s']/collaborators/", <END> this.coords ); }</code><technical_language>making double slashes here..</technical_language>

Target:
private String xpath() { return String.format( "/github/repos/repo[@coords='%s']/collaborators", this.coords ); }
Source:
<code>public void onGuiClosed() { NBTTagCompound nbtTagCompound = book.getTagCompound(); nbtTagCompound.setInteger("page", page); <START> nbtTagCompound.setFloat("sliderProgress", sliderProgress); <END> super.onGuiClosed(); }</code><technical_language>This work in creative mode client modify item data. write some kind of netcode (packets) server change item data</technical_language>

Target:
public void onGuiClosed() { ItemGuideBook.setCurrentPage(page, sliderProgress, hand); super.onGuiClosed(); }
Source:
<code>public DancerState getDancerState() { <START> return dancerState != null ? dancerState : HAS_TOKEN; <END> }</code><technical_language>NO_TOKEN default</technical_language>

Target:
public DancerState getDancerState() { return this.dancerState != null ? dancerState : accessToken == null ? NO_TOKEN : HAS_TOKEN; }
Source:
<code>private void updateId() { StringBuilder sb = new StringBuilder(triggerId); <START> sb.append("-").append(triggerMode.ordinal()); <END> sb.append("-").append(conditionSetSize); sb.append("-").append(conditionSetIndex); this.conditionId = sb.toString(); }</code><technical_language>I instead save ordinal (that is hard remind) good store literal of triggerMode, I guess this time ok gain for clarity</technical_language>

Target:
private void updateId() { StringBuilder sb = new StringBuilder(triggerId); sb.append("-").append(triggerMode.name()); sb.append("-").append(conditionSetSize); sb.append("-").append(conditionSetIndex); this.conditionId = sb.toString(); }
Source:
<code>public void sendMessage_shouldFailIfMessageIsNull() throws MessageException { <START> MessageService messageService = Context.getMessageService(); <END> messageService.sendMessage(null); }</code><technical_language>Mock this also</technical_language>

Target:
public void sendMessage_shouldFailIfMessageIsNull() throws MessageException { ms.sendMessage(null); }
Source:
<code>private long getNextQueryTime() { if (fCurrent != null) { long endTime = fCurrent.getEndTime(); return (Long.max(endTime + 1, <START> fLastQuery + fResolution)); <END> } return Long.max(fInitialTime, fSS.getStartTime()); }</code><technical_language>ensure this falls endTime, query interval multiple times? i.e. case fLastQuery + fResolution <= endTime</technical_language>

Target:
private long getNextQueryTime() { if (fCurrent != null) { long endTime = fCurrent.getEndTime(); return (fResolution == 1 ? endTime + 1 : ((endTime - fLastQueriedTime) / fResolution + 1) * fResolution); } return Long.max(fInitialTime, fSS.getStartTime()); }
Source:
<code>public void testAvailableInputLocationRetrieval() { TestingInputsLocationsRetriever originalLocationRetriever = new TestingInputsLocationsRetriever .Builder() .connectConsumerToProducer(EV5, EV1) .connectConsumerToProducer(EV5, EV2) .connectConsumerToProducer(EV5, EV3) .connectConsumerToProducer(EV5, EV4) .build(); originalLocationRetriever.assignTaskManagerLocation(EV1); originalLocationRetriever.markScheduled(EV2); originalLocationRetriever.failTaskManagerLocation(EV3, new Throwable()); originalLocationRetriever.cancelTaskManagerLocation(EV4); SyncPreferredLocationsRetriever locationsRetriever = new DefaultSyncPreferredLocationsRetriever( executionVertexId -> Optional.empty(), originalLocationRetriever); Collection<TaskManagerLocation> preferredLocations = locationsRetriever .getPreferredLocations(EV5, Collections.emptySet()); TaskManagerLocation expectedLocation = originalLocationRetriever .getTaskManagerLocation(EV1) .get() .join(); assertThat(preferredLocations, hasSize(1)); <START> assertThat(preferredLocations.iterator().next(), is(expectedLocation)); <END> }</code><technical_language>assertThat(preferredLocations, contains(expectedLocation)) do need assertThat(preferredLocations, hasSize(1));</technical_language>

Target:
public void testAvailableInputLocationRetrieval() { TestingInputsLocationsRetriever originalLocationRetriever = new TestingInputsLocationsRetriever .Builder() .connectConsumerToProducer(EV5, EV1) .connectConsumerToProducer(EV5, EV2) .connectConsumerToProducer(EV5, EV3) .connectConsumerToProducer(EV5, EV4) .build(); originalLocationRetriever.assignTaskManagerLocation(EV1); originalLocationRetriever.markScheduled(EV2); originalLocationRetriever.failTaskManagerLocation(EV3, new Throwable()); originalLocationRetriever.cancelTaskManagerLocation(EV4); SyncPreferredLocationsRetriever locationsRetriever = new DefaultSyncPreferredLocationsRetriever( executionVertexId -> Optional.empty(), originalLocationRetriever); Collection<TaskManagerLocation> preferredLocations = locationsRetriever .getPreferredLocations(EV5, Collections.emptySet()); TaskManagerLocation expectedLocation = originalLocationRetriever .getTaskManagerLocation(EV1) .get() .join(); assertThat(preferredLocations, contains(expectedLocation)); }
Source:
<code>private FTPSClient createSecureClient(boolean setKeystore) throws Exception { FTPSClient ftps = new FTPSClient(); if (setKeystore) { KeyManager keyManager = KeyManagerUtils.createClientKeyManager( new File(System.getProperty("javax.net.ssl.keyStore")), System.getProperty("javax.net.ssl.keyStorePassword")); ftps.setKeyManager(keyManager); } await() .atMost(30, TimeUnit.SECONDS) .pollDelay(1, TimeUnit.SECONDS) .dontCatchUncaughtExceptions() .until( <START> () -> { <END> ftps.connect(FTP_SERVER, Integer.parseInt(FTP_PORT.getPort())); return true; }); showServerReply(ftps); int connectionReply = ftps.getReplyCode(); if (!FTPReply.isPositiveCompletion(connectionReply)) { fail("FTP server refused connection: " + connectionReply); } boolean success = ftps.login(USERNAME, PASSWORD); showServerReply(ftps); if (!success) { fail("Could not log in to the FTP server."); } ftps.enterLocalPassiveMode(); ftps.setControlKeepAliveTimeout(300); ftps.setFileType(FTP.BINARY_FILE_TYPE); return ftps; }</code><technical_language>move lambda a private method</technical_language>

Target:
private FTPSClient createSecureClient(boolean setKeystore) throws Exception { FTPSClient ftps = new FTPSClient(); if (setKeystore) { KeyManager keyManager = KeyManagerUtils.createClientKeyManager( new File(System.getProperty("javax.net.ssl.keyStore")), System.getProperty("javax.net.ssl.keyStorePassword")); ftps.setKeyManager(keyManager); } await() .atMost(30, TimeUnit.SECONDS) .pollDelay(1, TimeUnit.SECONDS) .dontCatchUncaughtExceptions() .until( () -> successfulFtpConnection(ftps, FTP_SERVER, Integer.parseInt(FTP_PORT.getPort()))); showServerReply(ftps); int connectionReply = ftps.getReplyCode(); if (!FTPReply.isPositiveCompletion(connectionReply)) { fail("FTP server refused connection: " + connectionReply); } boolean success = ftps.login(USERNAME, PASSWORD); showServerReply(ftps); if (!success) { fail("Could not log in to the FTP server."); } ftps.enterLocalPassiveMode(); ftps.setControlKeepAliveTimeout(300); ftps.setFileType(FTP.BINARY_FILE_TYPE); return ftps; }
Source:
<code>private Mono<Message<?>> handleSendError(Message<?> requestMessage, Throwable exception) { if (logger.isDebugEnabled()) { logger.debug("failure occurred in gateway sendAndReceiveReactive: " + exception.getMessage()); <START> } <END> MessageChannel errorChannel = getErrorChannel(); if (errorChannel != null) { ErrorMessage errorMessage = buildErrorMessage(requestMessage, exception); try { return doSendAndReceiveMessageReactive(errorChannel, errorMessage, true); } catch (Exception errorFlowFailure) { return Mono.error( new MessagingException(errorMessage, "failure occurred in error-handling flow", errorFlowFailure)); } } else { return Mono.error(wrapExceptionIfNecessary(exception, "gateway received checked Exception")); } }</code><technical_language>resume response error channel ? If message different, is expected</technical_language>

Target:
private Mono<Message<?>> handleSendError(Message<?> requestMessage, Throwable exception) { if (logger.isDebugEnabled()) { logger.debug("failure occurred in gateway sendAndReceiveReactive: " + exception.getMessage()); } MessageChannel errorChannel = getErrorChannel(); if (errorChannel != null) { ErrorMessage errorMessage = buildErrorMessage(requestMessage, exception); try { return doSendAndReceiveMessageReactive(errorChannel, errorMessage, true); } catch (Exception errorFlowFailure) { throw new MessagingException(errorMessage, "failure occurred in error-handling flow", errorFlowFailure); } } else { throw wrapExceptionIfNecessary(exception, "gateway received checked Exception"); } }
Source:
<code>private void insertLinks() { Props azkProps = AzkabanExecutorServer.getApp().getAzkabanProps(); String baseURL = azkProps.get("azkaban.webserver.url"); <START> if (baseURL == null) <END> return; String flowName = node.getParentFlow().getFlowId(); String projectName = node.getParentFlow().getProjectName(); props.put(CommonJobProperties.EXECUTION_LINK, String.format("%s/executor?execid=%d", baseURL, executionId)); props.put(CommonJobProperties.JOBEXEC_LINK, String.format( "%s/executor?execid=%d&job=%s", baseURL, executionId, jobId)); props.put(CommonJobProperties.ATTEMPT_LINK, String.format( "%s/executor?execid=%d&job=%s&attempt=%d", baseURL, executionId, jobId, node.getAttempt())); props.put(CommonJobProperties.WORKFLOW_LINK, String.format( "%s/manager?project=%s&flow=%s", baseURL, projectName, flowName)); props.put(CommonJobProperties.JOB_LINK, String.format( "%s/manager?project=%s&flow=%s&job=%s", baseURL, projectName, flowName, jobId)); }</code><technical_language>Add braces this</technical_language>

Target:
private void insertLinks() { Props azkProps = AzkabanExecutorServer.getApp().getAzkabanProps(); String baseURL = azkProps.get("azkaban.webserver.url"); if (baseURL == null){ return; } String flowName = node.getParentFlow().getFlowId(); String projectName = node.getParentFlow().getProjectName(); props.put(CommonJobProperties.EXECUTION_LINK, String.format("%s/executor?execid=%d", baseURL, executionId)); props.put(CommonJobProperties.JOBEXEC_LINK, String.format( "%s/executor?execid=%d&job=%s", baseURL, executionId, jobId)); props.put(CommonJobProperties.ATTEMPT_LINK, String.format( "%s/executor?execid=%d&job=%s&attempt=%d", baseURL, executionId, jobId, node.getAttempt())); props.put(CommonJobProperties.WORKFLOW_LINK, String.format( "%s/manager?project=%s&flow=%s", baseURL, projectName, flowName)); props.put(CommonJobProperties.JOB_LINK, String.format( "%s/manager?project=%s&flow=%s&job=%s", baseURL, projectName, flowName, jobId)); }
Source:
<code>private void doWhatDoYouDoRequest(VoiceInput voiceInput, SsmlDocumentBuilder builder) { String bot = (String) voiceInput.getMetadata().get("bot"); if(bot == null || bot.isEmpty()){ builder.text("I don't have any info for this situation."); return; } switch(bot){ case "complibot": builder.text("I give you compliments and tell you how awesome you are, ").pause().text("and then I sit quietly and wait for you to talk to me again!").endSentence(); break; case "insultibot": builder.text("I mainly just tell you how awful you are. ").endSentence().text("Now, leave me alone.").endSentence(); break; default: <START> builder.text("I don't have that info for the bot named '" + bot + "'.").endSentence(); <END> return; } }</code><technical_language>info</technical_language>

Target:
private void doWhatDoYouDoRequest(VoiceInput voiceInput, SsmlDocumentBuilder builder) { String bot = (String) voiceInput.getMetadata().get("bot"); if(StringUtils.isEmpty(bot)){ builder.text("I don't have any info for this situation."); return; } switch(bot){ case "complibot": builder.text("I give you compliments and tell you how awesome you are, ").pause().text("and then I sit quietly and wait for you to talk to me again!").endSentence(); break; case "insultibot": builder.text("I mainly just tell you how awful you are. ").endSentence().text("Now, leave me alone.").endSentence(); break; default: builder.text("I don't have any info for the bot named '" + bot + "'.").endSentence(); return; } }
Source:
<code>public void brokerAdded(String brokerId, MqttBrokerConnection broker) { logger.trace("Found broker connection {}", brokerId); Map<String, Object> properties = new HashMap<>(); properties.put("host", broker.getHost()); properties.put("port", broker.getPort()); ThingUID thingUID; thingUID = new ThingUID(MqttBrokerBindingConstants.BRIDGE_TYPE_SYSTEMBROKER, brokerId); thingDiscovered(DiscoveryResultBuilder.create(thingUID).withProperties(properties) <START> .withLabel("Mqtt Broker (" + brokerId + " - " + broker.getHost() + ")").build()); <END> }</code><technical_language>a bit unfortunate MqttBrokerConnections do a label for UIs - imho need a property in order properly deal in UIs, wdyt? remove parts in brackets label - instead representation property, set instead (you'll decide brokerId host is unique identifier)</technical_language>

Target:
public void brokerAdded(String brokerId, MqttBrokerConnection broker) { logger.trace("Found broker connection {}", brokerId); Map<String, Object> properties = new HashMap<>(); properties.put("host", broker.getHost()); properties.put("port", broker.getPort()); properties.put("brokerid", brokerId); ThingUID thingUID; thingUID = new ThingUID(MqttBindingConstants.BRIDGE_TYPE_SYSTEMBROKER, brokerId); thingDiscovered(DiscoveryResultBuilder.create(thingUID).withProperties(properties) .withRepresentationProperty("brokerid").withLabel("MQTT Broker").build()); }
Source:
<code>void populate(final int row, final PluginInfo plugin) { CheckBox checkBox = new CheckBox(); table.setWidget(row, 1, checkBox); table.setWidget( row, 2, <START> new Anchor(plugin.name(), Gerrit.selfRedirect("/plugins/" <END> + plugin.name() + "/"))); table.setText(row, 3, plugin.version()); if(plugin.isDisabled()) { table.setText(row, 4, Util.C.pluginDisabled()); } final FlexCellFormatter fmt = table.getFlexCellFormatter(); fmt.addStyleName(row, 1, Gerrit.RESOURCES.css().iconCell()); fmt.addStyleName(row, 2, Gerrit.RESOURCES.css().dataCell()); fmt.addStyleName(row, 3, Gerrit.RESOURCES.css().dataCell()); fmt.addStyleName(row, 4, Gerrit.RESOURCES.css().dataCell()); setRowItem(row, plugin); }</code><technical_language>link a disabled plugin</technical_language>

Target:
void populate(final int row, final PluginInfo plugin) { if (plugin.isDisabled()) { table.setText(row, 1, plugin.name()); } else { table.setWidget( row, 1, new Anchor(plugin.name(), Gerrit.selfRedirect("/plugins/" + plugin.name() + "/"))); } table.setText(row, 2, plugin.version()); if (plugin.isDisabled()) { table.setText(row, 3, Util.C.pluginDisabled()); } final FlexCellFormatter fmt = table.getFlexCellFormatter(); fmt.addStyleName(row, 1, Gerrit.RESOURCES.css().dataCell()); fmt.addStyleName(row, 2, Gerrit.RESOURCES.css().dataCell()); fmt.addStyleName(row, 3, Gerrit.RESOURCES.css().dataCell()); setRowItem(row, plugin); }
Source:
<code>public static Person fromJSON(JSONObject json, int localTableBlogId) { if (json == null) { return null; } <START> long personID = Long.parseLong(json.optString("ID")); <END> String username = json.optString("login"); String firstName = json.optString("first_name"); String lastName = json.optString("last_name"); String displayName = json.optString("nice_name"); String avatarUrl = json.optString("avatar_URL"); Role role = Role.fromKey(json.optJSONArray("roles").optString(0)); return new Person(personID, localTableBlogId, username, firstName, lastName, displayName, avatarUrl, role); }</code><technical_language>Person id read optional field json. Is really? If yes, parseLong fail Unchecked exception force-closing app. If person id is optional need handle this. OTOH, if person id is optional in json/api more expressive getString() used. force handle potential error in json. in all, need handle potential error personID is part of DB table's key trustworthy. Cheers</technical_language>

Target:
public static Person fromJSON(JSONObject json, int localTableBlogId) { if (json == null) { return null; } try { long personID = Long.parseLong(json.getString("ID")); String username = json.optString("login"); String firstName = json.optString("first_name"); String lastName = json.optString("last_name"); String displayName = json.optString("nice_name"); String avatarUrl = json.optString("avatar_URL"); Role role = Role.fromKey(json.optJSONArray("roles").optString(0)); return new Person(personID, localTableBlogId, username, firstName, lastName, displayName, avatarUrl, role); } catch (JSONException e) { AppLog.e(AppLog.T.PEOPLE, "JSON exception occurred while parsing the user json: " + e); } catch (NumberFormatException e) { AppLog.e(AppLog.T.PEOPLE, "The ID parsed from the JSON couldn't be converted to long: " + e); } return null; }