auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public InputStream anyBlobQuery(QueryBuilder query, Field<InputStream> field) { Connection c; boolean closeConnection = false; try { c = ds.getConnection(); } catch (SQLException ex) { throw new IllegalStateException("Could not connect to DataSource.",ex); } try { LOGGER.log(Level.FINEST, query.toString()); PreparedStatement stmt = query.toStatement(c); try { ResultSet rs = stmt.executeQuery(); try { if(rs.next()) { assert(rs.last()); InputStream is = field.getValue(rs); return is == null ? null : new ClosingInputStreamWrapper(is, c); } else { closeConnection = true; return null; } } finally { rs.close(); } } finally { stmt.close(); } } catch (SQLException ex) { throw new IllegalStateException("BlobQuery Failed", ex); } finally { if (closeConnection) { try { c.close(); } catch (SQLException ex) { throw new IllegalArgumentException("Error while closing connection.",ex); } } } }

Target:
public InputStream anyBlobQuery(QueryBuilder query, Field<InputStream> field) { LOGGER.log(Level.FINEST, query.toString()); Connection c; boolean closeConnection = false; try { c = ds.getConnection(); } catch (SQLException ex) { throw new IllegalStateException("Could not connect to DataSource.",ex); } try { try (PreparedStatement stmt = query.toStatement(c)){ try (ResultSet rs = stmt.executeQuery()) { if(rs.next()) { assert(rs.last()); InputStream is = field.getValue(rs); return is == null ? null : new ClosingInputStreamWrapper(is, c); } else { closeConnection = true; return null; } } } } catch (SQLException ex) { throw new IllegalStateException("BlobQuery Failed", ex); } finally { if (closeConnection) { try { c.close(); } catch (SQLException ex) { throw new IllegalArgumentException("Error while closing connection.",ex); } } } }
Source:
public static UUID makeUUID(byte bytes[]) { long high = 0; long low = 0; if (bytes.length != Utils.UUID_LEN) { throw new IllegalArgumentException("UUID byte field must be 16 bytes long"); } final int bitsPerByte = Byte.SIZE; int bitMask = (1 << bitsPerByte) - 1; for (int i = 0; i < bitsPerByte; i++) { low = (low << bitsPerByte) | (bytes[i + bitsPerByte] & bitMask); high = (high << bitsPerByte) | (bytes[i] & bitMask); } UUID uuid = new UUID(high, low); return uuid; }

Target:
public static UUID makeUUID(byte bytes[]) { long high = 0; long low = 0; if (bytes.length < Utils.UUID_LEN) { throw new IllegalArgumentException("UUID byte field must be 16 bytes long"); } final int bitsPerByte = Byte.SIZE; int bitMask = (1 << bitsPerByte) - 1; for (int i = 0; i < bitsPerByte; i++) { low = (low << bitsPerByte) | (bytes[i + bitsPerByte] & bitMask); high = (high << bitsPerByte) | (bytes[i] & bitMask); } UUID uuid = new UUID(high, low); return uuid; }
Source:
public Statement apply(Statement statement, Description description) { return new Statement() { @Override public void evaluate() throws Throwable { AlluxioProperties props = ServerConfiguration.copyProperties(); try { statement.evaluate(); } finally { FileSystemMaster fsm = mCluster.mLocalAlluxioCluster.getLocalAlluxioMaster().getMasterProcess() .getMaster(FileSystemMaster.class); if (SecurityUtils.isAuthenticationEnabled(ServerConfiguration.global())) { try (AuthenticatedClientUserResource r = new AuthenticatedClientUserResource( fsm.getRootInodeOwner(), ServerConfiguration.global())) { resetFsm(fsm); } } else { resetFsm(fsm); } BlockWorker blkWorker = mCluster.mLocalAlluxioCluster.getWorkerProcess() .getWorker(BlockWorker.class); resetBlockWorker(blkWorker); ServerConfiguration.reset(); props.entrySet() .forEach(e -> { if (e.getValue() == null || e.getValue().equals("")) { ServerConfiguration.unset(e.getKey()); } else { ServerConfiguration.set(e.getKey(), e.getValue()); } }); } } }; }

Target:
public Statement apply(Statement statement, Description description) { return new Statement() { @Override public void evaluate() throws Throwable { AlluxioProperties props = ServerConfiguration.copyProperties(); try { statement.evaluate(); } finally { FileSystemMaster fsm = mCluster.mLocalAlluxioCluster.getLocalAlluxioMaster().getMasterProcess() .getMaster(FileSystemMaster.class); if (SecurityUtils.isAuthenticationEnabled(ServerConfiguration.global())) { try (AuthenticatedClientUserResource r = new AuthenticatedClientUserResource( fsm.getRootInodeOwner(), ServerConfiguration.global())) { resetFsm(fsm); } } else { resetFsm(fsm); } mCluster.mLocalAlluxioCluster.getWorkerProcesses().stream() .map(w -> w.getWorker(BlockWorker.class)) .forEach(blkWorker -> resetBlockWorker(blkWorker)); ServerConfiguration.reset(); props.entrySet() .forEach(e -> { if (e.getValue() == null || e.getValue().equals("")) { ServerConfiguration.unset(e.getKey()); } else { ServerConfiguration.set(e.getKey(), e.getValue()); } }); } } }; }
Source:
private void updateStack(AmazonCloudFormation cfn) throws IOException { String stackName = getStackName(); String cfnTemplateUrl = getCfnTemplateUrl(); List<Parameter> cfnStackParams = getCfnStackParams(); List<Tag> cfnStackTags = getCfnStackTags(); String cfnStackPolicyUrl = getCfnStackPolicyUrl(); File cfnTemplateFile = getCfnTemplateFile(); File cfnStackPolicyFile = getCfnStackPolicyFile(); getLogger().info("Update stack: {}", stackName); UpdateStackRequest req = new UpdateStackRequest() .withStackName(stackName) .withParameters(cfnStackParams) .withTags(cfnStackTags); if (Strings.isNullOrEmpty(cfnTemplateUrl) == false) { req.setTemplateURL(cfnTemplateUrl); getLogger().info("Using template url: {}", cfnTemplateUrl); } else { req.setTemplateBody(FileUtils.readFileToString(cfnTemplateFile)); getLogger().info("Using template file: {}", "$cfnTemplateFile.canonicalPath"); } if (isCapabilityIam()) { Capability selectedCapability = (getUseCapabilityIam() == null) ? Capability.CAPABILITY_IAM : getUseCapabilityIam(); getLogger().info("Using IAM capability: " + selectedCapability); req.setCapabilities(Arrays.asList(selectedCapability.toString())); } if (Strings.isNullOrEmpty(cfnStackPolicyUrl) == false) { req.setStackPolicyURL(cfnStackPolicyUrl); } else { req.setStackPolicyBody(FileUtils.readFileToString(cfnStackPolicyFile)); } UpdateStackResult updateStackResult = cfn.updateStack(req); getLogger().info("Update requested: {}", updateStackResult.getStackId()); }

