auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected ActionResult execute() throws EntityDoesNotExistException { String courseId = getRequestParamValue(Const.ParamsNames.COURSE_ID); Assumption.assertNotNull(courseId); String fsname = getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_NAME); int fsindex = Integer.parseInt(getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_INDEX)); Assumption.assertNotNull(fsname); instructor = logic.getInstructorForGoogleId(courseId, account.googleId); new GateKeeper().verifyAccessible(instructor, logic.getCourse(courseId)); CourseRoster roster = new CourseRoster( logic.getStudentsForCourse(courseId), logic.getInstructorsForCourse(courseId)); data = new InstructorFeedbackResponseCommentsLoadPageData(account); data.feedbackResultBundles = getFeedbackResultBundles(courseId, fsname, roster); data.instructorEmail = instructor.email; data.currentInstructor = instructor; data.roster = roster; data.feedbackSessionIndex = fsindex; data.numberOfPendingComments = logic.getCommentsForSendingState(courseId, CommentSendingState.PENDING).size() + logic.getFeedbackResponseCommentsForSendingState(courseId, CommentSendingState.PENDING).size(); return createShowPageResult(Const.ViewURIs.INSTRUCTOR_FEEDBACK_RESPONSE_COMMENTS_LOAD, data); }

Target:
protected ActionResult execute() throws EntityDoesNotExistException { String courseId = getRequestParamValue(Const.ParamsNames.COURSE_ID); Assumption.assertNotNull(courseId); String fsname = getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_NAME); String fsindexString = getRequestParamValue(Const.ParamsNames.FEEDBACK_SESSION_INDEX); Assumption.assertNotNull(fsindexString); int fsindex = 0; try { fsindex = Integer.parseInt(fsindexString); } catch(NumberFormatException e) { Assumption.fail("Invalid request parameter value for feedback session index: "+fsindexString); } Assumption.assertNotNull(fsname); instructor = logic.getInstructorForGoogleId(courseId, account.googleId); new GateKeeper().verifyAccessible(instructor, logic.getCourse(courseId)); CourseRoster roster = new CourseRoster( logic.getStudentsForCourse(courseId), logic.getInstructorsForCourse(courseId)); data = new InstructorFeedbackResponseCommentsLoadPageData(account); data.feedbackResultBundles = getFeedbackResultBundles(courseId, fsname, roster); data.instructorEmail = instructor.email; data.currentInstructor = instructor; data.roster = roster; data.feedbackSessionIndex = fsindex; data.numberOfPendingComments = logic.getCommentsForSendingState(courseId, CommentSendingState.PENDING).size() + logic.getFeedbackResponseCommentsForSendingState(courseId, CommentSendingState.PENDING).size(); return createShowPageResult(Const.ViewURIs.INSTRUCTOR_FEEDBACK_RESPONSE_COMMENTS_LOAD, data); }
Source:
private Set<BlockDevice> getBlockDevices(VirtualGuest virtualGuest) { if (virtualGuest.getVirtualGuestBlockDevices() == null) return null; Set<BlockDevice> set = FluentIterable.from(virtualGuest.getVirtualGuestBlockDevices()) .transform(new Function<VirtualGuestBlockDevice, BlockDevice>() { @Override public BlockDevice apply(VirtualGuestBlockDevice input) { return new BlockDevice(input.getDevice(), input.getVirtualDiskImage().getCapacity()); } }) .toSortedSet(new Comparator<BlockDevice>() { @Override public int compare(BlockDevice b1, BlockDevice b2) { return Integer.valueOf(b1.getDevice()).compareTo(Integer.valueOf(b2.getDevice())); } }); return set; }

Target:
private Set<BlockDevice> getBlockDevices(VirtualGuest virtualGuest) { if (virtualGuest.getVirtualGuestBlockDevices() == null) { return null; } ImmutableSortedSet.Builder<BlockDevice> blockDevices = ImmutableSortedSet.orderedBy(new BlockDevicesComparator()); for (VirtualGuestBlockDevice blockDevice : virtualGuest.getVirtualGuestBlockDevices()) { blockDevices.add(new BlockDevice(blockDevice.getDevice(), blockDevice.getVirtualDiskImage().getCapacity())); } return blockDevices.build(); }
Source:
public final void validationFailsOnArchitectsMismatch() throws Exception { final String commander = "Yegor1024"; final Profile master = new Profile.Fixed( new XMLDocument( String.format( ProfilesTest.PROFILE, "Yegor64", commander, "do_something" ) ) ); final Profile merged = new Profile.Fixed( new XMLDocument( String.format( ProfilesTest.PROFILE, "Bobby", commander, "do_another" ) ) ); try { new Profiles().validated(master, merged); MatcherAssert.assertThat( "Code above must throw an exception", false ); } catch (final Profile.ConfigException exception) { MatcherAssert.assertThat( exception.getMessage(), Matchers.is( String.format( ProfilesTest.MESSAGE, "architect" ) ) ); } }

Target:
public final void validationFailsOnArchitectsMismatch() throws Exception { final String commander = "Yegor1024"; final Profile master = new Profile.Fixed( new XMLDocument( String.format( ProfilesTest.PROFILE, "Yegor64", commander, "do_something", commander, commander ) ) ); final Profile merged = new Profile.Fixed( new XMLDocument( String.format( ProfilesTest.PROFILE, "Bobby", commander, "do_another", commander, commander ) ) ); try { new Profiles().validated(master, merged); Assert.fail("Code above must throw an exception"); } catch (final Profile.ConfigException exception) { MatcherAssert.assertThat( exception.getMessage(), Matchers.is( String.format( ProfilesTest.MESSAGE, "[architect]" ) ) ); } }
Source:
public static void main(String[] args) { if (!(args.length == 1 && !args[0].startsWith("-") || args.length == 2 && (args[0].equals("-q") || args[0].equals("--quiet")) && !args[1].startsWith("-"))) { System.err .println("usage: java edu.illinois.cs.cogcomp.lbj.pos.POSTag [-q] <testing set>\n" + " If -q is specified, the only output is timing and accuracy\n" + " information. Otherwise, the testing set is output with\n" + " extra tags indicating whether each prediction was correct."); System.exit(1); } boolean quiet = args.length == 2; testingFile = args[args.length - 1]; POSTagger tagger = new POSTagger(); BufferedReader in = open(); int correct = 0, incorrect = 0; for (String line = readLine(in); line != null; line = readLine(in)) { LinkedVector sentence = POSBracketToVector.parsePOSBracketForm(line); for (Word word = (Word) sentence.get(0); word != null; word = (Word) word.next) { String label = word.partOfSpeech; word.partOfSpeech = null; String prediction = tagger.discreteValue(word); if (prediction.equals(label)) { ++correct; if (!quiet) System.out.println("+"); } else { ++incorrect; if (!quiet) System.out.println("-[" + label + "]"); } if (!quiet) System.out.println(word + " "); } if (!quiet) System.out.println(""); } System.out.println("Accuracy: " + (100 * correct / (double) (correct + incorrect)) + "%"); }

