auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected HashMap<XPathExpression, ArrayList<String>> loadConfig(String filename) throws XPathExpressionException { HashMap<XPathExpression, ArrayList<String>> configMap = new HashMap<XPathExpression, ArrayList<String>>(); FileInputStream fstream; try { fstream = new FileInputStream(filename); } catch (FileNotFoundException e) { log.warn("XPATH Extractor config file not found: {}" , filename); e.printStackTrace(); return null; } DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; try { while ((strLine = br.readLine()) != null) { strLine = strLine.trim(); if (strLine.matches("^#.*")) { continue; } if (strLine.length() == 0) { continue; } String fieldName = strLine.split(",")[0]; int offset = fieldName.length() + 1; String strXPath = strLine.substring(offset, strLine.length()); XPathExpression xPath = xpath.compile(strXPath); if (debug) { log.info("Adding XPATH Maps To : {}",strXPath , fieldName); } if (configMap.containsKey(xPath)) { configMap.get(xPath).add(fieldName); } else { ArrayList<String> fields = new ArrayList<String>(); fields.add(fieldName); configMap.put(xPath, fields); } } } catch (IOException e) { log.warn("IO Exception reading from file : {}" , filename, e); return configMap; } try { br.close(); } catch (IOException e) { log.warn("Exception occured when trying to close the config file.. {}", e); } return configMap; }

Target:
protected HashMap<XPathExpression, ArrayList<String>> loadConfig(String filename) throws XPathExpressionException { HashMap<XPathExpression, ArrayList<String>> configMap = new HashMap<XPathExpression, ArrayList<String>>(); FileInputStream fstream; try { fstream = new FileInputStream(filename); } catch (FileNotFoundException e) { log.warn("XPATH Extractor config file not found: {}" , filename, e); return null; } DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; try { while ((strLine = br.readLine()) != null) { strLine = strLine.trim(); if (strLine.matches("^#.*")) { continue; } if (strLine.length() == 0) { continue; } String fieldName = strLine.split(",")[0]; int offset = fieldName.length() + 1; String strXPath = strLine.substring(offset, strLine.length()); XPathExpression xPath = xpath.compile(strXPath); if (debug) { log.info("Adding XPATH Maps To : {}",strXPath , fieldName); } if (configMap.containsKey(xPath)) { configMap.get(xPath).add(fieldName); } else { ArrayList<String> fields = new ArrayList<String>(); fields.add(fieldName); configMap.put(xPath, fields); } } } catch (IOException e) { log.warn("IO Exception reading from file {}" , filename, e); return configMap; } try { br.close(); } catch (IOException e) { log.warn("Exception occured when trying to close the config file.", e); } return configMap; }
Source:
public View getView(int position, View convertView, ViewGroup parent) { Contest contest = getItem(position); ViewHolder viewHolder; if (convertView == null) { viewHolder = new ViewHolder(); LayoutInflater inflater = LayoutInflater.from(getContext()); convertView = inflater.inflate(R.layout.contest_list_item, parent, false); viewHolder.title = (TextView) convertView.findViewById(R.id.contest_list_item_title); viewHolder.subTitle = (TextView) convertView.findViewById(R.id.contest_list_item_subtitle); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } if (contest.type.equals("Referendum")) { if (contest.referendumTitle != null && !contest.referendumTitle.isEmpty()) { viewHolder.title.setText(contest.referendumTitle); } else { viewHolder.title.setVisibility(View.GONE); } if (contest.referendumSubtitle != null && !contest.referendumSubtitle.isEmpty()) { viewHolder.subTitle.setText(contest.referendumSubtitle); } else { viewHolder.subTitle.setVisibility(View.GONE); } } else { if (contest.office != null && !contest.office.isEmpty()) { viewHolder.title.setText(contest.office); } else { viewHolder.title.setVisibility(View.GONE); } if (electionName != null && !electionName.isEmpty()) { viewHolder.subTitle.setText(electionName); } else { viewHolder.subTitle.setVisibility(View.GONE); } } return convertView; }

Target:
public View getView(int position, View convertView, ViewGroup parent) { Contest contest = getItem(position); ViewHolder viewHolder; if (convertView == null) { viewHolder = new ViewHolder(); LayoutInflater inflater = LayoutInflater.from(getContext()); convertView = inflater.inflate(R.layout.contest_list_item, parent, false); viewHolder.title = (TextView) convertView.findViewById(R.id.contest_list_item_title); viewHolder.subTitle = (TextView) convertView.findViewById(R.id.contest_list_item_subtitle); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } if (contest.type.equals("Referendum")) { setTextView(viewHolder.title, contest.referendumTitle); setTextView(viewHolder.subTitle, contest.referendumSubtitle); } else { setTextView(viewHolder.title, contest.office); setTextView(viewHolder.subTitle, electionName); } return convertView; }
Source:
public void run() { this.thread = Thread.currentThread(); while ( true ) { try { if (queue.peek() instanceof HeartbeatRowMap) { RowMap row = queue.take(); this.push(row); } else if (connectionListener.isNatsRunning()){ RowMap row = queue.take(); this.push(row); } } catch ( Exception e ) { LOGGER.info("Error: ", e); } } }

Target:
public void run() { int attempts = 0; try { Thread.sleep(1000L); while ( true ) { if (connectionListener.isNatsRunning()){ attempts = 0; RowMap row = queue.take(); this.push(row); } else { if (queue.peek() instanceof HeartbeatRowMap) { RowMap row = queue.take(); this.push(row); } if (attempts < natsMaxAttempts) { long sleepTime = (long) (Math.pow(2, attempts++) * 1000); Thread.sleep(sleepTime); } else { this.context.terminate(new RuntimeException("Nats Disconnected")); return; } } } } catch ( Exception e ) { LOGGER.info("Error: ", e); } }
Source:
protected StatusRow lockStatusRow(UUID queryId) { try (Statement stmt = connection.createStatement()) { ResultSet rs = stmt.executeQuery(String.format(ENGLISH, "SELECT completed_at FROM %s WHERE query_id = '%s' FOR UPDATE", escapeIdent(statusTableName), queryId.toString()) ); if (rs.next()) { Timestamp completedAt = rs.getTimestamp(1); if (rs.wasNull()) { return StatusRow.LOCKED_NOT_COMPLETED; } else { return StatusRow.LOCKED_COMPLETED; } } else { return StatusRow.NOT_EXISTS; } } catch (SQLException ex) { throw new DatabaseException("Failed to lock a status row", ex); } }