Target:
private void updateStack(AmazonCloudFormation cfn) throws IOException { String stackName = getStackName(); String cfnTemplateUrl = getCfnTemplateUrl(); File cfnTemplateFile = getCfnTemplateFile(); List<Parameter> cfnStackParams = getCfnStackParams(); List<Tag> cfnStackTags = getCfnStackTags(); String cfnStackPolicyUrl = getCfnStackPolicyUrl(); File cfnStackPolicyFile = getCfnStackPolicyFile(); getLogger().info("Update stack: {}", stackName); UpdateStackRequest req = new UpdateStackRequest() .withStackName(stackName) .withParameters(cfnStackParams) .withTags(cfnStackTags); if (Strings.isNullOrEmpty(cfnTemplateUrl) == false) { req.setTemplateURL(cfnTemplateUrl); getLogger().info("Using template url: {}", cfnTemplateUrl); } else { req.setTemplateBody(FileUtils.readFileToString(cfnTemplateFile)); getLogger().info("Using template file: {}", "$cfnTemplateFile.canonicalPath"); } if (isCapabilityIam()) { Capability selectedCapability = (getUseCapabilityIam() == null) ? Capability.CAPABILITY_IAM : getUseCapabilityIam(); getLogger().info("Using IAM capability: " + selectedCapability); req.setCapabilities(Arrays.asList(selectedCapability.toString())); } if (Strings.isNullOrEmpty(cfnStackPolicyUrl) == false) { req.setStackPolicyURL(cfnStackPolicyUrl); } else if (cfnStackPolicyFile != null) { req.setStackPolicyBody( FileUtils.readFileToString(cfnStackPolicyFile)); } UpdateStackResult updateStackResult = cfn.updateStack(req); getLogger().info("Update requested: {}", updateStackResult.getStackId()); }
Source:
private boolean spawnSnowman(Location location) { if (SNOWMAN_PATTERN.matches(location, true, 0, 0)) { location.getWorld().spawnEntity(location.clone().subtract(-0.5, 2, -0.5), EntityType.SNOWMAN); return true; } return false; }

Target:
private void spawnSnowman(Location location) { if (SNOWMAN_PATTERN.matches(location, true, 0, 0)) { location.getWorld().spawnEntity(location.clone().subtract(-0.5, 2, -0.5), EntityType.SNOWMAN); } }
Source:
public IndexedRecord getCurrent() { result.totalCount++; return factory.convertToAvro(rs); }

Target:
public IndexedRecord getCurrent() { return current; }
Source:
public void close() { log.debug("Closing record collector"); maybeAbortTxn(); if (eosEnabled) { try { producer.close(); } catch (final KafkaException e) { throw new StreamsException("Caught a recoverable exception while closing", e); } producer = null; } checkForException(); }

Target:
public void close() { log.debug("Closing record collector"); maybeAbortTxn(); if (eosEnabled) { try { producer.close(); } catch (final KafkaException e) { throw new StreamsException("Caught a recoverable exception while closing", e); } } checkForException(); }
Source:
public static int getFactionID(SolShip ship){ String shipName = ship.getHull().getHullConfig().getInternalName(); String[] folderList = getFolderList(); for(int i = 0; i < folderList.length; i++) { File factionFile = new File("modules/" + folderList[i] + "/assets/configs/factions.JSON"); JsonParser parser = new JsonParser(); shipName = shipName.replaceFirst(folderList[i], ""); shipName = shipName.replace(":", ""); try { FileReader fileReader = new FileReader(factionFile); JsonArray factionJSON = parser.parse(fileReader).getAsJsonArray(); for(int n = 0; n < factionJSON.size(); n++) { for(int z = 0; z < factionJSON.get(n).getAsJsonObject().get("ships").getAsJsonArray().size(); z++) if(shipName.equals(factionJSON.get(n).getAsJsonObject().get("ships").getAsJsonArray().get(z).getAsString())) { return n; } } } catch (FileNotFoundException e) { e.printStackTrace(); } } return 0; }

Target:
public static int getFactionID(SolShip ship) { String shipName = ship.getHull().getHullConfig().getInternalName(); for(String modulePath: getModuleSet()) { Json factionJson = Assets.getJson(modulePath); Validator.validate(factionJson.getJsonValue(), modulePath); JSONArray factionJsonArray = factionJson.getJsonValue().getJSONArray("factions"); shipName = shipName.replaceAll(".*:", ""); for(int n = 0; n < factionJsonArray.length(); n++) { for(int z = 0; z < factionJsonArray.getJSONObject(n).getJSONArray("ships").length(); z++) { if(shipName.equals(factionJsonArray.getJSONObject(n).getJSONArray("ships").get(z))) { return n; } } } } return 0; }
Source:
public void onLoad() { INSTANCE = this; getDataFolder().mkdirs(); WorldEdit worldEdit = WorldEdit.getInstance(); server = new BukkitServerInterface(this, getServer()); worldEdit.getPlatformManager().register(server); final File delChunks = Paths.get(getDataFolder().getPath(), "startup_delete_chunks.txt").toFile(); if (delChunks.exists()) { ChunkDeleter.runFromFile(delChunks, true); } }

Target:
public void onLoad() { INSTANCE = this; getDataFolder().mkdirs(); WorldEdit worldEdit = WorldEdit.getInstance(); server = new BukkitServerInterface(this, getServer()); worldEdit.getPlatformManager().register(server); Path delChunks = Paths.get(getDataFolder().getPath(), DELCHUNKS_FILE_NAME); if (Files.exists(delChunks)) { ChunkDeleter.runFromFile(delChunks, true); } }
Source:
public String getAppFolderToMonitor() { if (folder == null) { File f = new File("Applications"); folder = f.getAbsolutePath(); } return folder; }

Target:
public String getAppFolderToMonitor() { return folder; }
Source:
public int offer(BBContainer data, long startId, long endId) throws IOException { synchronized (PersistentBinaryDeque.this) { if (m_closed) throw new IOException("GapWriter is closed"); assert(m_requiresId && m_gapHeader != null); assert(startId != PBDSegment.INVALID_ID && endId != PBDSegment.INVALID_ID && endId >= startId); Map.Entry<Long, PBDSegment<M>> entry = m_segments.floorEntry(startId); PBDSegment<M> prev = findValidSegmentFrom((entry == null ? null : entry.getValue()), false, PBDSegment.INVALID_ID, true); if (m_activeSegment!= null && m_activeSegment.m_id != m_segments.lastKey() && (prev == null || prev.getStartId() != m_activeSegment.getStartId())) { finishWrite(m_activeSegment); } if (prev == null && peekFirstSegment() != null) { verifyRangeNotInSegment(peekFirstSegment(), startId, endId); } else if (prev != null) { verifyRangeNotInSegment(prev, startId, endId); Map.Entry<Long, PBDSegment<M>> nextEntry = m_segments.higherEntry(entry.getKey()); PBDSegment<M> next = findValidSegmentFrom((nextEntry == null ? null : nextEntry.getValue()), true, PBDSegment.INVALID_ID, true); if (next != null) { verifyRangeNotInSegment(next, startId, endId); } } Pair<Integer, PBDSegment<M>> result = offerToSegment(prev, data, startId, endId, m_gapHeader, false); m_activeSegment = result.getSecond(); return result.getFirst(); } }