Target:
public static void main(String[] args) { if (!(args.length == 1 && !args[0].startsWith("-") || args.length == 2 && (args[0].equals("-q") || args[0].equals("--quiet")) && !args[1].startsWith("-"))) { System.err .println("usage: java edu.illinois.cs.cogcomp.lbj.pos.POSTag [-q] <testing set>\n" + " If -q is specified, the only output is timing and accuracy\n" + " information. Otherwise, the testing set is output with\n" + " extra tags indicating whether each prediction was correct."); System.exit(1); } boolean quiet = args.length == 2; testingFile = args[args.length - 1]; POSTagger tagger = new POSTagger(); BufferedReader in = open(); int correct = 0, incorrect = 0; for (String line = readLine(in); line != null; line = readLine(in)) { LinkedVector sentence = POSBracketToVector.parsePOSBracketForm(line); for (Word word = (Word) sentence.get(0); word != null; word = (Word) word.next) { String label = word.partOfSpeech; word.partOfSpeech = null; String prediction = tagger.discreteValue(word); if (prediction.equals(label)) { ++correct; if (!quiet) System.out.print("+"); } else { ++incorrect; if (!quiet) System.out.print("-[" + label + "]"); } if (!quiet) System.out.print(word + " "); } if (!quiet) System.out.print(""); } System.out.println("Accuracy: " + (100 * correct / (double) (correct + incorrect)) + "%"); }
Source:
int staticScore() { if (upper == lower) { return 1; } return upper != Long.MAX_VALUE && lower != Long.MIN_VALUE ? 2 : 3; }

Target:
int staticScore() { if (upper == lower) { return 1; } return !lowerUnbounded && !upperUnbounded ? 2 : 3; }
Source:
public String toString() { String fileName = "No file ("; if (!mediaFiles.isEmpty()) { URI uri = mediaFiles.entrySet().iterator().next().getValue(); fileName = FilenameUtils.getBaseName(uri.getPath()).concat(" ("); } if (type != null) { fileName = type + ' ' + fileName; } return mediaFiles.entrySet().stream().map(Entry::getKey).map(MediaVariant::getUse) .collect(Collectors.joining(", ", fileName, ")")); }

Target:
public String toString() { String fileName = "No file ("; if (!mediaFiles.isEmpty()) { URI uri = mediaFiles.entrySet().iterator().next().getValue(); fileName = FilenameUtils.getBaseName(uri.getPath()).concat(" ("); } if (Objects.nonNull(type)) { fileName = type + ' ' + fileName; } return mediaFiles.entrySet().stream().map(Entry::getKey).map(MediaVariant::getUse) .collect(Collectors.joining(", ", fileName, ")")); }
Source:
public void testPrivateEnum() { testEnumSerializer(PrivateEnum.ONE, PrivateEnum.TWO, PrivateEnum.THREE); }

Target:
public void testPrivateEnum() { testEnumSerializer(PublicEnum.FOO, PublicEnum.BAR, PublicEnum.PETER, PublicEnum.NATHANIEL, PublicEnum.EMMA, PublicEnum.PAULA); }
Source:
private void updateWorkflowInstanceWithTransaction(final WorkflowInstance instance, final WorkflowInstanceAction action, final List<WorkflowInstance> childWorkflows) { transaction.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { updateWorkflowInstance(instance); int parentActionId = insertWorkflowInstanceAction(instance, action); for (WorkflowInstance childTemplate : childWorkflows) { Integer rootWorkflowId = instance.rootWorkflowId != null ? instance.rootWorkflowId : instance.id; WorkflowInstance childWorkflow = new WorkflowInstance.Builder(childTemplate).setRootWorkflowId(rootWorkflowId) .setParentWorkflowId(instance.id).setParentActionId(parentActionId).build(); insertWorkflowInstance(childWorkflow); } } }); }

Target:
private void updateWorkflowInstanceWithTransaction(final WorkflowInstance instance, final WorkflowInstanceAction action, final List<WorkflowInstance> childWorkflows) { transaction.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { updateWorkflowInstance(instance); int parentActionId = insertWorkflowInstanceAction(instance, action); for (WorkflowInstance childTemplate : childWorkflows) { Integer rootWorkflowId = instance.rootWorkflowId == null ? instance.id : instance.rootWorkflowId; WorkflowInstance childWorkflow = new WorkflowInstance.Builder(childTemplate).setRootWorkflowId(rootWorkflowId) .setParentWorkflowId(instance.id).setParentActionId(parentActionId).build(); insertWorkflowInstance(childWorkflow); } } }); }
Source:
private void addingBundle(Bundle bundle) { ScheduledFuture<?> future = scheduler.schedule(new Runnable() { @Override public void run() { processBundle(bundle); } }, 0, TimeUnit.SECONDS); queue.put(bundle, future); }

Target:
private void addingBundle(Bundle bundle) { Future<?> future = scheduler.submit(new Runnable() { @Override public void run() { processBundle(bundle); } }); queue.put(bundle, future); }
Source:
boolean interceptRequest(Request request, Response response) throws Exception; default boolean onRequestInterceptionError(Request request, Response response, Exception e) { String message = "Exception while executing request interceptor " + this.getClass(); Logger log = LoggerFactory.getLogger(this.getClass()); log.error(message, e); response.setEntity(e.getMessage() + " - " + message + this.getClass()) .setMediaType(MediaType.TEXT_PLAIN) .setStatus(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); return false; }

Target:
boolean interceptRequest(Request request, Response response) throws Exception; default boolean onRequestInterceptionError(Request request, Response response, Exception e) { String message = "Exception while executing request interceptor " + this.getClass(); Logger log = LoggerFactory.getLogger(this.getClass()); log.error(message, e); response.setEntity(message) .setMediaType(MediaType.TEXT_PLAIN) .setStatus(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); return false; }
Source:
public void changeMasterEncryptionPassword() { try { certificatesMgmService.checkPassword(currentPassword); } catch (EncryptionMasterPasswordException ex) { MessagesController.addErrorMessage(ex.getMessage()); return; } catch (IOException ex) { MessagesController.addErrorMessage("Error while reading master password file!"); return; } FacesContext context = FacesContext.getCurrentInstance(); HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest(); String userEmail = request.getUserPrincipal().getName(); certificatesMgmService.resetMasterEncryptionPassword(newPassword, userEmail); MessagesController.addInfoMessage("Changing password...", "Check your Inbox for completion status"); }