Target:
protected StatusRow lockStatusRow(UUID queryId) { try (Statement stmt = connection.createStatement()) { ResultSet rs = stmt.executeQuery(String.format(ENGLISH, "SELECT completed_at FROM %s WHERE query_id = '%s' FOR UPDATE", escapeIdent(statusTableName), queryId.toString()) ); if (rs.next()) { rs.getTimestamp(1); if (rs.wasNull()) { return StatusRow.LOCKED_NOT_COMPLETED; } else { return StatusRow.LOCKED_COMPLETED; } } else { return StatusRow.NOT_EXISTS; } } catch (SQLException ex) { throw new DatabaseException("Failed to lock a status row", ex); } }
Source:
private void createNote(NotebookSocket conn, HashSet<String> userAndRoles, Notebook notebook, Message message) throws IOException { AuthenticationInfo subject = new AuthenticationInfo(message.principal); try { Note note = notebook.createNote(subject); note.addParagraph(); if (message != null) { String noteName = (String) message.get("name"); if (noteName == null || noteName.isEmpty()){ noteName = "Note " + note.getId(); } note.setName(noteName); } note.persist(subject); addConnectionToNote(note.getId(), (NotebookSocket) conn); conn.send(serializeMessage(new Message(OP.NEW_NOTE).put("note", note))); } catch (FileSystemException e) { LOG.error("Exception from createNote", e); conn.send(serializeMessage(new Message(OP.ERROR_INFO).put("info", "Oops! There is something wrong with the notebook file system. " + "Please check the logs for more details."))); return; } broadcastNoteList(subject); }

Target:
private void createNote(NotebookSocket conn, HashSet<String> userAndRoles, Notebook notebook, Message message) throws IOException { AuthenticationInfo subject = new AuthenticationInfo(message.principal); try { Note note = null; String defaultInterpreterId = (String) message.get("defaultInterpreterId"); if (!StringUtils.isEmpty(defaultInterpreterId)) { List<String> interpreterSettingIds = new LinkedList<>(); interpreterSettingIds.add(defaultInterpreterId); for (String interpreterSettingId : notebook.getInterpreterFactory(). getDefaultInterpreterSettingList()) { if (!interpreterSettingId.equals(defaultInterpreterId)) { interpreterSettingIds.add(interpreterSettingId); } } note = notebook.createNote(interpreterSettingIds, subject); } else { note = notebook.createNote(subject); } note.addParagraph(); if (message != null) { String noteName = (String) message.get("name"); if (StringUtils.isEmpty(noteName)) { noteName = "Note " + note.getId(); } note.setName(noteName); } note.persist(subject); addConnectionToNote(note.getId(), (NotebookSocket) conn); conn.send(serializeMessage(new Message(OP.NEW_NOTE).put("note", note))); } catch (FileSystemException e) { LOG.error("Exception from createNote", e); conn.send(serializeMessage(new Message(OP.ERROR_INFO).put("info", "Oops! There is something wrong with the notebook file system. " + "Please check the logs for more details."))); return; } broadcastNoteList(subject, userAndRoles); }
Source:
public List<String> getNegativePriorityScoreReasonsFromDB(DBObject priorityReasons) { List<String> negativeScoreReasons = new ArrayList<>(); Optional<List<String>> negativeReasons = Optional.of(TranslatorUtils .toList(priorityReasons, NEGATIVE_REASONS_KEY)); if (negativeReasons.isPresent()) { Iterator<String> negativeReasonsIterator = negativeReasons.get().iterator(); while (negativeReasonsIterator.hasNext()) { negativeScoreReasons.add(negativeReasonsIterator.next()); } return negativeScoreReasons; } else { return negativeScoreReasons; } }

Target:
public List<String> getNegativePriorityScoreReasonsFromDB(DBObject priorityReasons) { List<String> negativeScoreReasons = Lists.newArrayList(); Optional<List<String>> negativeReasons = Optional.of(TranslatorUtils .toList(priorityReasons, NEGATIVE_REASONS_KEY)); if (negativeReasons.isPresent()) { Iterator<String> negativeReasonsIterator = negativeReasons.get().iterator(); while (negativeReasonsIterator.hasNext()) { negativeScoreReasons.add(negativeReasonsIterator.next()); } return negativeScoreReasons; } else { return negativeScoreReasons; } }
Source:
public List<Tree.Kind> nodesToVisit() { return ImmutableList.of(Tree.Kind.CLASS); }

Target:
public List<Tree.Kind> nodesToVisit() { return Collections.singletonList(Tree.Kind.CLASS); }
Source:
public void returnsLatestCacheKeyForOldCacheKeys() throws InvalidAcceptorCacheKeyException { AcceptorCache cache = cache(ImmutableMap.of()); AcceptorCacheKey newCacheKey = cache.getAllUpdates().newCacheKey(); cache.updateSequenceNumbers(ImmutableSet.of(WithSeq.of(20L, Client.of("client1")))); AcceptorCacheKey newCacheKeyAfterFirstUpdate = cache.getAllUpdates().newCacheKey(); cache.updateSequenceNumbers(ImmutableSet.of(WithSeq.of(25L, Client.of("client4")))); AcceptorCacheKey newCacheKeyAfterSecondUpdate = cache.getAllUpdates().newCacheKey(); assertThat(cache.updatesSinceCacheKey(newCacheKey)) .map(AcceptorCacheDigest::newCacheKey) .as("asking with first cache key after two updates should return latest cache key") .contains(newCacheKeyAfterSecondUpdate); assertThat(cache.updatesSinceCacheKey(newCacheKeyAfterFirstUpdate)) .map(AcceptorCacheDigest::newCacheKey) .as("asking with second cache key after one update should also return latest cache key") .contains(newCacheKeyAfterSecondUpdate); assertThat(cache.updatesSinceCacheKey(newCacheKeyAfterSecondUpdate)) .as("no updates past this cache key as this is the latest cache key, return empty") .isEmpty(); }

Target:
public void returnsLatestCacheKeyForOldCacheKeys() throws InvalidAcceptorCacheKeyException { AcceptorCache cache = cache(ImmutableMap.of()); AcceptorCacheKey initialCacheKey = cache.getAllUpdates().newCacheKey(); cache.updateSequenceNumbers(ImmutableSet.of(WithSeq.of(20L, Client.of("client1")))); AcceptorCacheKey cacheKeyAfterFirstUpdate = cache.getAllUpdates().newCacheKey(); cache.updateSequenceNumbers(ImmutableSet.of(WithSeq.of(25L, Client.of("client4")))); AcceptorCacheKey cacheKeyAfterSecondUpdate = cache.getAllUpdates().newCacheKey(); assertThat(cache.updatesSinceCacheKey(initialCacheKey)) .map(AcceptorCacheDigest::newCacheKey) .as("asking with first cache key after two updates should return latest cache key") .contains(cacheKeyAfterSecondUpdate); assertThat(cache.updatesSinceCacheKey(cacheKeyAfterFirstUpdate)) .map(AcceptorCacheDigest::newCacheKey) .as("asking with second cache key after one update should also return latest cache key") .contains(cacheKeyAfterSecondUpdate); assertThat(cache.updatesSinceCacheKey(cacheKeyAfterSecondUpdate)) .as("no updates past this cache key as this is the latest cache key, return empty") .isEmpty(); }
Source:
public VCardBuilder addAdr(final Map parameters, final List values) { properties.add(new VCardProperty("adr", parameters, "text", (List) getAdrTextOrDefault(values))); return this; }