Target:
public int offer(BBContainer data, long startId, long endId) throws IOException { synchronized (PersistentBinaryDeque.this) { if (m_closed) throw new IOException("updateGapHeader call on closed PBD " + m_nonce); assert(m_gapHeader != null); assert(startId != PBDSegment.INVALID_ID && endId >= startId); PBDSegment<M> prev = m_activeSegment; if (m_activeSegment == null || startId != m_activeSegment.getEndId()+1) { Map.Entry<Long, PBDSegment<M>> entry = m_segments.floorEntry(startId); prev = findValidSegmentFrom((entry == null ? null : entry.getValue()), false, true); if (m_activeSegment!= null && m_activeSegment.m_id != m_segments.lastKey()) { finishActiveSegmentWrite(); } } PBDSegment<M> next = null; if (prev == null) { next = findValidSegmentFrom(peekFirstSegment(), true, true); } else { Map.Entry<Long, PBDSegment<M>> nextEntry = m_segments.higherEntry(prev.m_id); next = findValidSegmentFrom((nextEntry == null ? null : nextEntry.getValue()), true, true); } if (prev!=null && startId <= prev.getEndId()) { throw new IllegalArgumentException("PBD segment with range [" + prev.getStartId() + "-" + prev.getEndId() + "] already contains some entries offered in the range ]" + startId + "-" + endId + "]"); } if (next!=null && endId >= next.getStartId()) { throw new IllegalArgumentException("PBD segment with range [" + next.getStartId() + "-" + next.getEndId() + "] already contains some entries offered in the range ]" + startId + "-" + endId + "]"); } if (prev != null && startId != prev.getEndId()+1) { prev = null; } m_filledGap = true; Pair<Integer, PBDSegment<M>> result = offerToSegment(prev, data, startId, endId, m_gapHeader, false); m_activeSegment = result.getSecond(); return result.getFirst(); } }
Source:
public void truncateToSequenceNumber(final long truncationSeqNo) throws IOException { assert(m_memoryDeque.isEmpty()); m_persistentDeque.parseAndTruncate(new BinaryDequeTruncator() { @Override public TruncatorResponse parse(BBContainer bbc, boolean firstObject) { ByteBuffer b = bbc.b(); b.order(ByteOrder.LITTLE_ENDIAN); if (firstObject) { byte version = b.get(); assert(version == EXPORT_BUFFER_VERSION); b.getLong(); int skipSchema = b.getInt() + b.position(); b.position(skipSchema); } final long startSequenceNumber = b.getLong(); if (startSequenceNumber > truncationSeqNo) { return PersistentBinaryDeque.fullTruncateResponse(); } final int tupleCountPos = b.position(); final int tupleCount = b.getInt(); final long lastSequenceNumber = startSequenceNumber + tupleCount - 1; if (lastSequenceNumber <= truncationSeqNo) { return null; } b.getLong(); int offset = 0; while (b.hasRemaining()) { if (startSequenceNumber + offset > truncationSeqNo) { b.limit(b.position()); b.putInt(tupleCountPos, offset - 1); b.position(0); return new ByteBufferTruncatorResponse(b); } offset++; final int rowLength = b.getInt(); if (b.position() + rowLength > b.limit()) { System.out.println(rowLength); } b.position(b.position() + rowLength); } return null; } }); m_persistentDeque.close(); m_persistentDeque = new PersistentBinaryDeque(m_nonce, new VoltFile(m_path), exportLog); m_reader = m_persistentDeque.openForRead(m_nonce); exportLog.info("After truncate, PBD size is " + (m_reader.sizeInBytes() - (8 * m_reader.getNumObjects()))); }

Target:
public void truncateToSequenceNumber(final long truncationSeqNo) throws IOException { assert(m_memoryDeque.isEmpty()); m_persistentDeque.parseAndTruncate(new BinaryDequeTruncator() { @Override public TruncatorResponse parse(BBContainer bbc) { ByteBuffer b = bbc.b(); ByteOrder endianness = b.order(); b.order(ByteOrder.LITTLE_ENDIAN); try { final long startSequenceNumber = b.getLong(); if (startSequenceNumber > truncationSeqNo) { return PersistentBinaryDeque.fullTruncateResponse(); } final int tupleCountPos = b.position(); final int tupleCount = b.getInt(); final long lastSequenceNumber = startSequenceNumber + tupleCount - 1; if (lastSequenceNumber <= truncationSeqNo) { return null; } b.getLong(); int offset = 0; while (b.hasRemaining()) { if (startSequenceNumber + offset > truncationSeqNo) { b.limit(b.position()); b.putInt(tupleCountPos, offset - 1); b.position(0); return new ByteBufferTruncatorResponse(b); } offset++; final int rowLength = b.getInt(); if (b.position() + rowLength > b.limit()) { System.out.println(rowLength); } b.position(b.position() + rowLength); } return null; } finally { b.order(endianness); } } }); m_persistentDeque.close(); StreamTableSchemaSerializer ds = new StreamTableSchemaSerializer( VoltDB.instance().getCatalogContext(), m_streamName); m_persistentDeque = new PersistentBinaryDeque(m_nonce, ds, new VoltFile(m_path), exportLog); m_reader = m_persistentDeque.openForRead(m_nonce); exportLog.info("After truncate, PBD size is " + (m_reader.sizeInBytes() - (8 * m_reader.getNumObjects()))); }
Source:
public void updateProjectAction(ActionEvent e) { CurrentProject project = appContext.getCurrentProject(); if (project == null || !"maven".equals(project.getRootProject().getType())) { e.getPresentation().setEnabledAndVisible(false); return; } Selection<?> selection = projectExplorer.getSelection(); if (selection == null) { e.getPresentation().setEnabledAndVisible(false); return; } e.getPresentation().setVisible(true); e.getPresentation().setEnabled(selection.isSingleSelection() && (selection.getHeadElement() instanceof SourceFolderNode || selection.getHeadElement() instanceof PackageNode)); }