Target:
public void changeMasterEncryptionPassword() { try { FacesContext context = FacesContext.getCurrentInstance(); HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest(); String userEmail = request.getUserPrincipal().getName(); certificatesMgmService.checkPassword(currentPassword, userEmail); certificatesMgmService.resetMasterEncryptionPassword(newPassword, userEmail); MessagesController.addInfoMessage("Changing password...", "Check your Inbox for completion status"); } catch (EncryptionMasterPasswordException ex) { MessagesController.addErrorMessage(ex.getMessage()); } catch (IOException ex) { MessagesController.addErrorMessage("Error while reading master password file!"); } }
Source:
public void genSchema() throws Exception { String jsonStr = JsonUtilTest.readJson("FullExampleJsonSchema.json"); FullExampleProperties properties = new FullExampleProperties("properties"); properties.init(); System.out.println(JsonUtil.toJson(properties, true)); JsonSchemaGenerator generator = new JsonSchemaGenerator(); assertEquals(jsonStr, generator.genSchema(properties).toString()); }

Target:
public void genSchema() throws Exception { String jsonStr = JsonSchemaUtilTest.readJson("FullExampleJsonSchema.json"); FullExampleProperties properties = new FullExampleProperties("fullexample"); properties.init(); JsonSchemaGenerator generator = new JsonSchemaGenerator(); assertEquals(jsonStr, generator.genSchema(properties, Form.MAIN).toString()); }
Source:
void setAutoHideDiffHeader(boolean hide) { autoHideHeader = hide; if (!hide) { setHeaderVisible(true); } }

Target:
void setAutoHideDiffHeader(boolean hide) { autoHideHeader = hide; if (!hide) { showHeader(true); } }
Source:
public void testMetadataContentRecordV2() throws IOException, MessageFormatException { List<StoreKey> keys = getKeys(60, 5); int chunkSize = ThreadLocalRandom.current().nextInt(1, Integer.MAX_VALUE); long totalSize = (long) keys.size() * chunkSize; ByteBuffer metadataContent = getSerializedMetadataContentV2(chunkSize, totalSize, keys); CompositeBlobInfo compositeBlobInfo = deserializeMetadataContentV2(metadataContent, new MockIdFactory()); Assert.assertEquals("Chunk size doesn't match", chunkSize, compositeBlobInfo.getChunkSize()); Assert.assertEquals("List of keys dont match", keys, compositeBlobInfo.getKeys()); }

Target:
public void testMetadataContentRecordV2() throws IOException, MessageFormatException { List<StoreKey> keys = getKeys(60, 5); int[] chunkSizes = {ThreadLocalRandom.current().nextInt(1, Integer.MAX_VALUE), 15}; long[] totalSizes = {(long) keys.size() * chunkSizes[0], ((long) keys.size() * chunkSizes[1]) - 11}; for (int i = 0; i < chunkSizes.length; i++) { ByteBuffer metadataContent = getSerializedMetadataContentV2(chunkSizes[i], totalSizes[i], keys); CompositeBlobInfo compositeBlobInfo = deserializeMetadataContentV2(metadataContent, new MockIdFactory()); Assert.assertEquals("Chunk size doesn't match", chunkSizes[i], compositeBlobInfo.getChunkSize()); Assert.assertEquals("Total size doesn't match", totalSizes[i], compositeBlobInfo.getTotalSize()); Assert.assertEquals("List of keys dont match", keys, compositeBlobInfo.getKeys()); } }
Source:
public void onBrowserEvent(Context context, Element parent, T value, NativeEvent event, ValueUpdater<T> valueUpdater) { super.onBrowserEvent(context, parent, value, event, valueUpdater); int eventX = event.getClientX(); int eventY = event.getClientY(); if ("click".equals(event.getType())) { EventTarget eventTarget = event.getEventTarget(); if (parent.getFirstChildElement().isOrHasChild(Element.as(eventTarget))) { menuPanelPopup.asPopupPanel().showAndFitToScreen(eventX, eventY); } } if("mouseover".equals(event.getType())) { if (isVisible(value)) { parent.getStyle().setBorderColor("#96B7D6"); } } else { parent.getStyle().setBorderColor("transparent"); } }

Target:
public void onBrowserEvent(Context context, Element parent, T value, NativeEvent event, ValueUpdater<T> valueUpdater) { super.onBrowserEvent(context, parent, value, event, valueUpdater); int eventX = event.getClientX(); int eventY = event.getClientY(); if ("click".equals(event.getType())) { EventTarget eventTarget = event.getEventTarget(); if (parent.getFirstChildElement().isOrHasChild(Element.as(eventTarget))) { menuPanelPopup.asPopupPanel().showAndFitToScreen(eventX, eventY); } } else if("mouseover".equals(event.getType())) { if (isVisible(value)) { parent.getStyle().setBorderColor("#96B7D6"); } } else { parent.getStyle().setBorderColor("transparent"); } }
Source:
private void copyFileToLocalDirectory(String remoteDirectoryPath, F remoteFile, File localDirectory, Session<F> session) throws IOException { String remoteFileName = this.getFilename(remoteFile); String localFileName = this.generateLocalFileName(remoteFileName); String remoteFilePath = remoteDirectoryPath + remoteFileSeparator + remoteFileName; if (!this.isFile(remoteFile)) { if (logger.isDebugEnabled()) { logger.debug("cannot copy, not a file: " + remoteFilePath); } return; } File localFile = new File(localDirectory, localFileName); if (!localFile.exists()) { String tempFileName = localFile.getAbsolutePath() + this.temporaryFileSuffix; File tempFile = new File(tempFileName); InputStream inputStream = null; FileOutputStream fileOutputStream = new FileOutputStream(tempFile); try { session.read(remoteFilePath, fileOutputStream); } catch (Exception e) { if (e instanceof RuntimeException){ throw (RuntimeException) e; } else { throw new MessagingException("Failure occurred while copying from remote to local directory", e); } } finally { try { if (inputStream != null) { inputStream.close(); } } catch (Exception ignored1) { } try { fileOutputStream.close(); } catch (Exception ignored2) { } } if (tempFile.renameTo(localFile)) { if (this.deleteRemoteFiles) { session.remove(remoteFilePath); if (logger.isDebugEnabled()) { logger.debug("deleted " + remoteFilePath); } } } localFile.setLastModified(getModified(remoteFile)); } }