Target:
public VCardBuilder addAdr(final Map parameters, final List values) { properties.add(new VCardProperty("adr", parameters, "text", getAdrTextOrDefault(values))); return this; }
Source:
private Properties getKafkaProperties(Stage.Context context) { Properties props = new Properties(); props.putAll(conf.kafkaOptions); props.setProperty("bootstrap.servers", conf.brokerURI); props.setProperty("group.id", conf.consumerGroup); props.setProperty("max.poll.records", String.valueOf(batchSize)); props.setProperty(KafkaConstants.KEY_DESERIALIZER_CLASS_CONFIG, conf.keyDeserializer.getKeyClass()); props.setProperty(KafkaConstants.VALUE_DESERIALIZER_CLASS_CONFIG, conf.valueDeserializer.getValueClass()); props.setProperty(KafkaConstants.CONFLUENT_SCHEMA_REGISTRY_URL_CONFIG, StringUtils.join(conf.dataFormatConfig.schemaRegistryUrls, ",")); if(conf.enableAutoCommitOffset) { props.setProperty(KafkaConstants.AUTO_COMMIT_OFFEST, "true"); props.setProperty(KafkaConstants.AUTO_COMMIT_INTERVAL, String.valueOf(conf.autoCommitInterval)); } else { props.setProperty(KafkaConstants.AUTO_COMMIT_OFFEST, "false"); } if(context.isPreview()) { props.setProperty(KafkaConstants.AUTO_OFFSET_RESET_CONFIG, KafkaConstants.AUTO_OFFSET_RESET_PREVIEW_VALUE); } return props; }

Target:
private Properties getKafkaProperties(Stage.Context context) { Properties props = new Properties(); props.putAll(conf.kafkaOptions); props.setProperty("bootstrap.servers", conf.brokerURI); props.setProperty("group.id", conf.consumerGroup); props.setProperty("max.poll.records", String.valueOf(batchSize)); props.setProperty(KafkaConstants.KEY_DESERIALIZER_CLASS_CONFIG, conf.keyDeserializer.getKeyClass()); props.setProperty(KafkaConstants.VALUE_DESERIALIZER_CLASS_CONFIG, conf.valueDeserializer.getValueClass()); props.setProperty(KafkaConstants.CONFLUENT_SCHEMA_REGISTRY_URL_CONFIG, StringUtils.join(conf.dataFormatConfig.schemaRegistryUrls, ",")); props.setProperty(KafkaConstants.AUTO_COMMIT_OFFEST, "false"); if(context.isPreview()) { props.setProperty(KafkaConstants.AUTO_OFFSET_RESET_CONFIG, KafkaConstants.AUTO_OFFSET_RESET_PREVIEW_VALUE); } return props; }
Source:
public BlueZBluetoothDevice(BlueZBridgeHandler adapter, BluetoothAddress address, String name) { super(adapter, address); this.name = name; logger.debug("Creating BlueZ device with address '{}'", address); scheduler.submit(() -> { tinyb.BluetoothDevice tinybDevice = findTinybDevice(address.toString()); if (tinybDevice != null) { setTinybDevice(tinybDevice); } }); }

Target:
public BlueZBluetoothDevice(BlueZBridgeHandler adapter, BluetoothAddress address, String name) { super(adapter, address); this.name = name; logger.debug("Creating BlueZ device with address '{}'", address); }
Source:
public static Optional<ObaRegion> getClosestRegion(Location l) { log.debug("Invoked getClosestRegion() with location " + l.toString()); ObaRegionsResponse response = ObaRegionsRequest.newRequest().call(); ArrayList<ObaRegion> regions = new ArrayList<>(Arrays.asList(response.getRegions())); return Optional.of(RegionUtils.getClosestRegion( regions, l, true)); }

Target:
public static Optional<ObaRegion> getClosestRegion(Location l) { log.debug("Invoked getClosestRegion() with location " + l.toString()); ObaRegionsResponse response = ObaRegionsRequest.newRequest().call(); ArrayList<ObaRegion> regions = new ArrayList<>(Arrays.asList(response.getRegions())); return Optional.ofNullable(RegionUtils.getClosestRegion( regions, l, true)); }
Source:
private static Bucket storage() { final String key = Manifests.read("Netbout-S3Key"); final com.jcabi.s3.Region region; if (key.matches("[0-9A-Z]{20}")) { region = new com.jcabi.s3.Region.Simple( key, Manifests.read("Netbout-S3Secret") ); } else { final Path temp; try { temp = Files.createTempDirectory( DyAttachment.class.getSimpleName() ); temp.toFile().deleteOnExit(); } catch (final IOException ex) { throw new IllegalStateException(ex); } region = new MkRegion(temp.toFile()); } return region.bucket(Manifests.read("Netbout-S3Bucket")); }

Target:
private static Bucket storage() { final String key = Manifests.read("Netbout-S3Key"); final com.jcabi.s3.Region region; if (key.matches("[0-9A-Z]{20}")) { region = new com.jcabi.s3.Region.Simple( key, Manifests.read("Netbout-S3Secret") ); } else { final File temp; try { temp = Files.createTempDirectory( DyAttachment.class.getSimpleName() ).toFile(); temp.deleteOnExit(); } catch (final IOException ex) { throw new IllegalStateException(ex); } region = new MkRegion(temp); } return region.bucket(Manifests.read("Netbout-S3Bucket")); }
Source:
public static DatabaseInfo extractDatabaseInfo( Map<String,Value> metadata ) { Value dbValue = metadata.get( "db" ); if ( dbValue == null || dbValue.isNull() || !dbValue.hasType( TYPE_SYSTEM.STRING() ) ) { return DEFAULT_DATABASE_INFO; } else { return new InternalDatabaseInfo( dbValue.asString() ); } }