Target:
public void updateProjectAction(ActionEvent e) { CurrentProject project = appContext.getCurrentProject(); if (project == null || !MAVEN.equals(project.getRootProject().getType())) { e.getPresentation().setEnabledAndVisible(false); return; } Selection<?> selection = projectExplorer.getSelection(); if (selection == null) { e.getPresentation().setEnabledAndVisible(false); return; } e.getPresentation().setVisible(true); e.getPresentation().setEnabled(selection.isSingleSelection() && (selection.getHeadElement() instanceof SourceFolderNode || selection.getHeadElement() instanceof PackageNode)); }
Source:
private void createTooltipShell(Shell parent) { final Display display = parent.getDisplay(); if (fTipShell != null && !fTipShell.isDisposed()) { fTipShell.dispose(); } fTipShell = new Shell(parent, SWT.ON_TOP | SWT.TOOL); fTipShell.addDisposeListener(e -> e.display.removeFilter(SWT.MouseMove, fListener)); fTipShell.addDisposeListener(e -> e.display.removeFilter(SWT.FocusOut, fFocusLostListener)); fTipShell.addListener(SWT.Deactivate, e -> { if (fTipShell.isDisposed()) { fTipShell.dispose(); } }); GridLayout gridLayout = new GridLayout(); gridLayout.numColumns = 2; gridLayout.marginWidth = 2; gridLayout.marginHeight = 2; fTipShell.setLayout(gridLayout); fTipShell.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND)); fTipComposite = new Composite(fTipShell, SWT.NONE); fTipComposite.setLayout(new GridLayout(3, false)); setupControl(fTipComposite); }

Target:
private void createTooltipShell(Shell parent) { final Display display = parent.getDisplay(); if (fTipShell != null && !fTipShell.isDisposed()) { fTipShell.dispose(); } fTipShell = new Shell(parent, SWT.ON_TOP | SWT.TOOL); fTipShell.addDisposeListener(e -> e.display.removeFilter(SWT.MouseMove, fListener)); fTipShell.addDisposeListener(e -> e.display.removeFilter(SWT.FocusOut, fFocusLostListener)); fTipShell.addListener(SWT.Deactivate, e -> { if (!fTipShell.isDisposed()) { fTipShell.dispose(); } }); GridLayout gridLayout = new GridLayout(); gridLayout.numColumns = 2; gridLayout.marginWidth = 2; gridLayout.marginHeight = 2; fTipShell.setLayout(gridLayout); fTipShell.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND)); fTipComposite = new Composite(fTipShell, SWT.NONE); fTipComposite.setLayout(new GridLayout(3, false)); setupControl(fTipComposite); }
Source:
public Single<Optional<java.io.File>> getDriveFileAsJavaFile(String fileId, java.io.File downloadLocationFile) { try (InputStream is = driveService.files().get(fileId).setFields("*").executeMediaAsInputStream()) { try (FileOutputStream fileOutputStream = new FileOutputStream(downloadLocationFile)) { byte[] buffer = new byte[BYTE_BUFFER_SIZE]; int read; while ((read = is.read(buffer)) != -1) { fileOutputStream.write(buffer, 0, read); } return Single.just(Optional.of(downloadLocationFile)); } catch (FileNotFoundException e) { Logger.error(DriveServiceHelper.this, "Failed write file with FileNotFoundException: ", e); return Single.error(e); } } catch (GoogleJsonResponseException e) { Logger.error(DriveServiceHelper.this, "Failed write file with GoogleJsonResponseException: ", e); return Single.just(Optional.absent()); } catch (IOException e) { Logger.error(DriveServiceHelper.this, "Failed write file with IOException: ", e); return Single.error(e); } }

Target:
public Single<Optional<java.io.File>> getDriveFileAsJavaFile(String fileId, java.io.File downloadLocationFile) { try (InputStream is = driveService.files().get(fileId).setFields("*").executeMediaAsInputStream()) { try (FileOutputStream fileOutputStream = new FileOutputStream(downloadLocationFile)) { byte[] buffer = new byte[BYTE_BUFFER_SIZE]; int read; while ((read = is.read(buffer)) != -1) { fileOutputStream.write(buffer, 0, read); } return Single.just(Optional.of(downloadLocationFile)); } catch (FileNotFoundException e) { Logger.error(DriveServiceHelper.this, "Failed write file with FileNotFoundException: ", e); return Single.error(e); } } catch (GoogleJsonResponseException e) { Logger.warn(DriveServiceHelper.this, "Failed write file with GoogleJsonResponseException: ", e); return Single.just(Optional.absent()); } catch (IOException e) { Logger.error(DriveServiceHelper.this, "Failed write file with IOException: ", e); return Single.error(e); } }
Source:
private ApplicationManager createSourceAndDeployApp(String appName, File file, String format, String outputDatasetName, Schema schema) throws Exception { String schemaString = null; if (schema != null) { schemaString = schema.toString(); } ETLStage source = new ETLStage( "source", new ETLPlugin("File", BatchSource.PLUGIN_TYPE, ImmutableMap.<String, String>builder() .put(Constants.Reference.REFERENCE_NAME, "TestFile") .put(Properties.File.FILESYSTEM, "Text") .put(Properties.File.PATH, file.getAbsolutePath()) .put(Properties.File.FORMAT, format) .put(Properties.File.IGNORE_NON_EXISTING_FOLDERS, "false") .put("pathField", "file") .put(Properties.File.SCHEMA, schemaString) .build(), null)); ETLStage sink = new ETLStage("sink", MockSink.getPlugin(outputDatasetName)); ETLBatchConfig etlConfig = ETLBatchConfig.builder("* * * * *") .addStage(source) .addStage(sink) .addConnection(source.getName(), sink.getName()) .build(); AppRequest<ETLBatchConfig> appRequest = new AppRequest<>(BATCH_ARTIFACT, etlConfig); ApplicationId appId = NamespaceId.DEFAULT.app(appName + format + "Format"); ApplicationManager appManager = deployApplication(appId, appRequest); return appManager; }