Target:
private void copyFileToLocalDirectory(String remoteDirectoryPath, F remoteFile, File localDirectory, Session<F> session) throws IOException { String remoteFileName = this.getFilename(remoteFile); String localFileName = this.generateLocalFileName(remoteFileName); String remoteFilePath = remoteDirectoryPath + remoteFileSeparator + remoteFileName; if (!this.isFile(remoteFile)) { if (logger.isDebugEnabled()) { logger.debug("cannot copy, not a file: " + remoteFilePath); } return; } File localFile = new File(localDirectory, localFileName); if (!localFile.exists()) { String tempFileName = localFile.getAbsolutePath() + this.temporaryFileSuffix; File tempFile = new File(tempFileName); FileOutputStream fileOutputStream = new FileOutputStream(tempFile); try { session.read(remoteFilePath, fileOutputStream); } catch (Exception e) { if (e instanceof RuntimeException){ throw (RuntimeException) e; } else { throw new MessagingException("Failure occurred while copying from remote to local directory", e); } } finally { try { fileOutputStream.close(); } catch (Exception ignored2) { } } if (tempFile.renameTo(localFile)) { if (this.deleteRemoteFiles) { session.remove(remoteFilePath); if (logger.isDebugEnabled()) { logger.debug("deleted " + remoteFilePath); } } } if (this.preserveTimestamp) { localFile.setLastModified(getModified(remoteFile)); } } }
Source:
NpmRemoteRepositoryConfiguration(MutableNpmRemoteRepositoryConfiguration delegate) { this.lastCnahgeId = delegate.getLastCnahgeId(); }

Target:
NpmRemoteRepositoryConfiguration(MutableNpmRemoteRepositoryConfiguration delegate) { this.lastChangeId = delegate.getLastChangeId(); this.replicateUrl = delegate.getReplicateUrl(); }
Source:
private KeyScanCursor<String> clusterScan(KeyScanCursor<String> cursor, ScanArgs scanArgs) { RedisAdvancedClusterCommands<String, String> commands = (RedisAdvancedClusterCommands<String, String>) connection; List<String> nodeIds; String currentNodeId; if ( cursor == null ) { Set<RedisClusterNode> masterNodes = commands.masters().asMap().keySet(); nodeIds = new ArrayList<>(); for ( RedisClusterNode masterNode : masterNodes ) { nodeIds.add( masterNode.getNodeId() ); } if ( nodeIds.isEmpty() ) { return scan( connection, cursor, scanArgs ); } currentNodeId = nodeIds.get( 0 ); } else { if ( !( cursor instanceof ClusterwideKeyScanCursor ) ) { throw new IllegalArgumentException( "A scan in Redis Cluster mode requires to reuse the resulting cursor from the previous scan invocation" ); } ClusterwideKeyScanCursor<String> clusterKeyScanCursor = (ClusterwideKeyScanCursor<String>) cursor; nodeIds = clusterKeyScanCursor.nodeIds; currentNodeId = getNodeIdForNextScanIteration( nodeIds, clusterKeyScanCursor ); } RedisClusterCommands<String, String> nodeConnection = commands.getConnection( currentNodeId ); KeyScanCursor<String> nodeKeyScanCursor = scan( nodeConnection, cursor, scanArgs ); return new ClusterwideKeyScanCursor( nodeIds, currentNodeId, nodeKeyScanCursor ); }

Target:
private KeyScanCursor<String> clusterScan(KeyScanCursor<String> cursor, ScanArgs scanArgs) { RedisAdvancedClusterCommands<String, String> commands = (RedisAdvancedClusterCommands<String, String>) connection; List<String> nodeIds; String currentNodeId; if ( cursor == null ) { Set<RedisClusterNode> masterNodes = commands.masters().asMap().keySet(); nodeIds = new ArrayList<>(); for ( RedisClusterNode masterNode : masterNodes ) { if ( masterNode.getSlots().isEmpty() ) { continue; } nodeIds.add( masterNode.getNodeId() ); } if ( nodeIds.isEmpty() ) { return scan( connection, cursor, scanArgs ); } currentNodeId = nodeIds.get( 0 ); } else { ClusterwideKeyScanCursor<String> clusterKeyScanCursor = (ClusterwideKeyScanCursor<String>) cursor; nodeIds = clusterKeyScanCursor.nodeIds; currentNodeId = getNodeIdForNextScanIteration( nodeIds, clusterKeyScanCursor ); } RedisClusterCommands<String, String> nodeConnection = commands.getConnection( currentNodeId ); KeyScanCursor<String> nodeKeyScanCursor = scan( nodeConnection, cursor, scanArgs ); return new ClusterwideKeyScanCursor( nodeIds, currentNodeId, nodeKeyScanCursor ); }
Source:
protected void internalUpdateItem(String slaveName, InputRegister[] registers, String itemName) { for (ModbusBindingProvider provider : providers) { if (!provider.providesBindingFor(itemName)) { continue; } ModbusBindingConfig config = provider.getConfig(itemName); if (!config.slaveName.equals(slaveName)) { continue; } ModbusSlave slave = modbusSlaves.get(slaveName); String slaveValueType = slave.getValueType(); double rawDataMultiplier = slave.getRawDataMultiplier(); State newState = extractStateFromRegisters(registers, config.readIndex, slaveValueType); State newStateBoolean = provider.getConfig(itemName) .translateBoolean2State(!newState.equals(DecimalType.ZERO)); if (!UnDefType.UNDEF.equals(newStateBoolean)) { newState = newStateBoolean; } else if ((rawDataMultiplier != 1) && (config.getState() instanceof DecimalType)) { double tmpValue = ((DecimalType) newState).doubleValue() * rawDataMultiplier; newState = new DecimalType(String.valueOf(tmpValue)); } if (slave.isUpdateUnchangedItems() || !newState.equals(config.getState())) { eventPublisher.postUpdate(itemName, newState); config.setState(newState); } } }