Target:
public static DatabaseInfo extractDatabaseInfo( Map<String,Value> metadata ) { Value dbValue = metadata.get( "db" ); if ( dbValue == null || dbValue.isNull() ) { return DEFAULT_DATABASE_INFO; } else { return new InternalDatabaseInfo( dbValue.asString() ); } }
Source:
public static void addDefaultResourceBundle(String resourceBundleName) { ClassLoader ccl = null; synchronized (classLoaderMap) { ccl = getThreadCurrentThreadGetContextClassLoader(); List<String> bundles = classLoaderMap.get(ccl.hashCode()); if (bundles == null) { bundles = new ArrayList<String>(); classLoaderMap.put(ccl.hashCode(), bundles); bundles.add(XWORK_MESSAGES_BUNDLE); } bundles.remove(resourceBundleName); bundles.add(0, resourceBundleName); } if (LOG.isDebugEnabled()) { LOG.debug("Added default resource bundle '" + resourceBundleName + "' to default resource bundles for the following classloader " + ccl.toString()); } }

Target:
public static void addDefaultResourceBundle(String resourceBundleName) { ClassLoader ccl = null; synchronized (XWORK_MESSAGES_BUNDLE) { ccl = getCurrentThreadContextClassLoader(); List<String> bundles = classLoaderMap.get(ccl.hashCode()); if (bundles == null) { bundles = new ArrayList<String>(); classLoaderMap.put(ccl.hashCode(), bundles); bundles.add(XWORK_MESSAGES_BUNDLE); } bundles.remove(resourceBundleName); bundles.add(0, resourceBundleName); } if (LOG.isDebugEnabled()) { LOG.debug("Added default resource bundle '{}' to default resource bundles for the following classloader '{}'", resourceBundleName, ccl.toString()); } }
Source:
public void testConsistentIdConfiguredInIgniteCfg() throws Exception { defConsistentId = "IgniteCfg consistent id"; Ignite ignite = startGrid(0); assertEquals(defConsistentId, ignite.configuration().getConsistentId()); assertEquals(defConsistentId, ignite.cluster().localNode().consistentId()); info("Consistent id in that case: " + ignite.cluster().localNode().consistentId()); }

Target:
public void testConsistentIdConfiguredInIgniteCfg() throws Exception { defConsistentId = "IgniteCfg consistent id"; Ignite ignite = startGrid(0); assertEquals(defConsistentId, ignite.configuration().getConsistentId()); assertEquals(defConsistentId, ignite.cluster().localNode().consistentId()); info("Consistent ID: " + ignite.cluster().localNode().consistentId()); }
Source:
protected void updateQuotaByCluster(final Guid defaultQuota, final String quotaName) { Cluster cluster = getModel().getSelectedCluster(); if (cluster == null) { return; } if (!getModel().getQuota().getIsAvailable()) { getModel().getQuota().setItems(null); return; } AsyncDataProvider.getInstance().getAllRelevantQuotasForClusterSorted(new AsyncQuery<>( quotaList -> { UnitVmModel vmModel = getModel(); vmModel.getQuota().setItems(quotaList); if (quotaList == null) { return; } if (!Guid.isNullOrEmpty(defaultQuota)) { boolean hasQuotaInList = false; if (!quotaList.isEmpty()) { hasQuotaInList = defaultQuota.equals(quotaList.get(0).getId()); } if (!hasQuotaInList && !getModel().getIsNew() && !getModel().getIsClone()) { Quota quota = new Quota(); quota.setId(defaultQuota); quota.setQuotaName(quotaName); quotaList.add(0, quota); vmModel.getQuota().setItems(quotaList); vmModel.getQuota().setSelectedItem(quota); } } }), cluster.getId(), defaultQuota); }

Target:
protected void updateQuotaByCluster(final Guid defaultQuota, final String quotaName) { Cluster cluster = getModel().getSelectedCluster(); if (cluster == null) { return; } if (!getModel().getQuota().getIsAvailable()) { getModel().getQuota().setItems(null); return; } AsyncDataProvider.getInstance().getAllRelevantQuotasForClusterSorted(new AsyncQuery<>( quotaList -> { UnitVmModel vmModel = getModel(); vmModel.getQuota().setItems(quotaList); if (quotaList == null) { return; } if (!Guid.isNullOrEmpty(defaultQuota)) { boolean hasQuotaInList = false; if (!quotaList.isEmpty()) { hasQuotaInList = defaultQuota.equals(quotaList.get(0).getId()); } if (!hasQuotaInList && !getModel().getIsNew()) { Quota quota = new Quota(); quota.setId(defaultQuota); quota.setQuotaName(quotaName); quotaList.add(0, quota); vmModel.getQuota().setItems(quotaList); vmModel.getQuota().setSelectedItem(quota); } } }), cluster.getId(), defaultQuota); }
Source:
public void testRemoteUnix() { host = createLinuxHost(HOST_NAME); assertNotNull(host); String home = "/home/rob/jboss-eap-5.1"; IServer s = createEAP5Server(home); String args = getStartArgsForServer(s); System.out.println(args); assertTrue(args.contains("/home/rob/jboss-eap-5.1/lib/endorsed")); assertTrue(args.contains("/home/rob/jboss-eap-5.1/server")); assertTrue(args.contains("/home/rob/jboss-eap-5.1/bin/native")); }

Target:
public void testRemoteUnix() { host = createLinuxHost(HOST_NAME); assertNotNull(host); String home = "/home/wonkauser/jboss-eap-5.1"; IServer s = createEAP5Server(home); String args = getStartArgsForServer(s); assertTrue(args.contains("/home/wonkauser/jboss-eap-5.1/lib/endorsed")); assertTrue(args.contains("/home/wonkauser/jboss-eap-5.1/server")); assertTrue(args.contains("/home/wonkauser/jboss-eap-5.1/bin/native")); }
Source:
protected String getDescription() { return "Kills a scheduled or running task"; }

Target:
protected String getDescription() { return "Kill a scheduled or running task"; }
Source:
public void write(K key, V value) throws Exception { lock.writeLock().lock(); try { LOGGER.info("Key - '{}' ,Value - '{}' successfully wriiten", key, value); data.put(key, new Pair<K, V>(key, value)); } finally { lock.writeLock().unlock(); } }

Target:
public void write(K key, V value) throws Exception { lock.writeLock().lock(); try { LOGGER.info("Key - '{}', Value - '{}' successfully written", key, value); data.put(key, new Pair<K, V>(key, value)); } finally { lock.writeLock().unlock(); } }
Source:
private DateTimeFormatter getDateTimeFormatterFromCache(String pattern) { DateTimeFormatter dateTimeFormatter = patternDateTimeFormatterCache.getOrDefault(pattern, DateTimeFormat.forPattern(pattern)); patternDateTimeFormatterCache.putIfAbsent(pattern, dateTimeFormatter); return dateTimeFormatter; }