Target:
private ApplicationManager createSourceAndDeployApp(String appName, File file, String format, String outputDatasetName, Schema schema) throws Exception { String schemaString = null; if (schema != null) { schemaString = schema.toString(); } ETLStage source = new ETLStage( "source", new ETLPlugin("File", BatchSource.PLUGIN_TYPE, ImmutableMap.<String, String>builder() .put(Constants.Reference.REFERENCE_NAME, "TestFile") .put(Properties.File.FILESYSTEM, "Text") .put(Properties.File.PATH, file.getAbsolutePath()) .put(Properties.File.FORMAT, format) .put(Properties.File.IGNORE_NON_EXISTING_FOLDERS, "false") .put("pathField", "file") .put(Properties.File.SCHEMA, schemaString) .build(), null)); ETLStage sink = new ETLStage("sink", MockSink.getPlugin(outputDatasetName)); ETLBatchConfig etlConfig = ETLBatchConfig.builder("* * * * *") .addStage(source) .addStage(sink) .addConnection(source.getName(), sink.getName()) .build(); AppRequest<ETLBatchConfig> appRequest = new AppRequest<>(BATCH_ARTIFACT, etlConfig); ApplicationId appId = NamespaceId.DEFAULT.app(appName); ApplicationManager appManager = deployApplication(appId, appRequest); return appManager; }
Source:
public void alertFound(Alert alert) { parentScanner.notifyAlertFound(alert); PluginStats pluginStats = mapPluginStats.get(alert.getPluginId()); if (pluginStats != null) { pluginStats.incAlertCount(); } alertCount++; ExtensionAlert extensionAlertRef = Control.getSingleton().getExtensionLoader().getExtension(ExtensionAlert.class); if (extensionAlertRef != null) { if (extensionAlertRef.isNewAlert(alert) == true) { newAlertCount++; } } }

Target:
public void alertFound(Alert alert) { ExtensionAlert extensionAlertRef = Control.getSingleton().getExtensionLoader().getExtension(ExtensionAlert.class); if (extensionAlertRef.isNewAlert(alert)) { newAlertCount++; } parentScanner.notifyAlertFound(alert); PluginStats pluginStats = mapPluginStats.get(alert.getPluginId()); if (pluginStats != null) { pluginStats.incAlertCount(); } alertCount++; }
Source:
protected void createRawDataHeader(Workbook wb, Sheet baseSheet, Map<QuestionGroupDto, List<QuestionDto>> questionMap ) { int columnIdx = addMetaDataHeaders(baseSheet, !makeRepSheets); addComment(baseSheet); if (questionMap != null) { int offset = ++columnIdx; for (QuestionGroupDto group : orderedGroupList) { if (questionMap.get(group) != null) { if (qgSheetMap.containsKey(group.getKeyId())) { Sheet groupSheet = qgSheetMap.get(group.getKeyId()); int metaEnd = addMetaDataHeaders(groupSheet, true); addComment(groupSheet); writeRawDataGroupHeaders(groupSheet, group, questionMap.get(group), metaEnd + 1); } else { offset = writeRawDataGroupHeaders(baseSheet, group, questionMap.get(group), offset); } } } columnIndexMap.put(DIGEST_COLUMN, offset); } }

Target:
protected void createRawDataHeader(Workbook wb, Sheet baseSheet, Map<QuestionGroupDto, List<QuestionDto>> questionMap ) { int columnIdx = addMetaDataHeaders(baseSheet, !separateSheetsForRepeatableGroups); addComment(baseSheet); if (questionMap != null) { int offset = ++columnIdx; for (QuestionGroupDto group : orderedGroupList) { if (questionMap.get(group) != null) { if (qgSheetMap.containsKey(group.getKeyId())) { Sheet groupSheet = qgSheetMap.get(group.getKeyId()); int metaEnd = addMetaDataHeaders(groupSheet, true); addComment(groupSheet); writeRawDataGroupHeaders(groupSheet, group, questionMap.get(group), metaEnd + 1); } else { offset = writeRawDataGroupHeaders(baseSheet, group, questionMap.get(group), offset); } } } columnIndexMap.put(DIGEST_COLUMN, offset); } }
Source:
public static boolean basesEqual(byte lhs, byte rhs) { if (lhs == rhs) return true; if (lhs > 90) lhs -= 32; if (rhs > 90) rhs -= 32; if ((isValidBase(lhs, VALID_BASES_WITH_N_UPPER) && (isValidBase(rhs, VALID_BASES_WITH_N_UPPER)))) { return lhs == rhs; } final Set<Byte> rightSide = iupacBaseMappings.get(rhs); for (byte b : iupacBaseMappings.get(lhs)) { if (rightSide.contains(b)) { return true; } } return false; }

Target:
public static boolean basesEqual(byte lhs, byte rhs) { return (bases[lhs] & bases[rhs]) > 0; }
Source:
public CreateOnlyResourceOperationsImpl(OkHttpClient client, Config config, String apiGroupName, String apiGroupVersion, String plural, Class<T> subjectAccessRequestClass) { this(new OperationContext().withOkhttpClient(client).withConfig(config), apiGroupName, apiGroupVersion, plural, subjectAccessRequestClass); this.subjectAccessRequestClass = subjectAccessRequestClass; }

Target:
public CreateOnlyResourceOperationsImpl(OkHttpClient client, Config config, String apiGroupName, String apiGroupVersion, String plural, Class<T> subjectAccessRequestClass) { this(new OperationContext().withOkhttpClient(client).withConfig(config), apiGroupName, apiGroupVersion, plural, subjectAccessRequestClass); }
Source:
public TreeWsResponse tree(TreeWsRequest request) { GetRequest get = new GetRequest(path(ACTION_TREE)) .setParam(PARAM_COMPONENT_ID, request.getBaseComponentId()) .setParam(PARAM_COMPONENT, request.getComponent()) .setParam(PARAM_BRANCH, request.getBranch()) .setParam(PARAM_QUALIFIERS, inlineMultipleParamValue(request.getQualifiers())) .setParam(PARAM_STRATEGY, request.getStrategy()) .setParam(Param.PAGE, request.getPage()) .setParam(Param.PAGE_SIZE, request.getPageSize()) .setParam(Param.TEXT_QUERY, request.getQuery()) .setParam(Param.SORT, inlineMultipleParamValue(request.getSort())); return call(get, TreeWsResponse.parser()); }

Target:
public TreeWsResponse tree(TreeWsRequest request) { GetRequest get = new GetRequest(path(ACTION_TREE)) .setParam(PARAM_COMPONENT_ID, request.getBaseComponentId()) .setParam("baseComponentKey", request.getBaseComponentKey()) .setParam(PARAM_COMPONENT, request.getComponent()) .setParam(PARAM_BRANCH, request.getBranch()) .setParam(PARAM_QUALIFIERS, inlineMultipleParamValue(request.getQualifiers())) .setParam(PARAM_STRATEGY, request.getStrategy()) .setParam(Param.PAGE, request.getPage()) .setParam(Param.PAGE_SIZE, request.getPageSize()) .setParam(Param.TEXT_QUERY, request.getQuery()) .setParam(Param.SORT, inlineMultipleParamValue(request.getSort())); return call(get, TreeWsResponse.parser()); }
Source:
public CoupleMbusDeviceByChannelResponseDto execute(final DlmsConnectionHolder conn, final DlmsDevice device, final CoupleMbusDeviceByChannelRequestDataDto requestDto) throws ProtocolAdapterException { LOGGER.info("Retrieving values for mbus channel on meter {}", requestDto.getChannel(), device.getDeviceIdentification()); final List<GetResult> resultList = this.coupleMBusDeviceCommandExecutor.getMBusClientAttributeValues(conn, device, requestDto.getChannel()); return new CoupleMbusDeviceByChannelResponseDto( this.coupleMBusDeviceCommandExecutor.makeChannelElementValues(requestDto.getChannel(), resultList)); }