Target:
protected void internalUpdateItem(String slaveName, InputRegister[] registers, String itemName) { for (ModbusBindingProvider provider : providers) { if (!provider.providesBindingFor(itemName)) { continue; } ModbusBindingConfig config = provider.getConfig(itemName); if (!config.slaveName.equals(slaveName)) { continue; } ModbusSlave slave = modbusSlaves.get(slaveName); String slaveValueType = slave.getValueType(); double rawDataMultiplier = slave.getRawDataMultiplier(); State newState = extractStateFromRegisters(registers, config.readIndex, slaveValueType); State newStateBoolean = provider.getConfig(itemName) .translateBoolean2State(!newState.equals(DecimalType.ZERO)); if (!UnDefType.UNDEF.equals(newStateBoolean)) { newState = newStateBoolean; } else if ((rawDataMultiplier != 1) && (config.getItemClass().isAssignableFrom(NumberItem.class))) { double tmpValue = ((DecimalType) newState).doubleValue() * rawDataMultiplier; newState = new DecimalType(String.valueOf(tmpValue)); } if (slave.isUpdateUnchangedItems() || !newState.equals(config.getState())) { eventPublisher.postUpdate(itemName, newState); config.setState(newState); } } }
Source:
public License getLicense(ObjectNode node, String location, ParseResult result) { if (node == null) return null; License license = new License(); String value = getString("name", node, true, location, result); license.setName(value); value = getString("url", node, false, location, result); license.setUrl(value); license.setExtensions(new LinkedHashMap<>()); Set<String> keys = getKeys(node); for(String key : keys) { if(key.startsWith("x-")) { license.getExtensions().put(key, Json.mapper().convertValue(node.get(key), Object.class)); } else if (!LICENSE_KEYS.contains(key)) { result.extra(location + ".license", key, node.get(key)); } } return license; }

Target:
public License getLicense(ObjectNode node, String location, ParseResult result) { if (node == null) return null; License license = new License(); String value = getString("name", node, true, location, result); if(StringUtils.isNotBlank(value)) { license.setName(value); } value = getString("url", node, false, location, result); if(StringUtils.isNotBlank(value)) { license.setUrl(value); } Map <String,Object> extensions = getExtensions(node,location,result); if(extensions != null && extensions.size() > 0) { license.setExtensions(extensions); } return license; }
Source:
public SubscribeSpec(String name) { refName = name; isWildcard = name.endsWith("/*"); }

Target:
public SubscribeSpec(String name) { refName = name; isWildcard = RefSpec.isWildcard(name); }
Source:
private static HiveConf createHiveConf(@Nullable String hiveConfDir, @Nullable String hadoopConfDir) { LOG.info("Setting hive conf dir as {}", hiveConfDir); try { HiveConf.setHiveSiteLocation( hiveConfDir == null ? null : Paths.get(hiveConfDir, "hive-site.xml").toUri().toURL()); } catch (MalformedURLException e) { throw new CatalogException( String.format("Failed to get hive-site.xml from %s", hiveConfDir), e); } Configuration hadoopConf = HadoopUtils.getHadoopConfiguration(new org.apache.flink.configuration.Configuration()); for (String possibleHadoopConfPath : HadoopUtils.possibleHadoopConfPaths(new org.apache.flink.configuration.Configuration(), hadoopConfDir)) { File mapredSite = new File(new File(possibleHadoopConfPath), "mapred-site.xml"); if (mapredSite.exists()) { hadoopConf.addResource(new Path(mapredSite.getAbsolutePath())); break; } } return new HiveConf(hadoopConf, HiveConf.class); }

Target:
private static HiveConf createHiveConf(@Nullable String hiveConfDir, @Nullable String hadoopConfDir) { LOG.info("Setting hive conf dir as {}", hiveConfDir); try { HiveConf.setHiveSiteLocation( hiveConfDir == null ? null : Paths.get(hiveConfDir, "hive-site.xml").toUri().toURL()); } catch (MalformedURLException e) { throw new CatalogException( String.format("Failed to get hive-site.xml from %s", hiveConfDir), e); } Configuration hadoopConf = null; if (isNullOrWhitespaceOnly(hadoopConfDir)) { for (String possibleHadoopConfPath : HadoopUtils.possibleHadoopConfPaths(new org.apache.flink.configuration.Configuration())) { hadoopConf = getHadoopConfiguration(possibleHadoopConfPath); if (hadoopConf != null) { break; } } } else { hadoopConf = getHadoopConfiguration(hadoopConfDir); } return new HiveConf(hadoopConf == null ? new Configuration() : hadoopConf, HiveConf.class); }
Source:
public Short getPublishedOwnerLevel() { return publishedOwnerLevel; }

Target:
Short getPublishedOwnerLevel() { return publishedOwnerLevel; }
Source:
private Set<IProject> collectProjects(List<?> elements) { Set<IProject> projects = Sets.newLinkedHashSet(); AdapterFunction<IProject> adapterFunction = AdapterFunction.forType(IProject.class); for (Object element : elements) { IProject project = adapterFunction.apply(element); if (project != null && !GradleProjectNature.isPresentOn(project) && project.getLocation() != null) { IPath location = project.getLocation(); if (location != null) { buildConfigs.add(CorePlugin.configurationManager().createBuildConfiguration(location.toFile(), false, GradleDistribution.fromBuild(), null, false, false)); } } } return projects; }

Target:
private Set<IProject> collectProjects(List<?> elements) { Set<IProject> projects = Sets.newLinkedHashSet(); AdapterFunction<IProject> adapterFunction = AdapterFunction.forType(IProject.class); for (Object element : elements) { IProject project = adapterFunction.apply(element); if (project != null && !GradleProjectNature.isPresentOn(project) && project.getLocation() != null) { projects.add(project); } } return projects; }
Source:
public TcpConnectionSupport getConnection() throws Exception { this.checkActive(); if (this.isSingleUse()) { return obtainConnection(); } else { synchronized(this) { TcpConnectionSupport connection = obtainConnection(); return connection; } } }

Target:
public TcpConnectionSupport getConnection() throws Exception { this.checkActive(); return this.obtainConnection(); }
Source:
private long indexSize(Cache<?, ?> cache) { SearchManager searchManager = Search.getSearchManager(cache); searchManager.refresh(Object.class); return searchManager.search(Object.class) .where(f -> f.matchAll()) .fetchTotalHitCount(); }

Target:
private long indexSize(Cache<?, ?> cache) { QueryFactory queryFactory = Search.getQueryFactory(cache); Query<?> query = queryFactory.create("FROM " + Person.class.getName()); return query.execute().hitCount().orElse(-1); }
Source:
public void close() { flushBuffer(); if (executor != null) { executor.shutdown(); try { boolean e = executor.awaitTermination(closeTimeout, TimeUnit.SECONDS); if (e == false) { LOGGER.debug("Executor service shut down after time out"); } } catch (InterruptedException e) { } executor = null; } }