Target:
private DateTimeFormatter getDateTimeFormatterFromCache(String pattern) { return patternCache .computeIfAbsent(pattern, missingPattern -> DateTimeFormat.forPattern(missingPattern).withZoneUTC()); }
Source:
public static Vcs extractVcs(File workingDir, Log log) throws IOException { File dotGit = getDotGit(workingDir); Vcs vcs = new Vcs(); vcs.setRevision(extractVcsRevision(dotGit, log)); vcs.setUrl(extractVcsUrl(dotGit, log)); return vcs; }

Target:
public static Vcs extractVcs(File workingDir, Log log) throws IOException { File dotGit = getDotGit(workingDir); if (dotGit == null) { throw new FileNotFoundException("Could not find .git directory for extracting Vcs details"); } Vcs vcs = new Vcs(); vcs.setRevision(extractVcsRevision(dotGit, log)); vcs.setUrl(extractVcsUrl(dotGit, log)); return vcs; }
Source:
public void testRequestsWithContent() throws Exception { HttpClient mockClient = mock(HttpClient.class); org.apache.http.HttpResponse mockResponse = mock(org.apache.http.HttpResponse.class); when(mockClient.execute(any(HttpUriRequest.class))).thenReturn(mockResponse); ApacheHttpTransport transport = new ApacheHttpTransport(mockClient); subtestUnsupportedRequestsWithContent( transport.buildRequest("GET", "<LINK_0>"), "GET"); subtestUnsupportedRequestsWithContent( transport.buildRequest("DELETE", "<LINK_0>"), "DELETE"); subtestUnsupportedRequestsWithContent( transport.buildRequest("HEAD", "<LINK_0>"), "HEAD"); execute(transport.buildRequest("PUT", "<LINK_0>")); execute(transport.buildRequest("POST", "<LINK_0>")); execute(transport.buildRequest("PATCH", "<LINK_0>")); }

Target:
public void testRequestsWithContent() throws Exception { HttpClient mockClient = mock(HttpClient.class); HttpResponse mockResponse = mock(HttpResponse.class); when(mockClient.execute(any(HttpUriRequest.class))).thenReturn(mockResponse); ApacheHttpTransport transport = new ApacheHttpTransport(mockClient); subtestUnsupportedRequestsWithContent( transport.buildRequest("GET", "<LINK_0>"), "GET"); subtestUnsupportedRequestsWithContent( transport.buildRequest("DELETE", "<LINK_0>"), "DELETE"); subtestUnsupportedRequestsWithContent( transport.buildRequest("HEAD", "<LINK_0>"), "HEAD"); execute(transport.buildRequest("PUT", "<LINK_0>")); execute(transport.buildRequest("POST", "<LINK_0>")); execute(transport.buildRequest("PATCH", "<LINK_0>")); }
Source:
public void put(final K key, final V value) throws CacheAccessException { accessObserver.begin(); checkKey(key); checkValue(value); while (true) { final long now = timeSource.getTimeMillis(); try { backingMap().compute(key, new BiFunction<K, OffHeapValueHolder<V>, OffHeapValueHolder<V>>() { @Override public OffHeapValueHolder<V> apply(K mappedKey, OffHeapValueHolder<V> mappedValue) { if (mappedValue != null && mappedValue.isExpired(now, TimeUnit.MILLISECONDS)) { mappedValue = null; } if (mappedValue == null) { return newCreateValueHolder(key, value, now); } else { return newUpdatedValueHolder(key, value, mappedValue, now); } } }, false); break; } catch (OversizeMappingException ex) { handleOversizeMappingException(key, ex); } } accessObserver.end(StoreOperationOutcomes.AccessOutcome.WRITE); }

Target:
public void put(final K key, final V value) throws CacheAccessException { accessObserver.begin(); checkKey(key); checkValue(value); while (true) { final long now = timeSource.getTimeMillis(); try { backingMap().compute(key, new BiFunction<K, OffHeapValueHolder<V>, OffHeapValueHolder<V>>() { @Override public OffHeapValueHolder<V> apply(K mappedKey, OffHeapValueHolder<V> mappedValue) { if (mappedValue != null && mappedValue.isExpired(now, TimeUnit.MILLISECONDS)) { mappedValue = null; } if (mappedValue == null) { return newCreateValueHolder(key, value, now); } else { return newUpdatedValueHolder(key, value, mappedValue, now); } } }, false); accessObserver.end(StoreOperationOutcomes.AccessOutcome.WRITE); return; } catch (OversizeMappingException ex) { handleOversizeMappingException(key, ex); } } }
Source:
public void testSetLTE() { mConnectionUT = new ImsPhoneConnection(mImsPhone, mImsCall, mImsCT, mForeGroundCall, false); assertFalse(mConnectionUT.getCallRadioTech() == ServiceState.RIL_RADIO_TECHNOLOGY_LTE); doReturn(ServiceState.RIL_RADIO_TECHNOLOGY_LTE).when(mImsCall).getRadioTechnology(); mBundle.putString(ImsCallProfile.EXTRA_CALL_RAT_TYPE, ServiceState.RIL_RADIO_TECHNOLOGY_LTE + ""); assertTrue(mConnectionUT.update(mImsCall, Call.State.ACTIVE)); assertTrue(mConnectionUT.getCallRadioTech() == ServiceState.RIL_RADIO_TECHNOLOGY_LTE); }

Target:
public void testSetLTE() { mConnectionUT = new ImsPhoneConnection(mImsPhone, mImsCall, mImsCT, mForeGroundCall, false); assertNotEquals(mConnectionUT.getCallRadioTech(), ServiceState.RIL_RADIO_TECHNOLOGY_LTE); doReturn(ServiceState.RIL_RADIO_TECHNOLOGY_LTE).when(mImsCall).getRadioTechnology(); mBundle.putString(ImsCallProfile.EXTRA_CALL_RAT_TYPE, ServiceState.RIL_RADIO_TECHNOLOGY_LTE + ""); assertTrue(mConnectionUT.update(mImsCall, Call.State.ACTIVE)); assertEquals(mConnectionUT.getCallRadioTech(), ServiceState.RIL_RADIO_TECHNOLOGY_LTE); }
Source:
private void removeImageFromDB() { TransactionSupport.executeInScope(TransactionScopeOption.Required, new TransactionMethod<Object>() { @Override public Object runInTransaction() { DiskImage diskImage = getDiskImage(); if (diskImage != null) { getDiskImageDynamicDAO().remove(diskImage.getImageId()); Guid imageTemplate = diskImage.getit_guid(); Guid currentGuid = diskImage.getImageId(); while (!imageTemplate.equals(currentGuid) && !currentGuid.equals(Guid.Empty)) { RemoveChildren(currentGuid); DiskImage image = getDiskImageDao().getSnapshotById(currentGuid); if (image != null) { RemoveSnapshot(image); removeImageFromSnapshotConfiguration( image.getvm_snapshot_id().getValue(), currentGuid); currentGuid = image.getParentId(); } else { currentGuid = Guid.Empty; log.warnFormat( "RemoveImageCommand::RemoveImageFromDB: 'image' (snapshot of image '{0}') is null, cannot remove it.", diskImage.getImageId()); } } getBaseDiskDao().remove(diskImage.getId()); getVmDeviceDAO().remove(new VmDeviceId(diskImage.getId(), null)); } else { log.warn("RemoveImageCommand::RemoveImageFromDB: DiskImage is null, nothing to remove."); } return null; } }); }