Target:
public CoupleMbusDeviceByChannelResponseDto execute(final DlmsConnectionHolder conn, final DlmsDevice device, final CoupleMbusDeviceByChannelRequestDataDto requestDto) throws ProtocolAdapterException { LOGGER.info("Retrieving values for mbus channel on device {}", requestDto.getChannel(), device.getDeviceIdentification()); final List<GetResult> resultList = this.coupleMBusDeviceCommandExecutor.getMBusClientAttributeValues(conn, device, requestDto.getChannel()); return new CoupleMbusDeviceByChannelResponseDto( this.coupleMBusDeviceCommandExecutor.makeChannelElementValues(requestDto.getChannel(), resultList)); }
Source:
public Map<String, String> getUserConfig(String loggedInUser) { HashMap<String, String> userConfig = new HashMap<String, String>(); userConfig.put(GrillConfConstants.GRILL_SESSION_CLUSTER_USER, userMap.get(loggedInUser) == null ? hiveConf.get(GrillConfConstants.GRILL_SESSION_USER_RESOLVER_FIXED_VALUE, "grill") : userMap.get(loggedInUser)); return userConfig; }

Target:
public Map<String, String> getUserConfig(String loggedInUser) { return userMap.get(loggedInUser) == null ? userMap.get("*") : userMap.get(loggedInUser); }
Source:
public ZLoop(Context context) { assert (context != null); context = context; pollers = new ArrayList<SPoller>(); timers = new ArrayList<STimer>(); zombies = new ArrayList<Object>(); newTimers = new ArrayList<STimer>(); }

Target:
public ZLoop(Context context) { assert (context != null); this.context = context; pollers = new ArrayList<SPoller>(); timers = new ArrayList<STimer>(); zombies = new ArrayList<Object>(); newTimers = new ArrayList<STimer>(); }
Source:
public AccessControlPolicy[] getEffectivePolicies(String path) throws PathNotFoundException, AccessDeniedException, RepositoryException { if (session.isReadOnly()) { throw new AccessDeniedException("Session is read only"); } AccessControlPolicy[] policies = getPolicies(path); if (policies.length == 0) { return new AccessControlPolicy[]{(AccessControlPolicy) this.getApplicablePolicies(path).next()}; } return policies; }

Target:
public AccessControlPolicy[] getEffectivePolicies(String path) throws PathNotFoundException, AccessDeniedException, RepositoryException { AccessControlPolicy[] policies = getPolicies(path); if (policies.length == 0) { return new AccessControlPolicy[]{(AccessControlPolicy) this.getApplicablePolicies(path).next()}; } return policies; }
Source:
public ComponentBuilder append(BaseComponent component, FormatRetention retention) { BaseComponent previous = parts.get( parts.size() - 1 ); if ( previous == null ) { previous = dummy; dummy = null; } if ( previous != null ) { component.copyFormatting( previous, retention, false ); } parts.add( component ); resetCursor(); return this; }

Target:
public ComponentBuilder append(BaseComponent component, FormatRetention retention) { BaseComponent previous = ( parts.isEmpty() ) ? null : parts.get( parts.size() - 1 ); if ( previous == null ) { previous = dummy; dummy = null; } if ( previous != null ) { component.copyFormatting( previous, retention, false ); } parts.add( component ); resetCursor(); return this; }
Source:
public void testLoadAddresses() { Collection<Address> addresses = provider.loadAddresses(); assertTrue("Expected that at least one address is loaded", addresses.size() > 0); for (Address address : addresses) { assertEquals(PRIVATE_IP_ADDRESS, address.getHost()); } }

Target:
public void testLoadAddresses() { Collection<Address> addresses = provider.loadAddresses(); assertEquals(3, addresses.size()); for (Address address : expectedAddresses.keySet()) { addresses.remove(address); } assertTrue(addresses.isEmpty()); }
Source:
private Boolean isMobile() { final String aClass = driver.findElement(slotSelector).getAttribute("class"); return aClass.contains("is-mobile-device") || aClass.contains("theme-mobile-layout"); }

Target:
private Boolean isMobile() { final String aClass = driver.findElement(slotSelector).getAttribute("class"); return aClass.contains("is-mobile-layout"); }
Source:
protected DefaultDataContainer(int concurrencyLevel, long thresholdSize, EvictionStrategy strategy, EvictionThreadPolicy policy, Equivalence<? super K> keyEquivalence, EntrySizeCalculator<? super K, ? super V> sizeCalculator) { DefaultEvictionListener evictionListener; switch (policy) { case PIGGYBACK: case DEFAULT: evictionListener = new DefaultEvictionListener(); break; default: throw new IllegalArgumentException("No such eviction thread policy " + policy); } EntrySizeCalculator<K, InternalCacheEntry<K, V>> calc = new CacheEntrySizeCalculator<>(sizeCalculator); com.github.benmanes.caffeine.cache.Cache<K, InternalCacheEntry<K, V>> cache = applyListener(Caffeine.newBuilder() .<K, InternalCacheEntry<K, V>>weigher((k, v) -> (int) calc.calculateSize(k, v)) .maximumWeight(thresholdSize), evictionListener) .build(); entries = new CaffeineConcurrentMap<>(cache); }

Target:
protected DefaultDataContainer(int concurrencyLevel, long thresholdSize, EvictionStrategy strategy, EvictionThreadPolicy policy, Equivalence<? super K> keyEquivalence, EntrySizeCalculator<? super K, ? super V> sizeCalculator) { DefaultEvictionListener evictionListener; switch (policy) { case PIGGYBACK: case DEFAULT: evictionListener = new DefaultEvictionListener(); break; default: throw new IllegalArgumentException("No such eviction thread policy " + policy); } EntrySizeCalculator<K, InternalCacheEntry<K, V>> calc = new CacheEntrySizeCalculator<>(sizeCalculator); com.github.benmanes.caffeine.cache.Cache<K, InternalCacheEntry<K, V>> cache = applyListener(Caffeine.newBuilder() .weigher((K k, InternalCacheEntry<K, V> v) -> (int) calc.calculateSize(k, v)) .maximumWeight(thresholdSize), evictionListener) .build(); entries = new CaffeineConcurrentMap<>(cache); }
Source:
public void newProfile() { if (getWindow() != null) { return; } SystemTreeItemModel treeSelectedItem = (SystemTreeItemModel) CommonModel.getInstance().getSystemTree().getSelectedItem(); SystemTreeItemModel treeSelectedDc = treeSelectedItem.getType() == SystemTreeItemType.DataCenter ? treeSelectedItem : null; final VnicProfileModel profileModel = new NewVnicProfileModel(this, ((StoragePool) treeSelectedDc.getEntity()).getcompatibility_version()); setWindow(profileModel); initNetworkList(profileModel); }