Target:
public void close() { flushBuffer(); if (executor != null) { executor.shutdown(); try { if (!executor.awaitTermination(closeTimeout, TimeUnit.SECONDS)) { executor.shutdownNow(); if (!executor.awaitTermination(closeTimeout, TimeUnit.SECONDS)) LOGGER.warn("Executor did not terminate"); } } catch (InterruptedException ie) { executor.shutdownNow(); Thread.currentThread().interrupt(); } } }
Source:
protected static SqlParts selectStatementForAndClause(List<Object> clause, String indexName) { if (clause == null || clause.isEmpty()) { return null; } if (indexName == null || indexName.isEmpty()) { return null; } SqlParts where = whereSqlForAndClause(clause, indexName); if (where == null) { return null; } String tableName = IndexManager.tableNameForIndex(indexName); String sql = String.format("SELECT _id FROM \"%s\" WHERE %s", tableName, where.sqlWithPlaceHolders); return SqlParts.partsForSql(sql, where.placeHolderValues); }

Target:
protected static SqlParts selectStatementForAndClause(List<Object> clause, String indexName) { if (clause == null || clause.isEmpty()) { return null; } if (indexName == null || indexName.isEmpty()) { return null; } SqlParts where = whereSqlForAndClause(clause, indexName); if (where == null) { return null; } String tableName = IndexManager.tableNameForIndex(indexName); String sql = String.format(Locale.ENGLISH, "SELECT _id FROM \"%s\" WHERE %s", tableName, where.sqlWithPlaceHolders); return SqlParts.partsForSql(sql, where.placeHolderValues); }
Source:
public void close() { for (List<Interpreter> session : sessions.values()) { for (Interpreter interpreter : session) { try { interpreter.close(); } catch (InterpreterException e) { LOGGER.warn("Fail to close interpreter: " + interpreter.getClassName()); } } } sessions.clear(); }

Target:
public void close() { for (List<Interpreter> session : sessions.values()) { for (Interpreter interpreter : session) { try { interpreter.close(); } catch (InterpreterException e) { LOGGER.warn("Fail to close interpreter: " + interpreter.getClassName(), e); } } } sessions.clear(); }
Source:
public void getSystemProperties() throws Exception { Map<String, String> entries = resolve(managementCenterService.getSystemProperties(members[0])); assertTrue(entries.containsKey("user.dir")); assertNotNull(entries.get("user.dir")); assertFalse(entries.get("user.dir").isEmpty()); }

Target:
public void getSystemProperties() throws Exception { Map<String, String> entries = resolve(managementCenterService.getSystemProperties(members[0])); assertThat(entries.get("user.dir"), not(isEmptyOrNullString())); }
Source:
private List<Long> listStalledVMInTransitionStateOnUpHost(final long hostId, final Date cutTime) { final String sql = "SELECT i.* FROM vm_instance as i, host as h WHERE h.status = 'UP' " + "AND h.id = ? AND i.power_state_update_time < ? AND i.host_id = h.id " + "AND (i.state ='Starting' OR i.state='Stopping' OR i.state='Migrating') " + "AND i.id NOT IN (SELECT w.vm_instance_id FROM vm_work_job AS w JOIN async_job AS j ON w.id = j.id WHERE j.job_status = ?)" + "AND i.removed IS NULL"; final List<Long> l = new ArrayList<Long>(); try (TransactionLegacy txn = TransactionLegacy.open(TransactionLegacy.CLOUD_DB)) { try (PreparedStatement pstmt = txn.prepareAutoCloseStatement(sql)) { pstmt.setLong(1, hostId); pstmt.setString(2, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutTime)); pstmt.setInt(3, JobInfo.Status.IN_PROGRESS.ordinal()); final ResultSet rs = pstmt.executeQuery(); while (rs.next()) { l.add(rs.getLong(1)); } } catch (final SQLException e) { } catch (final Throwable e) { } } return l; }

Target:
private List<Long> listStalledVMInTransitionStateOnUpHost(final long hostId, final Date cutTime) { final String sql = "SELECT i.* FROM vm_instance as i, host as h WHERE h.status = 'UP' " + "AND h.id = ? AND i.power_state_update_time < ? AND i.host_id = h.id " + "AND (i.state ='Starting' OR i.state='Stopping' OR i.state='Migrating') " + "AND i.id NOT IN (SELECT w.vm_instance_id FROM vm_work_job AS w JOIN async_job AS j ON w.id = j.id WHERE j.job_status = ?)" + "AND i.removed IS NULL"; final List<Long> l = new ArrayList<Long>(); TransactionLegacy txn = null; try { txn = TransactionLegacy.open(TransactionLegacy.CLOUD_DB); PreparedStatement pstmt = null; try { pstmt = txn.prepareAutoCloseStatement(sql); pstmt.setLong(1, hostId); pstmt.setString(2, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), cutTime)); pstmt.setInt(3, JobInfo.Status.IN_PROGRESS.ordinal()); final ResultSet rs = pstmt.executeQuery(); while (rs.next()) { l.add(rs.getLong(1)); } } catch (final SQLException e) { } catch (final Throwable e) { } } finally { if (txn != null) { txn.close(); } } return l; }
Source:
private void UpdateOptionsNonLocalFS() { if (hosts == null || allHosts == null) { return; } try { UICommand addHostAction = new UICommand("AddHost", this); if (hosts.size() > 1) { hosts.remove(0); } if (hosts.isEmpty()) { addHostAction.setTitle(ClusterConfigureHostsAction); getCompulsoryActions().add(addHostAction); } else { addHostAction.setTitle(ClusterAddAnotherHostAction); getOptionalActions().add(addHostAction); } if (getEntity().getStoragePoolId() == null) { addHostAction.getExecuteProhibitionReasons().add(ConstantsManager.getInstance() .getConstants() .theClusterIsntAttachedToADcClusterGuide()); addHostAction.setIsExecutionAllowed(false); return; } ArrayList<VDS> availableHosts = new ArrayList<VDS>(); for (VDS vds : allHosts) { if (!getEntity().getId().equals(vds.getVdsGroupId()) && (vds.getStatus() == VDSStatus.Maintenance || vds.getStatus() == VDSStatus.PendingApproval) && vds.getSupportedClusterVersionsSet().contains(getEntity().getcompatibility_version())) { availableHosts.add(vds); } } UICommand selectHostAction = new UICommand("SelectHost", this); if (availableHosts.size() > 0) { if (hosts.isEmpty()) { selectHostAction.setTitle(SelectHostsAction); getCompulsoryActions().add(selectHostAction); } else { selectHostAction.setTitle(SelectHostsAction); getOptionalActions().add(selectHostAction); } } } finally { StopProgress(); } }