Target:
private void removeImageFromDB() { final DiskImage diskImage = getDiskImage(); final List<Snapshot> updatedSnapshots = prepareSnapshotConfigurationsWithoutImage(diskImage.getId()); TransactionSupport.executeInScope(TransactionScopeOption.Required, new TransactionMethod<Object>() { @Override public Object runInTransaction() { getDiskImageDynamicDAO().remove(diskImage.getImageId()); Guid imageTemplate = diskImage.getit_guid(); Guid currentGuid = diskImage.getImageId(); while (!imageTemplate.equals(currentGuid) && !currentGuid.equals(Guid.Empty)) { RemoveChildren(currentGuid); DiskImage image = getDiskImageDao().getSnapshotById(currentGuid); if (image != null) { RemoveSnapshot(image); currentGuid = image.getParentId(); } else { currentGuid = Guid.Empty; log.warnFormat( "RemoveImageCommand::RemoveImageFromDB: 'image' (snapshot of image '{0}') is null, cannot remove it.", diskImage.getImageId()); } } getBaseDiskDao().remove(diskImage.getId()); getVmDeviceDAO().remove(new VmDeviceId(diskImage.getId(), null)); for (Snapshot s : updatedSnapshots) { getSnapshotDAO().update(s); } return null; } }); }
Source:
protected boolean executeAnalysis(@NonNull IProgressMonitor monitor) throws TmfAnalysisException { ITmfTrace trace = getTrace(); if (trace == null) { System.out.println(1); initialize(false); return false; } IStatus status1 = segmentStoreModule.schedule(); IStatus status2 = stateSystemModule.schedule(); if (!(status1.isOK() && status2.isOK())) { System.out.println(2); cancelSubAnalyses(); initialize(false); return false; } if (!stateSystemModule.waitForInitialization()) { System.out.println(3); initialize(false); return false; } ITmfStateSystem stateSystem = stateSystemModule.getStateSystem(); if (stateSystem == null) { System.out.println(4); initialize(false); return false; } initialize(true); if (!(stateSystemModule.waitForCompletion(monitor) && segmentStoreModule.waitForCompletion(monitor))) { System.out.println(5); return false; } System.out.println("worked!"); return true; }

Target:
protected boolean executeAnalysis(@NonNull IProgressMonitor monitor) throws TmfAnalysisException { ITmfTrace trace = getTrace(); if (trace == null) { initialize(false); return false; } IStatus status1 = segmentStoreModule.schedule(); IStatus status2 = stateSystemModule.schedule(); if (!(status1.isOK() && status2.isOK())) { cancelSubAnalyses(); initialize(false); return false; } if (!stateSystemModule.waitForInitialization()) { initialize(false); return false; } ITmfStateSystem stateSystem = stateSystemModule.getStateSystem(); if (stateSystem == null) { initialize(false); return false; } initialize(true); if (!(stateSystemModule.waitForCompletion(monitor) && segmentStoreModule.waitForCompletion(monitor))) { return false; } return true; }
Source:
public <T> TypeSerializer<T> getTypeSerializerIn(int index, ClassLoader cl) { Input[] inputs = getInputs(cl); if (index >= inputs.length) { return null; } checkState(inputs[index] instanceof NetworkInput, "Input [%d] was assumed to be network input", index); return (TypeSerializer<T>) ((NetworkInput) inputs[index]).typeSerializer; }

Target:
public <T> TypeSerializer<T> getTypeSerializerIn(int index, ClassLoader cl) { InputConfig[] inputs = getInputs(cl); checkState(index < inputs.length); checkState(inputs[index] instanceof NetworkInputConfig, "Input [%s] was assumed to be network input", index); return (TypeSerializer<T>) ((NetworkInputConfig) inputs[index]).typeSerializer; }
Source:
private SourceResponse cloneResponse(SourceResponse sourceResponse) { List<Result> clonedResults = sourceResponse .getResults() .stream() .map(Result::getMetacard) .map(m -> new MetacardImpl(m, m.getMetacardType())) .map(ResultImpl::new) .collect(Collectors.toList()); QueryResponseImpl clonedResponse = new QueryResponseImpl( sourceResponse.getRequest(), clonedResults, true, sourceResponse.getHits(), sourceResponse.getProperties()); Set<ProcessingDetails> detailsOfClonedResponse = clonedResponse.getProcessingDetails(); for (SourceProcessingDetails detailsOfSourceResponse : sourceResponse.getProcessingDetails()) { detailsOfClonedResponse.add(new ProcessingDetailsImpl(detailsOfSourceResponse, "")); } return clonedResponse; }

Target:
private SourceResponse cloneResponse(SourceResponse sourceResponse) { List<Result> clonedResults = sourceResponse .getResults() .stream() .map(Result::getMetacard) .map(m -> new MetacardImpl(m, m.getMetacardType())) .map(ResultImpl::new) .collect(Collectors.toList()); Set<ProcessingDetails> processingDetails = sourceResponse .getProcessingDetails() .stream() .map(sourceDetails -> new ProcessingDetailsImpl(sourceDetails, source.getId())) .collect(Collectors.toSet()); return new QueryResponseImpl( sourceResponse.getRequest(), clonedResults, true, sourceResponse.getHits(), sourceResponse.getProperties(), processingDetails); }
Source:
private void gateways(Collection<IntegrationNode> nodes, Collection<LinkNode> links, Map<String, MessageChannelNode> channelNodes) { Map<String, MessagingGatewaySupport> gateways = this.applicationContext .getBeansOfType(MessagingGatewaySupport.class); for (Entry<String, MessagingGatewaySupport> entry : gateways.entrySet()) { MessagingGatewaySupport gateway = entry.getValue(); MessageGatewayNode gatewayNode = this.nodeFactory.gatewayNode(entry.getKey(), gateway); nodes.add(gatewayNode); producerLink(links, channelNodes, gatewayNode); } Map<String, GatewayProxyFactoryBean> gpfbs = this.applicationContext .getBeansOfType(GatewayProxyFactoryBean.class); for (Entry<String, GatewayProxyFactoryBean> entry : gpfbs.entrySet()) { Map<Method, MessagingGatewaySupport> methodMap = entry.getValue().getGateways(); int i = 0; for (Entry<Method, MessagingGatewaySupport> gwEntry : methodMap.entrySet()) { MessagingGatewaySupport gateway = gwEntry.getValue(); MessageGatewayNode gatewayNode = this.nodeFactory.gatewayNode( entry.getKey().substring(1) + "." + gwEntry.getKey().getName() + "#" + i++, gateway); nodes.add(gatewayNode); producerLink(links, channelNodes, gatewayNode); } } }