Target:
public void newProfile() { if (getWindow() != null) { return; } SystemTreeItemModel treeSelectedItem = (SystemTreeItemModel) CommonModel.getInstance().getSystemTree().getSelectedItem(); SystemTreeItemModel treeSelectedDc = SystemTreeItemModel.findAncestor(SystemTreeItemType.DataCenter, treeSelectedItem); final VnicProfileModel profileModel = new NewVnicProfileModel(this, ((StoragePool) treeSelectedDc.getEntity()).getcompatibility_version()); setWindow(profileModel); initNetworkList(profileModel); }
Source:
public void initialise() { this.playerCamera = worldRenderer.getActiveCamera(); this.shadowMapShader = worldRenderer.getMaterial("engine:prog.shadowMap"); this.renderingConfig = config.getRendering(); renderableWorld.setShadowMapCamera(shadowMapCamera); requireFBO(new FBOConfig(SHADOW_MAP_URN, FBO.Type.NO_COLOR).useDepthBuffer(), shadowMapResolutionDependentFBM); addDesiredStateChange(new BindFBO(SHADOW_MAP_URN, shadowMapResolutionDependentFBM)); addDesiredStateChange(new SetViewportSizeOf(SHADOW_MAP_URN, shadowMapResolutionDependentFBM)); }

Target:
public void initialise() { this.playerCamera = worldRenderer.getActiveCamera(); this.shadowMapShader = worldRenderer.getMaterial("engine:prog.shadowMap"); this.renderingConfig = config.getRendering(); renderableWorld.setShadowMapCamera(shadowMapCamera); requiresFBO(new FBOConfig(SHADOW_MAP, FBO.Type.NO_COLOR).useDepthBuffer(), shadowMapResolutionDependentFBOs); addDesiredStateChange(new BindFBO(SHADOW_MAP, shadowMapResolutionDependentFBOs)); addDesiredStateChange(new SetViewportSizeOf(SHADOW_MAP, shadowMapResolutionDependentFBOs)); }
Source:
public void setUp() throws Exception { strWords = "Foo"; BrickTestUtils.createProjectAndGetStartScript("SpeakAndWaitBrickTest").addBrick(new SpeakAndWaitBrick(strWords)); brickPosition = 1; baseActivityTestRule.launchActivity(null); }

Target:
public void setUp() throws Exception { String testSpeakString = "Foo Baar"; BrickTestUtils.createProjectAndGetStartScript("SpeakAndWaitBrickTest").addBrick(new SpeakAndWaitBrick(testSpeakString)); brickPosition = 1; baseActivityTestRule.launchActivity(null); }
Source:
private Xpp3Dom getPluginConfig(Plugin plugin, Xpp3Dom overrides) { Xpp3Dom config = (overrides != null) ? overrides : configuration(); if (plugin.getConfiguration() == null) { return config; } else { return Xpp3Dom.mergeXpp3Dom(config, (Xpp3Dom)plugin.getConfiguration()); } }

Target:
private Xpp3Dom getPluginConfig(Plugin plugin, Xpp3Dom overrides) { Xpp3Dom config = (overrides != null) ? overrides : configuration(); Xpp3Dom pluginConfig = (Xpp3Dom)plugin.getConfiguration(); if (pluginConfig != null) { config = Xpp3Dom.mergeXpp3Dom(config, pluginConfig); } return config; }
Source:
public static void ensureWritableDir(Path directory) throws IOException { if (!Files.exists(directory)) { Files.createDirectories(directory); } if (!Files.isDirectory(directory)) { throw new IOException("Not a directory: " + directory); } if (!Files.isReadable(directory) || !Files.isWritable(directory)) { throw new IOException("No read or write permissions: " + directory); } }

Target:
public static void ensureWritableDir(Path directory) throws IOException { if (!Files.exists(directory)) { Files.createDirectories(directory); } if (!Files.isDirectory(directory)) { throw new IOException("Not a directory: " + directory); } if (!Files.isReadable(directory) || !Files.isWritable(directory)) { throw new IOException("Missing read or write permissions: " + directory); } }
Source:
private Response processResponse(Response directDebitResponse) { try { DirectDebitSearchResponse response = directDebitResponse.readEntity(DirectDebitSearchResponse.class); List<DirectDebitPaymentForSearch> paymentFromResponse = response .getPayments() .stream() .map(payment -> DirectDebitPaymentForSearch.valueOf( payment, publicApiUriGenerator.getPaymentURI(payment.getPaymentId()) )).collect(Collectors.toList()); HalRepresentation.HalRepresentationBuilder halRepresentation = HalRepresentation.builder() .addProperty("results", paymentFromResponse); return Response.ok().entity(paginationDecorator.decoratePagination(halRepresentation, response, PAYMENT_PATH).build().toString()).build(); } catch (ProcessingException ex) { throw new SearchPaymentsException(ex); } }

Target:
private Response processResponse(Response directDebitResponse) { DirectDebitSearchResponse response; try { response = directDebitResponse.readEntity(DirectDebitSearchResponse.class); } catch (ProcessingException ex) { throw new SearchPaymentsException(ex); } List<DirectDebitPaymentForSearch> paymentFromResponse = response .getPayments() .stream() .map(payment -> DirectDebitPaymentForSearch.valueOf( payment, publicApiUriGenerator.getPaymentURI(payment.getPaymentId()) )).collect(Collectors.toList()); HalRepresentation.HalRepresentationBuilder halRepresentation = HalRepresentation.builder() .addProperty("results", paymentFromResponse); return Response.ok().entity(paginationDecorator.decoratePagination(halRepresentation, response, PAYMENT_PATH).build().toString()).build(); }
Source:
public static Entry deserializeEntry(byte[] data) { ByteBuffer b = ByteBuffer.wrap(data); int version = b.getInt(); int classNameLength = b.getInt(); byte[] classNameBytes = new byte[classNameLength]; b.get(classNameBytes); String className = new String(classNameBytes, StandardCharsets.UTF_8); byte[] encrypted = new byte[data.length - (8 + classNameLength)]; b.get(encrypted); return new Entry(version, className, encrypted); }