Target:
private void UpdateOptionsNonLocalFS() { if (hosts == null || allHosts == null) { return; } if (getEntity() == null) { StopProgress(); return; } UICommand addHostAction = new UICommand("AddHost", this); if (hosts.size() > 1) { hosts.remove(0); } if (hosts.isEmpty()) { addHostAction.setTitle(ClusterConfigureHostsAction); getCompulsoryActions().add(addHostAction); } else { addHostAction.setTitle(ClusterAddAnotherHostAction); getOptionalActions().add(addHostAction); } if (getEntity().getStoragePoolId() == null) { addHostAction.getExecuteProhibitionReasons().add(ConstantsManager.getInstance() .getConstants() .theClusterIsntAttachedToADcClusterGuide()); addHostAction.setIsExecutionAllowed(false); return; } ArrayList<VDS> availableHosts = new ArrayList<VDS>(); for (VDS vds : allHosts) { if (!getEntity().getId().equals(vds.getVdsGroupId()) && (vds.getStatus() == VDSStatus.Maintenance || vds.getStatus() == VDSStatus.PendingApproval) && vds.getSupportedClusterVersionsSet().contains(getEntity().getcompatibility_version())) { availableHosts.add(vds); } } UICommand selectHostAction = new UICommand("SelectHost", this); if (availableHosts.size() > 0) { if (hosts.isEmpty()) { selectHostAction.setTitle(SelectHostsAction); getCompulsoryActions().add(selectHostAction); } else { selectHostAction.setTitle(SelectHostsAction); getOptionalActions().add(selectHostAction); } } StopProgress(); }
Source:
public IStringExpression toStringExpression(@NonNull final String joinOnColumnNameFQ) { return sql.resolvePartial(Evaluatees .mapBuilder() .put(SQL_PARAM_FilterSql, joinOnColumnNameFQ) .put(SQL_PARAM_KeyId, joinOnColumnNameFQ) .put(SQL_PARAM_ShowInactive, SQL_PARAM_VALUE_ShowInactive_Yes) .build()); }

Target:
public IStringExpression toStringExpression(@NonNull final String joinOnColumnNameFQ) { return sql.resolvePartial(Evaluatees .mapBuilder() .put(SQL_PARAM_KeyId, joinOnColumnNameFQ) .put(SQL_PARAM_ShowInactive, SQL_PARAM_VALUE_ShowInactive_Yes) .build()); }
Source:
public void testCompleteData() { intervals = new ArrayList<>(); intervals.add(INTERVAL_JAN_1_4); rows = new ArrayList<Row>(); rows.add(JAN_1_M_10); rows.add(JAN_2_M_10); rows.add(JAN_3_M_10); rows.add(JAN_4_M_10); List<Row> expected_day1 = Collections.singletonList(JAN_1_M_10); List<Row> expected_day2 = Collections.singletonList(JAN_2_M_10); List<Row> expected_day3 = Collections.singletonList(JAN_3_M_10); List<Row> expected_day4 = Collections.singletonList(JAN_4_M_10); Sequence<Row> seq = Sequences.simple(rows); RowBucketIterable rbi = new RowBucketIterable(seq, intervals, ONE_DAY); Iterator<RowBucket> iter = rbi.iterator(); RowBucket actual = iter.next(); assertEquals(JAN_1, actual.getDateTime()); assertEquals(expected_day1, actual.getRows()); actual = iter.next(); assertEquals(JAN_2, actual.getDateTime()); assertEquals(expected_day2, actual.getRows()); actual = iter.next(); assertEquals(JAN_3, actual.getDateTime()); assertEquals(expected_day3, actual.getRows()); actual = iter.next(); assertEquals(JAN_4, actual.getDateTime()); assertEquals(expected_day4, actual.getRows()); }

Target:
public void testCompleteData() { intervals = new ArrayList<>(); intervals.add(INTERVAL_JAN_1_4); rows = new ArrayList<>(); rows.add(JAN_1_M_10); rows.add(JAN_2_M_10); rows.add(JAN_3_M_10); rows.add(JAN_4_M_10); List<Row> expectedDay1 = Collections.singletonList(JAN_1_M_10); List<Row> expectedDay2 = Collections.singletonList(JAN_2_M_10); List<Row> expectedDay3 = Collections.singletonList(JAN_3_M_10); List<Row> expectedDay4 = Collections.singletonList(JAN_4_M_10); Sequence<Row> seq = Sequences.simple(rows); RowBucketIterable rbi = new RowBucketIterable(seq, intervals, ONE_DAY); Iterator<RowBucket> iter = rbi.iterator(); RowBucket actual = iter.next(); assertEquals(JAN_1, actual.getDateTime()); assertEquals(expectedDay1, actual.getRows()); actual = iter.next(); assertEquals(JAN_2, actual.getDateTime()); assertEquals(expectedDay2, actual.getRows()); actual = iter.next(); assertEquals(JAN_3, actual.getDateTime()); assertEquals(expectedDay3, actual.getRows()); actual = iter.next(); assertEquals(JAN_4, actual.getDateTime()); assertEquals(expectedDay4, actual.getRows()); }
Source:
public void preFinishValidateOnFinish() { TaskRepository repository = createTaskRepository(); TestRepositorySettingsPage page = new TestRepositorySettingsPage(repository, true, Status.OK_STATUS); assertTrue(page.ranValidator()); assertTrue(page.preFinish(repository)); page = new TestRepositorySettingsPage(repository, true, Status.CANCEL_STATUS); assertTrue(page.ranValidator()); assertFalse(page.preFinish(repository)); }

Target:
public void preFinishValidateOnFinish() { TaskRepository repository = createTaskRepository(); TestRepositorySettingsPage page = createPage(repository, true, Status.OK_STATUS); assertTrue(page.preFinish(repository)); assertTrue(page.ranValidator()); page = createPage(repository, true, Status.CANCEL_STATUS); assertFalse(page.preFinish(repository)); assertTrue(page.ranValidator()); }
Source:
public AuthenticationResult getTokenForCode(String code) throws IOException, AuthenticationException { String requestMessage; if (mWebRequestHandler == null) { throw new IllegalArgumentException("webRequestHandler"); } try { requestMessage = buildTokenRequestMessage(code); } catch (UnsupportedEncodingException encoding) { Logger.e(TAG, encoding.getMessage(), "", ADALError.ENCODING_IS_NOT_SUPPORTED, encoding); return null; } HashMap<String, String> headers = getRequestHeaders(); return postMessage(requestMessage, headers); }