Target:
private void gateways(Collection<IntegrationNode> nodes, Collection<LinkNode> links, Map<String, MessageChannelNode> channelNodes) { Map<String, MessagingGatewaySupport> gateways = this.applicationContext .getBeansOfType(MessagingGatewaySupport.class); for (Entry<String, MessagingGatewaySupport> entry : gateways.entrySet()) { MessagingGatewaySupport gateway = entry.getValue(); MessageGatewayNode gatewayNode = this.nodeFactory.gatewayNode(entry.getKey(), gateway); nodes.add(gatewayNode); producerLink(links, channelNodes, gatewayNode); } Map<String, GatewayProxyFactoryBean> gpfbs = this.applicationContext .getBeansOfType(GatewayProxyFactoryBean.class); for (Entry<String, GatewayProxyFactoryBean> entry : gpfbs.entrySet()) { Map<Method, MessagingGatewaySupport> methodMap = entry.getValue().getGateways(); for (Entry<Method, MessagingGatewaySupport> gwEntry : methodMap.entrySet()) { MessagingGatewaySupport gateway = gwEntry.getValue(); Method method = gwEntry.getKey(); String signature = method.getName() + "(" + StringUtils.arrayToCommaDelimitedString(method.getParameterTypes()) + ")"; MessageGatewayNode gatewayNode = this.nodeFactory.gatewayNode( entry.getKey().substring(1) + "." + signature, gateway); nodes.add(gatewayNode); producerLink(links, channelNodes, gatewayNode); } } }
Source:
public void testToString(){ final String expectedLinear = "TmfTimestampLinear [ alpha = 314.0, beta = 0.0 ]"; final String expectedOffset = "TmfConstantTransform [ offset=19:00:00.000 000 314 ]"; final String expectedIdentity = "TmfTimestampTransform [ IDENTITY ]"; assertEquals( expectedLinear, TimestampTransformFactory.create(314, 0).toString()); assertEquals( expectedOffset, TimestampTransformFactory.create(1, 314).toString()); assertEquals( expectedOffset, TimestampTransformFactory.create(314).toString()); assertEquals( expectedOffset, TimestampTransformFactory.create(14).composeWith( TimestampTransformFactory.create(300)).toString()); assertEquals( expectedIdentity, TimestampTransformFactory.create(314).composeWith( TimestampTransformFactory.create(-314)).toString()); assertEquals( expectedIdentity, TimestampTransformFactory.create(0).toString()); }

Target:
public void testToString(){ final String expectedLinear = "TmfTimestampLinear [ alpha = 314.0, beta = 0.0 ]"; final String expectedOffset = "TmfConstantTransform [ offset = 314 ]"; final String expectedIdentity = "TmfTimestampTransform [ IDENTITY ]"; assertEquals( expectedLinear, TimestampTransformFactory.create(314, 0).toString()); assertEquals( expectedOffset, TimestampTransformFactory.create(1, 314).toString()); assertEquals( expectedOffset, TimestampTransformFactory.create(314).toString()); assertEquals( expectedOffset, TimestampTransformFactory.create(14).composeWith( TimestampTransformFactory.create(300)).toString()); assertEquals( expectedIdentity, TimestampTransformFactory.create(314).composeWith( TimestampTransformFactory.create(-314)).toString()); assertEquals( expectedIdentity, TimestampTransformFactory.create(0).toString()); }
Source:
private JobGraph createJobGraph() { preValidate(); jobGraph.setScheduleMode(streamGraph.getScheduleMode()); Map<Integer, byte[]> hashes = defaultStreamGraphHasher.traverseStreamGraphAndGenerateHashes(streamGraph); List<Map<Integer, byte[]>> legacyHashes = new ArrayList<>(legacyStreamGraphHashers.size()); for (StreamGraphHasher hasher : legacyStreamGraphHashers) { legacyHashes.add(hasher.traverseStreamGraphAndGenerateHashes(streamGraph)); } setChaining(hashes, legacyHashes); setPhysicalEdges(); setSlotSharingAndCoLocation(); setManagedMemoryFraction( Collections.unmodifiableMap(jobVertices), Collections.unmodifiableMap(vertexConfigs), Collections.unmodifiableMap(chainedConfigs), id -> streamGraph.getStreamNode(id).getManagedMemoryUseCaseWeights().getOrDefault(ManagedMemoryUseCase.BATCH_OP, 0)); configureCheckpointing(); jobGraph.setSavepointRestoreSettings(streamGraph.getSavepointRestoreSettings()); JobGraphUtils.addUserArtifactEntries(streamGraph.getUserArtifacts(), jobGraph); try { jobGraph.setExecutionConfig(streamGraph.getExecutionConfig()); } catch (IOException e) { throw new IllegalConfigurationException("Could not serialize the ExecutionConfig." + "This indicates that non-serializable types (like custom serializers) were registered"); } return jobGraph; }

Target:
private JobGraph createJobGraph() { preValidate(); jobGraph.setScheduleMode(streamGraph.getScheduleMode()); Map<Integer, byte[]> hashes = defaultStreamGraphHasher.traverseStreamGraphAndGenerateHashes(streamGraph); List<Map<Integer, byte[]>> legacyHashes = new ArrayList<>(legacyStreamGraphHashers.size()); for (StreamGraphHasher hasher : legacyStreamGraphHashers) { legacyHashes.add(hasher.traverseStreamGraphAndGenerateHashes(streamGraph)); } setChaining(hashes, legacyHashes); setPhysicalEdges(); setSlotSharingAndCoLocation(); setManagedMemoryFraction( Collections.unmodifiableMap(jobVertices), Collections.unmodifiableMap(vertexConfigs), Collections.unmodifiableMap(chainedConfigs), id -> Optional.ofNullable(streamGraph.getStreamNode(id).getManagedMemoryUseCaseWeights().get(ManagedMemoryUseCase.BATCH_OP))); configureCheckpointing(); jobGraph.setSavepointRestoreSettings(streamGraph.getSavepointRestoreSettings()); JobGraphUtils.addUserArtifactEntries(streamGraph.getUserArtifacts(), jobGraph); try { jobGraph.setExecutionConfig(streamGraph.getExecutionConfig()); } catch (IOException e) { throw new IllegalConfigurationException("Could not serialize the ExecutionConfig." + "This indicates that non-serializable types (like custom serializers) were registered"); } return jobGraph; }
Source:
private boolean isRecoverable(String message) { List<String> knownFailures = Arrays.asList( "Connection refused", "Connection reset", "Connection timed out", "No route to host", "Premature connection close" ); for (String s : knownFailures) { if (message.startsWith(s)) return true; } return false; }