Target:
public static Entry deserializeEntry(byte[] data) { ByteIterator bi = ByteIterator.ofBytes(data); int version = bi.getBE32(); int classNameLength = bi.getBE32(); String className = bi.drainToUtf8(classNameLength); byte[] encrypted = bi.drain(); return new Entry(version, className, encrypted); }
Source:
public void shouldFormatAsDesigned() throws IOException { StringBuilder featureBuilder = new StringBuilder(); featureBuilder.append("# language: pt\n"); featureBuilder.append("Funcionalidade: formatar no Cucumber\n"); featureBuilder.append("Cenário: O Cucumber consegue formatar uma tabela incompleta.\n"); featureBuilder.append("Quando eu monto uma tabela como esta:\n"); featureBuilder.append("\t|nome|valor|\n"); featureBuilder.append("\t|a|b|\n"); featureBuilder.append("Então deve formatar corretamente.\n"); String feature = featureBuilder.toString(); List<String> lines = doFormatter(feature); assertEquals("Formatter produces unexpected quantity of lines. ", 8, lines.size()); assertEquals("# language: pt", lines.get(0)); assertEquals("Funcionalidade: formatar no Cucumber", lines.get(1)); assertEquals("", lines.get(2)); assertEquals(" Cenário: O Cucumber consegue formatar uma tabela incompleta.", lines.get(3)); assertEquals(" Quando eu monto uma tabela como esta:", lines.get(4)); assertEquals(" | nome | valor |", lines.get(5)); assertEquals(" | a | b |", lines.get(6)); assertEquals(" Então deve formatar corretamente.", lines.get(7)); }

Target:
public void shouldFormatAsDesigned() throws IOException { StringBuilder featureBuilder = new StringBuilder(); featureBuilder.append("Feature: PrettyFormatter\n"); featureBuilder.append("Scenario: Formmat beautifully\n"); featureBuilder.append("When I have this table:\n"); featureBuilder.append("\t|name|value|\n"); featureBuilder.append("\t|a|b|\n"); featureBuilder.append("Then should formatt beautifully.\n"); String feature = featureBuilder.toString(); List<String> lines = doFormatter(feature); assertEquals("Formatter produces unexpected quantity of lines. ", 7, lines.size()); assertEquals("Feature: PrettyFormatter", lines.get(0)); assertEquals("", lines.get(1)); assertEquals(" Scenario: Formmat beautifully", lines.get(2)); assertEquals(" When I have this table:", lines.get(3)); assertEquals(" | name | value |", lines.get(4)); assertEquals(" | a | b |", lines.get(5)); assertEquals(" Then should formatt beautifully.", lines.get(6)); }
Source:
private InputStream open() throws Exception { URLConnection conn; InputStream in; if (client != null && !"jrt".equals(url.getProtocol())) { TaggedData tag = client.connectTagged(url); conn = tag.getConnection(); in = tag.getInputStream(); } else { conn = url.openConnection(); conn.connect(); in = conn.getInputStream(); } lastModified = conn.getLastModified(); int length = conn.getContentLength(); if (length != -1) { size = length; } return in; }

Target:
private InputStream open() throws Exception { URLConnection conn; InputStream in; if (client != null) { TaggedData tag = client.connectTagged(url); conn = tag.getConnection(); in = tag.getInputStream(); } else { conn = url.openConnection(); conn.connect(); in = conn.getInputStream(); } lastModified = conn.getLastModified(); int length = conn.getContentLength(); if (length != -1) { size = length; } return in; }
Source:
public void testSetGetXAttrCreateReplace() throws Exception { byte[] attributeValue = "one".getBytes(StandardCharsets.UTF_8); String attributeName = "user.someAttribute"; Path testFile = methodPath(); createEmptyFile(testFile, FsPermission.createImmutable(READ_WRITE_PERMISSIONS)); fs.setXAttr(testFile, attributeName, attributeValue, CREATE_FLAG); assertArrayEquals(attributeValue, fs.getXAttr(testFile, attributeName)); try { fs.setXAttr(testFile, attributeName, attributeValue, CREATE_FLAG); fail("Creating an existing xAttr should fail"); } catch (IOException ex) { assertExceptionContains("XAttr: " + attributeName + " already exists.", ex); } }

Target:
public void testSetGetXAttrCreateReplace() throws Exception { byte[] attributeValue = "one".getBytes(StandardCharsets.UTF_8); String attributeName = "user.someAttribute"; Path testFile = methodPath(); createEmptyFile(testFile, FsPermission.createImmutable(READ_WRITE_PERMISSIONS)); fs.setXAttr(testFile, attributeName, attributeValue, CREATE_FLAG); assertArrayEquals(attributeValue, fs.getXAttr(testFile, attributeName)); intercept(IOException.class, () -> fs.setXAttr(testFile, attributeName, attributeValue, CREATE_FLAG)); }
Source:
protected boolean handleSelectionExpending( int keyEventKeyCode, InputConnection ic, int globalSelectionStartPosition, int globalCursorPosition) { if (mArrowSelectionState && ic != null) { switch (keyEventKeyCode) { case KeyEvent.KEYCODE_DPAD_LEFT: final String toLeft = ic.getTextBeforeCursor(8, 0).toString(); if (toLeft.length() == 0) { ic.setSelection(globalSelectionStartPosition, globalCursorPosition); } else { ic.setSelection( globalSelectionStartPosition - Character.charCount( toLeft.codePointBefore(toLeft.length())), globalCursorPosition); } return true; case KeyEvent.KEYCODE_DPAD_RIGHT: final String toRight = ic.getTextAfterCursor(8, 0).toString(); if (toRight.length() == 0) { ic.setSelection(globalSelectionStartPosition, globalCursorPosition); } else { ic.setSelection( globalSelectionStartPosition, globalCursorPosition + Character.charCount(toRight.codePointAt(0))); } return true; default: mArrowSelectionState = false; } } return false; }

Target:
protected boolean handleSelectionExpending( int keyEventKeyCode, InputConnection ic, int globalSelectionStartPosition, int globalCursorPosition) { if (mArrowSelectionState && ic != null) { switch (keyEventKeyCode) { case KeyEvent.KEYCODE_DPAD_LEFT: final String toLeft = ic.getTextBeforeCursor(MAX_CHARS_PER_CODEPOINT, 0).toString(); if (toLeft.length() == 0) { ic.setSelection(globalSelectionStartPosition, globalCursorPosition); } else { ic.setSelection( globalSelectionStartPosition - Character.charCount( toLeft.codePointBefore(toLeft.length())), globalCursorPosition); } return true; case KeyEvent.KEYCODE_DPAD_RIGHT: final String toRight = ic.getTextAfterCursor(MAX_CHARS_PER_CODEPOINT, 0).toString(); if (toRight.length() == 0) { ic.setSelection(globalSelectionStartPosition, globalCursorPosition); } else { ic.setSelection( globalSelectionStartPosition, globalCursorPosition + Character.charCount(toRight.codePointAt(0))); } return true; default: mArrowSelectionState = false; } } return false; }