Target:
public AuthenticationResult getTokenForCode(String code) throws IOException, AuthenticationException { final String requestMessage; if (mWebRequestHandler == null) { throw new IllegalArgumentException("webRequestHandler"); } try { requestMessage = buildTokenRequestMessage(code); } catch (UnsupportedEncodingException encoding) { Logger.e(TAG, encoding.getMessage(), "", ADALError.ENCODING_IS_NOT_SUPPORTED, encoding); return null; } final Map<String, String> headers = getRequestHeaders(); return postMessage(requestMessage, headers); }
Source:
void removePostInfoFromForegroundNotification(@NonNull PostModel post, @Nullable List<MediaModel> media) { sNotificationData.totalPostItems--; if (post.isPage()) { sNotificationData.totalPageItemsIncludedInPostCount--; } if (media != null) { removeMediaInfoFromForegroundNotification(media); } startOrUpdateForegroundNotification(post); }

Target:
void removePostInfoFromForegroundNotification(@NonNull PostModel post, @Nullable List<MediaModel> media) { removePostInfoFromForegroundNotificationData(post, media); startOrUpdateForegroundNotification(post); }
Source:
static FacetOption ofTermStats(final TermStats termStats, final List<String> selectedValues) { return FacetOption.of(termStats.getTerm(), termStats.getProductCount(), selectedValues.contains(termStats.getTerm())); }

Target:
static FacetOption ofTermStats(final TermStats termStats, final List<String> selectedValues) { return FacetOption.of(termStats.getTerm(), firstNonNull(termStats.getProductCount(), 0L), selectedValues.contains(termStats.getTerm())); }
Source:
public synchronized void close() { if (released) { if (logger.isDebugEnabled()){ logger.debug("Session " + targetSession + " already released."); } } else { if (logger.isDebugEnabled()){ logger.debug("Releasing Session " + targetSession + " back to the pool."); } if (this.epoch < CachingSessionFactory.this.sharedSessionEpoch) { if (logger.isDebugEnabled()){ logger.debug("Closing session " + targetSession + " after reset."); } this.targetSession.close(); } pool.releaseItem(targetSession); released = true; } }

Target:
public synchronized void close() { if (released) { if (logger.isDebugEnabled()){ logger.debug("Session " + targetSession + " already released."); } } else { if (logger.isDebugEnabled()){ logger.debug("Releasing Session " + targetSession + " back to the pool."); } if (this.sharedSessionEpoch != CachingSessionFactory.this.sharedSessionEpoch) { if (logger.isDebugEnabled()){ logger.debug("Closing session " + targetSession + " after reset."); } this.targetSession.close(); } pool.releaseItem(targetSession); released = true; } }
Source:
static void startGetLocation() { OneSignal.Log(OneSignal.LOG_LEVEL.DEBUG, "LocationController startGetLocation with lastLocation: " + lastLocation); if (locationHandlerThread == null) locationHandlerThread = new LocationHandlerThread(); try { if (isGooglePlayServicesAvailable(classContext)) { initGoogleLocation(); } else if (isHMSAvailable(classContext)) { initHuaweiLocation(); } else { fireFailedComplete(); } } catch (Throwable t) { OneSignal.Log(OneSignal.LOG_LEVEL.WARN, "Location permission exists but there was an error initializing: ", t); fireFailedComplete(); } }

Target:
static void startGetLocation() { OneSignal.Log(OneSignal.LOG_LEVEL.DEBUG, "LocationController startGetLocation with lastLocation: " + lastLocation); if (locationHandlerThread == null) locationHandlerThread = new LocationHandlerThread(); try { if (isGooglePlayServicesAvailable()) { initGoogleLocation(); } else if (isHMSAvailable()) { initHuaweiLocation(); } else { fireFailedComplete(); } } catch (Throwable t) { OneSignal.Log(OneSignal.LOG_LEVEL.WARN, "Location permission exists but there was an error initializing: ", t); fireFailedComplete(); } }
Source:
public static String mysqlPasswordHash(String string) throws UnsupportedEncodingException{ try { MessageDigest digest = MessageDigest.getInstance(HashAlgorithms.SHA1); digest.update(string.getBytes(StandardCharsets.UTF_8)); byte[] encodedPassword = digest.digest(); digest.update(encodedPassword); encodedPassword = digest.digest(); String hash = new BigInteger(1, encodedPassword).toString(16).toUpperCase(); while(hash.length() < 40){ hash = "0" + hash; } return "*" + hash; } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } }

Target:
public static String mysqlPasswordHash(String string) { try { MessageDigest digest = MessageDigest.getInstance(HashAlgorithms.SHA1); digest.update(string.getBytes(StandardCharsets.UTF_8)); byte[] encodedPassword = digest.digest(); digest.update(encodedPassword); encodedPassword = digest.digest(); String hash = new BigInteger(1, encodedPassword).toString(16).toUpperCase(); while(hash.length() < 40){ hash = "0" + hash; } return "*" + hash; } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } }
Source:
public CommandBuilder<T> withListeners(List<? extends ExecutionListener<?, T>> listeners) { this.listeners = listeners; return this; }

Target:
public CommandBuilder<T> withListeners(List<? extends ExecutionListener<?, T>> listeners) { if (this.listeners == null) { this.listeners = new LinkedList<ExecutionListener<?, T>>(listeners); } else { this.listeners.addAll((Collection) listeners); } return this; }
Source:
public void getReleaseAsset() throws Exception { final ReleaseAssets assets = new RtReleaseAssets( new FakeRequest().withStatus(HttpURLConnection.HTTP_OK) .withBody("{\"id\":1}"), release() ); MatcherAssert.assertThat( assets.get(1).number(), Matchers.is(1) ); }

Target:
public void getReleaseAsset() throws Exception { final ReleaseAssets assets = new RtReleaseAssets( new FakeRequest().withStatus(HttpURLConnection.HTTP_OK) .withBody("{\"id\":3}"), release() ); MatcherAssert.assertThat( assets.get(Tv.THREE).number(), Matchers.is(Tv.THREE) ); }
Source:
public Iterator<ProcessingError> errors() { return errors == null ? Collections.emptyIterator() : errors.iterator(); }

Target:
public Iterator<ProcessingError> errors() { return errors == null ? Collections.<ProcessingError>emptyIterator() : errors.iterator(); }