Target:
private boolean isRecoverable(String message) { for (String s : RECOVERABLE_FAILURES) { if (message.startsWith(s)) return true; } return false; }
Source:
public PersistentNode(CuratorFramework client, final CreateMode mode, boolean useProtection, final String basePath, byte[] initData) { this.useProtection = useProtection; this.client = Preconditions.checkNotNull(client, "client cannot be null"); this.basePath = PathUtils.validatePath(basePath); this.mode = Preconditions.checkNotNull(mode, "mode cannot be null"); final byte[] data = Preconditions.checkNotNull(initData, "data cannot be null"); backgroundCallback = new BackgroundCallback() { @Override public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { String path = null; boolean nodeExists = false; if ( event.getResultCode() == KeeperException.Code.NODEEXISTS.intValue() ) { path = event.getPath(); nodeExists = true; } else if ( event.getResultCode() == KeeperException.Code.OK.intValue() ) { path = event.getName(); } else if ( event.getResultCode() == KeeperException.Code.NOAUTH.intValue() ) { log.warn("Client does not have authorisation to write ephemeral node at path {}", event.getPath()); authFailure.set(true); return; } if ( path != null ) { authFailure.set(false); nodePath.set(path); watchNode(); if ( nodeExists ) { client.setData().inBackground(setDataCallback).forPath(getActualPath(), getData()); } else { initialisationComplete(); } } else { createNode(); } } }; createMethod = useProtection ? client.create().creatingParentContainersIfNeeded().withProtection() : client.create().creatingParentContainersIfNeeded(); this.data.set(Arrays.copyOf(data, data.length)); }

Target:
public PersistentNode(CuratorFramework client, final CreateMode mode, boolean useProtection, final String basePath, byte[] initData) { this.useProtection = useProtection; this.client = Preconditions.checkNotNull(client, "client cannot be null"); this.basePath = PathUtils.validatePath(basePath); this.mode = Preconditions.checkNotNull(mode, "mode cannot be null"); final byte[] data = Preconditions.checkNotNull(initData, "data cannot be null"); backgroundCallback = new BackgroundCallback() { @Override public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { String path = null; boolean nodeExists = false; if ( event.getResultCode() == KeeperException.Code.NODEEXISTS.intValue() ) { path = event.getPath(); nodeExists = true; } else if ( event.getResultCode() == KeeperException.Code.OK.intValue() ) { path = event.getName(); } else if ( event.getResultCode() == KeeperException.Code.NOAUTH.intValue() ) { log.warn("Client does not have authorisation to write node at path {}", event.getPath()); authFailure.set(true); return; } if ( path != null ) { authFailure.set(false); nodePath.set(path); watchNode(); if ( nodeExists ) { client.setData().inBackground(setDataCallback).forPath(getActualPath(), getData()); } else { initialisationComplete(); } } else { createNode(); } } }; createMethod = useProtection ? client.create().creatingParentContainersIfNeeded().withProtection() : client.create().creatingParentContainersIfNeeded(); this.data.set(Arrays.copyOf(data, data.length)); }
Source:
public void testConfigureFromManifestWithoutServer() throws Exception { Context context = mock(Context.class); PackageManager packageManager = mock(PackageManager.class); ApplicationInfo appInfo = mock(ApplicationInfo.class); Bundle metaData = setupMockMetaData(context, packageManager, appInfo); when(metaData.getString(PARSE_SERVER_URL)).thenReturn(null); when(metaData.getString(PARSE_APPLICATION_ID)).thenReturn(appId); when(metaData.getString(PARSE_CLIENT_KEY)).thenReturn(clientKey); Parse.initialize(context); }

Target:
public void testConfigureFromManifestWithoutServer() throws Exception { Bundle metaData = setupMockMetaData(); when(metaData.getString(PARSE_SERVER_URL)).thenReturn(null); when(metaData.getString(PARSE_APPLICATION_ID)).thenReturn(appId); when(metaData.getString(PARSE_CLIENT_KEY)).thenReturn(clientKey); Parse.initialize(RuntimeEnvironment.application); }
Source:
private void addVmRngDevice() { VmRngDevice rngDev = getParameters().getRngDevice(); if (rngDev != null) { rngDev.setVmId(getParameters().getVmId()); RngDeviceParameters params = new RngDeviceParameters(rngDev, true); VdcReturnValueBase result = getBackend().runInternalAction(VdcActionType.AddRngDevice, params); if (!result.getSucceeded()) { getReturnValue().setSucceeded(false); } } }

Target:
private void addVmRngDevice() { VmRngDevice rngDev = getParameters().getRngDevice(); if (rngDev != null) { RngDeviceParameters params = new RngDeviceParameters(rngDev, true); VdcReturnValueBase result = getBackend().runInternalAction(VdcActionType.AddRngDevice, params); if (!result.getSucceeded()) { throw new IllegalStateException("Couldn't add RNG device."); } } }
Source:
public void testGetModelsAfter2000UsingPipeline() { List<String> models = FunctionalProgramming.getModelsAfter2000(cars); assertEquals(models, Arrays.asList("Avenger", "Wrangler", "Focus", "Cascada")); }

Target:
public void testGetModelsAfter2000UsingPipeline() { List<String> models = FunctionalProgramming.getModelsAfter2000(cars); assertEquals(Arrays.asList("Avenger", "Wrangler", "Focus", "Cascada"), models); }
Source:
public String getCookies() { StringBuilder ret = new StringBuilder(); ArrayList<org.openqa.selenium.Cookie> cookies = new ArrayList<>(browserManagement .getCurrentWebDriver().manage().getCookies()); for (int i = 0; i < cookies.size(); i++) { ret.append(cookies.get(i).getName()).append("=").append(cookies.get(i).getValue()); if (i != cookies.size() - 1) { ret.append("; "); } } return ret.toString(); }

Target:
public String getCookies() { StringBuilder ret = new StringBuilder(); ArrayList<org.openqa.selenium.Cookie> cookies = new ArrayList<>(browserManagement .getCurrentWebDriver().manage().getCookies()); for (int i = 0; i < cookies.size(); i++) { ret.append(cookies.get(i).getName()).append('=').append(cookies.get(i).getValue()); if (i != cookies.size() - 1) { ret.append("; "); } } return ret.toString(); }