auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void copy(Vector x, Vector y) { int n = y.size(); if (x.size() != n) throw new CardinalityException(x.size(), n); if (y.isArrayBased()) { double[] yData = y.getStorage().data(); if (x.isArrayBased()) System.arraycopy(x.getStorage().data(), 0, y.getStorage().data(), 0, n); else { if (y instanceof SparseLocalVector) { for (int i = 0; i < n; i++) yData[i] = x.getX(i); } } } else throw new IllegalArgumentException("y must be array based in copy"); }

Target:
public void copy(Vector x, Vector y) { int n = y.size(); if (x.size() != n) throw new CardinalityException(x.size(), n); if (y.isArrayBased()) { double[] yData = y.getStorage().data(); if (x.isArrayBased()) System.arraycopy(x.getStorage().data(), 0, y.getStorage().data(), 0, n); else { if (y instanceof SparseLocalVector) { for (int i = 0; i < n; i++) yData[i] = x.getX(i); } } } else throw new IllegalArgumentException("Vector y must be array based in copy."); }
Source:
public synchronized void onSchoolDataWorkspaceUserDiscoveredEvent(@Observes SchoolDataWorkspaceUserDiscoveredEvent event) { String userIdentifier = event.getUserIdentifier(); String userDataSource = event.getUserDataSource(); SchoolDataIdentifier user = new SchoolDataIdentifier(userIdentifier, userDataSource); String workspaceDataSource = event.getWorkspaceDataSource(); String workspaceIdentifier = event.getWorkspaceIdentifier(); WorkspaceEntity workspace = workspaceEntityController.findWorkspaceByDataSourceAndIdentifier(workspaceDataSource, workspaceIdentifier); WorkspaceChatSettings workspaceChatStatus = chatController.findWorkspaceChatSettings(workspace.getId()); if (workspaceChatStatus.getStatus() == WorkspaceChatStatus.ENABLED) { chatSyncController.syncStudent(user); } }

Target:
public synchronized void onSchoolDataWorkspaceUserDiscoveredEvent(@Observes SchoolDataWorkspaceUserDiscoveredEvent event) { String userIdentifier = event.getUserIdentifier(); String userDataSource = event.getUserDataSource(); SchoolDataIdentifier user = new SchoolDataIdentifier(userIdentifier, userDataSource); String workspaceDataSource = event.getWorkspaceDataSource(); String workspaceIdentifier = event.getWorkspaceIdentifier(); WorkspaceEntity workspace = workspaceEntityController.findWorkspaceByDataSourceAndIdentifier(workspaceDataSource, workspaceIdentifier); WorkspaceChatSettings workspaceChatStatus = chatController.findWorkspaceChatSettings(workspace.getId()); if (workspaceChatStatus != null && workspaceChatStatus.getStatus() == WorkspaceChatStatus.ENABLED) { chatSyncController.syncWorkspaceUser(workspace, user); } }
Source:
public void testPingWrongServer() { PORT1 = initServerCache(true); initServerCache2(); InternalDistributedMember server2ID = server2.invoke("get ID", () -> cache.getMyId()); pool = (PoolImpl) createClientCache(NetworkUtils.getServerHostName(), PORT1); ClientProxyMembershipID proxyID = server1.invoke( () -> CacheClientNotifier.getInstance().getClientProxies().iterator().next().getProxyID()); logger.info("ProxyID is : " + proxyID); server2.invoke(() -> { assertThat(ClientHealthMonitor.getInstance().getClientHeartbeats().keySet().contains(proxyID)) .isFalse(); assertEquals(0, ClientHealthMonitor.getInstance().getClientHeartbeats().keySet().size()); }); PingOp.execute(pool, new ServerLocation(NetworkUtils.getServerHostName(), PORT1), server2ID); server2.invoke(() -> { await("For heartbeat to be received").timeout(Duration.ofMinutes(1)) .untilAsserted(() -> assertEquals(1, ClientHealthMonitor.getInstance().getClientHeartbeats().keySet().size())); ClientProxyMembershipID proxyIDFound = ClientHealthMonitor.getInstance().getClientHeartbeats().keySet().iterator().next(); logger.info("ProxyID found in clientHealthMonitor: " + proxyIDFound); assertThat( ClientHealthMonitor.getInstance().getClientHeartbeats().keySet().contains(proxyID)) .isTrue(); }); }

Target:
public void testPingWrongServer() { PORT1 = initServerCache(true); initServerCache2(); InternalDistributedMember server2ID = server2.invoke("get ID", () -> cache.getMyId()); pool = (PoolImpl) createClientCache(NetworkUtils.getServerHostName(), PORT1); ClientProxyMembershipID proxyID = server1.invoke( () -> CacheClientNotifier.getInstance().getClientProxies().iterator().next().getProxyID()); server2.invoke(() -> { assertThat(ClientHealthMonitor.getInstance().getClientHeartbeats().keySet().contains(proxyID)) .isFalse(); assertThat(ClientHealthMonitor.getInstance().getClientHeartbeats().keySet().size()) .isEqualTo(0); }); PingOp.execute(pool, new ServerLocation(NetworkUtils.getServerHostName(), PORT1), server2ID); server2.invoke(() -> { await("For heartbeat to be received").untilAsserted(() -> assertThat( ClientHealthMonitor.getInstance().getClientHeartbeats().keySet().size()) .isEqualTo(1)); ClientProxyMembershipID proxyIDFound = ClientHealthMonitor.getInstance().getClientHeartbeats().keySet().iterator().next(); assertThat( ClientHealthMonitor.getInstance().getClientHeartbeats().keySet().contains(proxyID)) .isTrue(); }); }
Source:
public void updated(Dictionary<String, ?> properties) throws ConfigurationException { { final String serialPort = (String) properties.get("serialPort"); if (StringUtils.isNotBlank(serialPort)) { this.serialPort = serialPort; } } { final String baudRate = (String) properties.get("baudRate"); if (StringUtils.isNotBlank(baudRate)) { this.baudRate = Integer.parseInt(baudRate); } } String canonical = serialPort; try { File device = new File(serialPort); if(device.canRead()) { canonical = device.getCanonicalPath(); } } catch (IOException e1) { logger.info("unable to get canonical path for '" + serialPort + "'"); canonical = serialPort; } xbeeSetupLock.lock(); try { if(xbee != null) { xbee.removePacketListener(this); xbee.close(); xbee = null; } xbee = new XBee(); try { logger.info("opening XBee communication on '" + canonical + "'"); xbee.open(canonical, baudRate); } catch (XBeeException e) { logger.error("failed to open connection to XBee module", e); xbee = null; return; } } finally { xbeeSetupLock.unlock(); } xbee.addPacketListener(this); }

Target:
public void updated(Dictionary<String, ?> properties) throws ConfigurationException { { final String serialPort = (String) properties.get("serialPort"); if (StringUtils.isNotBlank(serialPort)) { this.serialPort = serialPort; } } { final String baudRate = (String) properties.get("baudRate"); if (StringUtils.isNotBlank(baudRate)) { this.baudRate = Integer.parseInt(baudRate); } } String canonical = serialPort; try { File device = new File(serialPort); if (device.canRead()) { canonical = device.getCanonicalPath(); } } catch (IOException e1) { logger.info("unable to get canonical path for '{}'", serialPort); canonical = serialPort; } xbeeSetupLock.lock(); try { if (xbee != null) { xbee.removePacketListener(this); xbee.close(); xbee = null; } xbee = new XBee(); try { logger.info("opening XBee communication on '{}'", canonical); xbee.open(canonical, baudRate); } catch (XBeeException e) { logger.error("failed to open connection to XBee module", e); xbee = null; return; } } finally { xbeeSetupLock.unlock(); } xbee.addPacketListener(this); }
Source:
private void removeAaHits( final IDelegateBridge bridge, final CasualtyDetails casualties, final String currentTypeAa) { final List<Unit> killed = casualties.getKilled(); if (!killed.isEmpty()) { final IntegerMap<UnitType> costs = TuvUtils.getCostsForTuv(attacker, gameData); final int tuvLostAttacker = TuvUtils.getTuv(killed, attacker, costs, gameData); attackerLostTuv += tuvLostAttacker; removeAttackers(killed, false); new KillUnits(battleSite, killed, "${units} killed by " + currentTypeAa + " in ${territory}") .perform(bridge); } }

Target:
private void removeAaHits( final IDelegateBridge bridge, final CasualtyDetails casualties, final String currentTypeAa) { final List<Unit> killed = casualties.getKilled(); if (!killed.isEmpty()) { final IntegerMap<UnitType> costs = TuvUtils.getCostsForTuv(attacker, gameData); final int tuvLostAttacker = TuvUtils.getTuv(killed, attacker, costs, gameData); attackerLostTuv += tuvLostAttacker; removeAttackers(killed, false); HistoryChangeFactory.removeUnitsWithAa(battleSite, killed, currentTypeAa).perform(bridge); } }
Source:
private void assertRefundTransactions(Long paymentRequestId, DatabaseFixtures.TestRefund... testRefunds) { List<Map<String, Object>> refundTransactions = databaseTestHelper.getRefundTransaction(paymentRequestId); assertThat(refundTransactions.size(), is(testRefunds.length)); List<String> refundReferences = refundTransactions.stream().map(refund -> (String)refund.get("refund_reference")).collect(toList()); assertThat(refundReferences, containsInAnyOrder(stream(testRefunds).map(DatabaseFixtures.TestRefund::getReference).toArray())); }

Target:
private void assertRefundTransactions(Long paymentRequestId, DatabaseFixtures.TestRefund... testRefunds) { List<Map<String, Object>> refundTransactions = databaseTestHelper.getRefundTransaction(paymentRequestId); assertThat(refundTransactions.size(), is(testRefunds.length)); List<String> refundReferences = refundTransactions.stream().map(refund -> (String)refund.get("refund_external_id")).collect(toList()); assertThat(refundReferences, containsInAnyOrder(stream(testRefunds).map(DatabaseFixtures.TestRefund::getExternalRefundId).toArray())); }
Source:
protected void sendDirectMessage(final Object[] args, final Actor owner, final SResolver resolver) { CompilerAsserts.compilationConstant(args.length); SFarReference rcvr = (SFarReference) args[0]; Actor target = rcvr.getActor(); for (int i = 0; i < args.length; i++) { args[i] = wrapArgs[i].execute(args[i], target, owner); } assert !(args[0] instanceof SFarReference) : "This should not happen for this specialization, but it is handled in determineTargetAndWrapArguments(.)"; assert !(args[0] instanceof SPromise) : "Should not happen either, but just to be sure"; SteppingType step = getStepping(); DirectMessage msg = new DirectMessage( EventualMessage.getCurrentExecutingMessage(), EventualMessage.getCurrentExecutingMessageId(), target, selector, args, owner, resolver, onReceive, messageReceiverBreakpoint.executeCheckIsSetAndEnabled(), promiseResolverBreakpoint.executeCheckIsSetAndEnabled()); msg.setTriggerStepping(step); target.send(msg); }

Target:
protected void sendDirectMessage(final Object[] args, final Actor owner, final SResolver resolver) { CompilerAsserts.compilationConstant(args.length); SFarReference rcvr = (SFarReference) args[0]; Actor target = rcvr.getActor(); for (int i = 0; i < args.length; i++) { args[i] = wrapArgs[i].execute(args[i], target, owner); } assert !(args[0] instanceof SFarReference) : "This should not happen for this specialization, but it is handled in determineTargetAndWrapArguments(.)"; assert !(args[0] instanceof SPromise) : "Should not happen either, but just to be sure"; DirectMessage msg = new DirectMessage( EventualMessage.getCurrentExecutingMessageId(), target, selector, args, owner, resolver, onReceive, hasMessageReceiverBreakpoint(resolver), promiseResolverBreakpoint.executeCheckIsSetAndEnabled()); target.send(msg, actorPool); }
Source:
public void makeRecord(DocumentRef docRef) { Document doc = resolveReference(docRef); if (isRecord(docRef)) { return; } checkPermission(doc, CAN_MAKE_RECORD); DocumentModel docModel = readModel(doc); notifyEvent(DocumentEventTypes.BEFORE_MAKE_RECORD, docModel, null, null, null, true, false); doc.makeRecord(); docModel = readModel(doc); notifyEvent(DocumentEventTypes.AFTER_MAKE_RECORD, docModel, null, null, null, true, false); }

Target:
public void makeRecord(DocumentRef docRef) { Document doc = resolveReference(docRef); if (isRecord(docRef)) { return; } checkPermission(doc, MAKE_RECORD); DocumentModel docModel = readModel(doc); notifyEvent(DocumentEventTypes.BEFORE_MAKE_RECORD, docModel, null, null, null, true, false); doc.makeRecord(); docModel = readModel(doc); notifyEvent(DocumentEventTypes.AFTER_MAKE_RECORD, docModel, null, null, null, true, false); }
Source:
public void deleteIndex(String indexName, String designDocId) { assertNotEmpty(indexName, "indexName"); assertNotEmpty(designDocId, "designDocId"); URI uri = new DatabaseURIHelper(db.getDBUri()).path("_index/").path(designDocId) .path("/json/").path(indexName).build(); InputStream response = null; try { HttpConnection connection = Http.DELETE(uri); response = client.couchDbClient.executeToInputStream(connection); getResponse(response, Response.class, client.getGson()); } finally { close(response); } }

Target:
public void deleteIndex(String indexName, String designDocId) { assertNotEmpty(indexName, "indexName"); assertNotEmpty(designDocId, "designDocId"); URI uri = new DatabaseURIHelper(db.getDBUri()).path("_index").path(designDocId) .path("json").path(indexName).build(); InputStream response = null; try { HttpConnection connection = Http.DELETE(uri); response = client.couchDbClient.executeToInputStream(connection); getResponse(response, Response.class, client.getGson()); } finally { close(response); } }
Source:
private int getMatchingUsersCount(String username) { int count = 0; for (UserKeyRecord record : storage()) { if (record.getUsername().equals(username)) { count++; } } return count; }

Target:
private int getMatchingUsersCount(String username) { int count = 0; for (UserKeyRecord record : CommCareApplication._().getAppStorage(UserKeyRecord.class)) { if (record.getUsername().equals(username)) { count++; } } return count; }
Source:
protected synchronized void _dropIndexes(String name) throws MongoException { DBCollection indexColl = fongoDb.getCollection("system.indexes"); indexColl.remove(new BasicDBObject("name", name)); for (Map.Entry<Set<String>, Index> entry : indexes.entrySet()) { if (entry.getValue().getName().equals(name)) { indexes.remove(entry.getKey()); break; } } }

Target:
protected synchronized void _dropIndexes(String name) throws MongoException { DBCollection indexColl = fongoDb.getCollection("system.indexes"); indexColl.remove(new BasicDBObject("name", name)); ListIterator<Index> iterator = indexes.listIterator(); while (iterator.hasNext()) { Index index = iterator.next(); if (index.getName().equals(name)) { iterator.remove(); break; } } }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setHomeButtonEnabled(true); actionBar.setDisplayHomeAsUpEnabled(true); } setContentView(R.layout.people_management_activity); setTitle(R.string.people); int localBlogId = BlogUtils.getBlogLocalId(WordPress.getCurrentBlog()); Blog blog = WordPress.getBlog(localBlogId); if (savedInstanceState == null) { PeopleListFragment peopleListFragment = PeopleListFragment.newInstance(localBlogId); getFragmentManager().beginTransaction() .add(R.id.fragment_container, peopleListFragment, KEY_PEOPLE_LIST_FRAGMENT) .commit(); } if (blog != null) { refreshUsersList(blog.getDotComBlogId(), localBlogId); } }

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setHomeButtonEnabled(true); actionBar.setDisplayHomeAsUpEnabled(true); } setContentView(R.layout.people_management_activity); int localBlogId = BlogUtils.getBlogLocalId(WordPress.getCurrentBlog()); Blog blog = WordPress.getBlog(localBlogId); if (savedInstanceState == null) { PeopleListFragment peopleListFragment = PeopleListFragment.newInstance(localBlogId); getFragmentManager().beginTransaction() .add(R.id.fragment_container, peopleListFragment, KEY_PEOPLE_LIST_FRAGMENT) .commit(); } if (blog != null) { refreshUsersList(blog.getDotComBlogId(), localBlogId); } }
Source:
public McMMOPlayerCatalysisEvent(Player player, double speed) { super(player, SkillType.ALCHEMY); this.setSpeed(speed); cancelled = false; }

Target:
public McMMOPlayerCatalysisEvent(Player player, double speed) { super(player, SkillType.ALCHEMY); this.speed = speed; cancelled = false; }
Source:
public static JSONArray assembleTags(final JSONObject builddata, final HashMap<String,String> extra) { DatadogBuildListener.DescriptorImpl descriptor = DatadogUtilities.getDatadogDescriptor(); JSONArray tags = new JSONArray(); tags.add("job:" + builddata.get("job")); if ( (builddata.get("node") != null) && descriptor.getTagNode() != null && descriptor.getTagNode() ) { tags.add("node:" + builddata.get("node")); } if ( builddata.get("result") != null ) { tags.add("result:" + builddata.get("result")); } if ( builddata.get("branch") != null && !extra.containsKey("branch") ) { tags.add("branch:" + builddata.get("branch")); } for(Map.Entry entry : extra.entrySet()) { tags.add(String.format("%s:%s", entry.getKey(), entry.getValue())); logger.info(String.format("Emitted tag %s:%s", entry.getKey(), entry.getValue())); } return tags; }

Target:
public static JSONArray assembleTags(final JSONObject builddata, final HashMap<String,String> extra) { JSONArray tags = new JSONArray(); tags.add("job:" + builddata.get("job")); if ( (builddata.get("node") != null) && DatadogUtilities.getDatadogDescriptor().getTagNode() ) { tags.add("node:" + builddata.get("node")); } if ( builddata.get("result") != null ) { tags.add("result:" + builddata.get("result")); } if ( builddata.get("branch") != null && !extra.containsKey("branch") ) { tags.add("branch:" + builddata.get("branch")); } for(Map.Entry entry : extra.entrySet()) { tags.add(String.format("%s:%s", entry.getKey(), entry.getValue())); logger.info(String.format("Emitted tag %s:%s", entry.getKey(), entry.getValue())); } return tags; }
Source:
public void dispose() { this.h.removeCallbacksAndMessages(null); this.parent.dispose(); this.h = null; this.owner = null; this.parent = null; }

Target:
public void dispose() { }
Source:
private void executeScript(File vbDiffScript) throws OseeCoreException { Process process = null; try { String target = vbDiffScript.getName(); String cmd[] = {"cmd", "/s", "/c", "\"" + target + "\""}; ProcessBuilder builder = new ProcessBuilder(cmd); File parentDir = vbDiffScript.getParentFile(); if (parentDir != null) { builder.directory(parentDir); } process = builder.start(); Thread errorCatcher = new StreamLogger(process.getErrorStream()) { @Override protected void log(String message) { OseeLog.log(Activator.class, OseeLevel.SEVERE_POPUP, message); } }; Thread outputCatcher = new StreamLogger(process.getInputStream()) { @Override protected void log(String message) { OseeLog.log(Activator.class, Level.INFO, message); } }; errorCatcher.start(); outputCatcher.start(); String timeout = OseeInfo.getValue("osee.vba.word.diff.timeout"); if (timeout != null) { Long timeoutMs = Long.parseLong(timeout); if (!process.waitFor(timeoutMs, TimeUnit.MILLISECONDS)) { throw new OperationTimedoutException("The View Word Change Report Timed-out"); } } } catch (Exception ex) { OseeCoreException.wrapAndThrow(ex); } finally { if (process != null) { process.destroy(); } } }

Target:
private void executeScript(File vbDiffScript) throws OseeCoreException { Process process = null; try { String target = vbDiffScript.getName(); String cmd[] = {"cmd", "/s", "/c", "\"" + target + "\""}; ProcessBuilder builder = new ProcessBuilder(cmd); File parentDir = vbDiffScript.getParentFile(); if (parentDir != null) { builder.directory(parentDir); } process = builder.start(); Thread errorCatcher = new StreamLogger(process.getErrorStream()) { @Override protected void log(String message) { OseeLog.log(Activator.class, OseeLevel.SEVERE_POPUP, message); } }; Thread outputCatcher = new StreamLogger(process.getInputStream()) { @Override protected void log(String message) { OseeLog.log(Activator.class, Level.INFO, message); } }; errorCatcher.start(); outputCatcher.start(); Long timeoutMs = Long.MAX_VALUE; String timeout = OseeInfo.getValue("osee.vba.word.diff.timeout"); if (Strings.isValid(timeout)) { timeoutMs = Long.parseLong(timeout); } if (!process.waitFor(timeoutMs, TimeUnit.MILLISECONDS)) { throw new OperationTimedoutException("The View Word Change Report Timed-out"); } } catch (Exception ex) { OseeCoreException.wrapAndThrow(ex); } finally { if (process != null) { process.destroy(); } } }
Source:
public static void main(String... args) throws Exception { RSocketStats stats = RSocketStatsFactory.create(); RSocketFactory .receive(stats) .acceptor(new PingHandler()) .transport(WebsocketServerTransport.create(7878)) .start() .block() .onClose() .block(); }

Target:
public static void main(String... args) throws Exception { RSocketFactory .receive() .acceptor(new PingHandler()) .transport(WebsocketServerTransport.create(7878)) .start() .block() .onClose() .block(); }
Source:
public void destroyNode(String id) { waitServerUntilAvailable.apply(getNode(id)); logger.debug("Destroying %s ...", id); api.serverApi().delete(id); logger.debug("Destroyed %s!", id); }

Target:
public void destroyNode(String id) { checkState(cleanupResources.cleanupNode(id), "server(%s) and its resources still there after deleting!?", id); }
Source:
public void addKoreRules(Module module, TermContext termContext) { KOREtoBackendKIL transformer = new KOREtoBackendKIL(module, this, termContext, false, termContext.global().krunOptions.experimental.prove != null); List<org.kframework.definition.Rule> koreRules = JavaConversions.setAsJavaSet(module.sentences()).stream() .filter(org.kframework.definition.Rule.class::isInstance) .map(org.kframework.definition.Rule.class::cast) .collect(Collectors.toList()); koreRules.forEach(r -> { if (r.body() instanceof KApply && ((KApply) r.body()).klabel().name().equals("<T>")) { if (!r.att().contains("automaton")) { reverseRuleTable.put(r.hashCode(), reverseRuleTable.size()); } } }); koreRules.forEach(r -> { Rule convertedRule = transformer.convert(Optional.of(module), r); addRule(convertedRule); if (r.body() instanceof KApply && ((KApply) r.body()).klabel().name().equals("<T>")) { if (!r.att().contains("automaton")) { ruleTable.put(reverseRuleTable.get(r.hashCode()), convertedRule); } else { automaton = convertedRule; } } }); }

Target:
public void addKoreRules(Module module, TermContext termContext) { KOREtoBackendKIL transformer = new KOREtoBackendKIL(module, this, termContext, false, termContext.global().krunOptions.experimental.prove != null); List<org.kframework.definition.Rule> koreRules = JavaConversions.setAsJavaSet(module.sentences()).stream() .filter(org.kframework.definition.Rule.class::isInstance) .map(org.kframework.definition.Rule.class::cast) .collect(Collectors.toList()); koreRules.forEach(r -> { if (r.att().contains(Att.topRule())) { if (!r.att().contains(AUTOMATON)) { reverseRuleTable.put(r.hashCode(), reverseRuleTable.size()); } } }); koreRules.forEach(r -> { Rule convertedRule = transformer.convert(Optional.of(module), r); addRule(convertedRule); if (r.att().contains(Att.topRule())) { if (!r.att().contains(AUTOMATON)) { ruleTable.put(reverseRuleTable.get(r.hashCode()), convertedRule); } } if (r.att().contains(AUTOMATON)) { automaton = convertedRule; } }); }
Source:
public void initReview(){ int mStackLevel=0; mStackLevel++; if(reviewFragment==null) reviewFragment = ReviewFragment.newInstance(mStackLevel); replaceFragment(R.id.dashboard_details_container, reviewFragment); }

Target:
public void initReview(){ if(reviewFragment==null) reviewFragment = new ReviewFragment(); replaceFragment(R.id.dashboard_details_container, reviewFragment); }
Source:
public int size() { return permissions.size(); }

Target:
public synchronized int size() { return permissions.size(); }
Source:
public <T> T getAdapter(Class<T> adapter) { T result = null; if (adapter == DRepresentationDescriptor.class) { if (linkedRepresentation == null) { EditPartViewer viewer = getTargetEditPart().getViewer(); IEditorPart editor = (IEditorPart) ((DiagramEditDomain)viewer.getEditDomain()).getDiagramEditorPart(); Session session = ((SessionEditorInput) editor.getEditorInput()).getSession(); Shell shell = editor.getSite().getShell(); linkedRepresentation = SingleRepresentationTreeSelectionDialog.openSelectRepresentationDescriptor(shell, session); } result = (T) linkedRepresentation; } else if (adapter == EObject.class) { result = (T) linkedRepresentation; } return result; }

Target:
public <T> T getAdapter(Class<T> adapter) { T result = null; if (adapter == DRepresentationDescriptor.class) { if (linkedRepresentation == null) { Optional<Session> sessionOption = Session.of((EObject) getTargetEditPart().getModel()); if (sessionOption.isPresent()) { Shell shell = LinkNoteTool.this.getCurrentViewer().getControl().getShell(); linkedRepresentation = SingleRepresentationTreeSelectionDialog.openSelectRepresentationDescriptor(shell, sessionOption.get()); } } result = (T) linkedRepresentation; } else if (adapter == EObject.class) { result = (T) linkedRepresentation; } return result; }
Source:
private List<Project.NameKey> getAllParents(final Project.NameKey projectName) { final List<Project.NameKey> parents = new ArrayList<Project.NameKey>(); Project.NameKey p = projectName; while (p != null && !parents.contains(p)) { final ProjectState e = projectCache.get(p); if (e == null) { break; } p = getParentName(e.getProject()); if (p != null) { parents.add(p); } } return parents; }

Target:
private List<Project.NameKey> getAllParents(final Project.NameKey projectName) { final List<Project.NameKey> parents = new ArrayList<Project.NameKey>(); Project.NameKey p = projectName; while (p != null && parents.add(p)) { final ProjectState e = projectCache.get(p); if (e == null) { break; } p = getParentName(e.getProject()); } return parents; }
Source:
public KijiCell<T> next() { KijiCell<T> cell = null; while (mKVs.hasNext() && null == cell) { try { KeyValue kv = mKVs.next(); final KijiColumnName colName = mColumnNameTranslator.toKijiColumnName( new HBaseColumnName(kv.getFamily(), kv.getQualifier())); if (colName.getFamily().equals(mFamily)) { mNumVersions += 1; cell = new KijiCell<T>(mFamily, colName.getQualifier(), kv.getTimestamp(), mDecoder.decodeCell(kv.getValue())); } } catch (IOException ex) { throw new KijiIOException(ex.getMessage()); } } return cell; }

Target:
public KijiCell<T> next() { while (mKVs.hasNext()) { try { KeyValue kv = mKVs.next(); final KijiColumnName colName = mColumnNameTranslator.toKijiColumnName( new HBaseColumnName(kv.getFamily(), kv.getQualifier())); if (colName.getFamily().equals(mFamily)) { mNumVersions += 1; return new KijiCell<T>(mFamily, colName.getQualifier(), kv.getTimestamp(), mDecoder.decodeCell(kv.getValue())); } } catch (IOException ex) { throw new KijiIOException(ex); } } return null; }
Source:
public void restoreSnapshot(PeriodSnapshot s) { synchronized (coreLock) { if (s.getId() != getId()) { return; } if (getCurrentJam() != s.getCurrentJam()) { set(Value.CURRENT_JAM, s.getCurrentJam()); getLast(NChild.JAM).unlink(); } } }

Target:
public void restoreSnapshot(PeriodSnapshot s) { synchronized (coreLock) { if (s.getId() != getId()) { return; } if (getCurrentJam() != s.getCurrentJam()) { remove(NChild.JAM, getCurrentJam()); set(Value.CURRENT_JAM, s.getCurrentJam()); } } }
Source:
public void union() { NumberExpression<Integer> one = Expressions.ONE; NumberExpression<Integer> two = Expressions.TWO; NumberExpression<Integer> three = Expressions.THREE; Path<Integer> col1 = Expressions.path(Integer.class,"col1"); Union union = query.union( select(one.as(col1)), select(two), select(three)); if (templates.getDummyTable() == null) { assertEquals( "select 1 as col1\n" + "union\n" + "select 2\n" + "union\n" + "select 3", union.toString()); } else { String dummyTable = templates.getDummyTable(); assertEquals( "select 1 as col1 from " + dummyTable + "\n" + "union\n" + "select 2 from " + dummyTable + "\n" + "union\n" + "select 3 from " + dummyTable, union.toString()); } }

Target:
public void union() { NumberExpression<Integer> one = Expressions.ONE; NumberExpression<Integer> two = Expressions.TWO; NumberExpression<Integer> three = Expressions.THREE; Path<Integer> col1 = Expressions.path(Integer.class,"col1"); Union union = query.union( select(one.as(col1)), select(two), select(three)); if (templates.getDummyTable() == null) { if (templates.isUnionsWrapped()) { assertEquals( "(select 1 as col1)\n" + "union\n" + "(select 2)\n" + "union\n" + "(select 3)", union.toString()); } else { assertEquals( "select 1 as col1)\n" + "union\n" + "select 2\n" + "union\n" + "select 3", union.toString()); } } else { String dummyTable = templates.getDummyTable(); if (templates.isUnionsWrapped()) { assertEquals( "(select 1 as col1 from " + dummyTable + ")\n" + "union\n" + "(select 2 from " + dummyTable + ")\n" + "union\n" + "(select 3 from " + dummyTable + ")", union.toString()); } else { assertEquals( "select 1 as col1 from " + dummyTable + "\n" + "union\n" + "select 2 from " + dummyTable + "\n" + "union\n" + "select 3 from " + dummyTable, union.toString()); } } }
Source:
public static JsonValue makeRequest(String url) throws IOException { long startTime = 0; HttpClient httpClient = new DefaultHttpClient(); try { HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity entity = httpResponse.getEntity(); InputStream in = entity.getContent(); StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode != HttpStatus.SC_OK) { throw new IOException("The status code for " + url + " is not OK (200). It's " + statusCode); } try { JsonValue response = JsonValue.readFrom(new InputStreamReader( in)); return response; } catch (ParseException e) { throw new IOException(e); } } catch (Exception e) { if (e instanceof IOException) { throw (IOException) e; } throw new IOException(e); } finally { httpClient.getConnectionManager().shutdown(); } }

Target:
public static JsonValue makeRequest(String url) throws IOException { long startTime = 0; HttpClient httpClient = new DefaultHttpClient(); try { HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity entity = httpResponse.getEntity(); InputStream in = entity.getContent(); StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode != HttpStatus.SC_OK) { } try { JsonValue response = JsonValue.readFrom(new InputStreamReader( in)); return response; } catch (ParseException e) { throw new IOException(e); } } catch (Exception e) { if (e instanceof IOException) { throw (IOException) e; } throw new IOException(e); } finally { httpClient.getConnectionManager().shutdown(); } }
Source:
public Object execute(ExecutionEvent event) throws ExecutionException { Repository repository = getRepository(event); RevCommit commit = getSelectedCommit(event, repository); if (commit != null) { try { CommitEditor.open(new RepositoryCommit(repository, commit)); } catch (PartInitException e) { Activator.showError("Error opening commit viewer", e); } } return null; }

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { Repository repository = getRepository(event); RevCommit commit = getSelectedCommit(event, repository); if (commit != null) CommitEditor.openQuiet((new RepositoryCommit(repository, commit))); return null; }
Source:
public String asCql() { StringBuilder builder = new StringBuilder("UPDATE "); CqlHelper.qualify(keyspace, table, builder); if (timestamp != null) { builder.append(" USING TIMESTAMP "); if (timestamp instanceof BindMarker) { ((BindMarker) timestamp).appendTo(builder); } else { builder.append(timestamp); } } if (ttl != null) { builder.append(" USING TTL "); if (ttl instanceof BindMarker) { ((BindMarker) ttl).appendTo(builder); } else { builder.append(ttl); } } CqlHelper.append(assignments, builder, " SET ", ", ", null); CqlHelper.append(relations, builder, " WHERE ", " AND ", null); if (ifExists) { builder.append(" IF EXISTS"); } else { CqlHelper.append(conditions, builder, " IF ", " AND ", null); } return builder.toString(); }

Target:
public String asCql() { StringBuilder builder = new StringBuilder("UPDATE "); CqlHelper.qualify(keyspace, table, builder); if (timestamp != null) { builder.append(" USING TIMESTAMP "); if (timestamp instanceof BindMarker) { ((BindMarker) timestamp).appendTo(builder); } else { builder.append(timestamp); } } if (ttlInSeconds != null) { builder.append((timestamp != null) ? " AND " : " USING ").append("TTL "); if (ttlInSeconds instanceof BindMarker) { ((BindMarker) ttlInSeconds).appendTo(builder); } else { builder.append(ttlInSeconds); } } CqlHelper.append(assignments, builder, " SET ", ", ", null); CqlHelper.append(relations, builder, " WHERE ", " AND ", null); if (ifExists) { builder.append(" IF EXISTS"); } else { CqlHelper.append(conditions, builder, " IF ", " AND ", null); } return builder.toString(); }
Source:
protected void createCacheManagers() throws Throwable { cchf = new ControlledConsistentHashFactory.Default(new int[][]{{0, 1}, {1, 2}, {2, 3}, {3, 0}}); configBuilder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC); configBuilder.clustering().partitionHandling().whenSplit(PartitionHandling.DENY_READ_WRITES); configBuilder.clustering().hash().numSegments(4).stateTransfer().timeout(30000); globalBuilder = GlobalConfigurationBuilder.defaultClusteredBuilder(); globalBuilder.serialization().addAdvancedExternalizer(2500, new JGroupsAddress.Externalizer()); }

Target:
protected void createCacheManagers() throws Throwable { cchf = new ControlledConsistentHashFactory.Default(new int[][]{{0, 1}, {1, 2}, {2, 3}, {3, 0}}); configBuilder = getDefaultClusteredCacheConfig(CacheMode.DIST_SYNC); configBuilder.clustering().partitionHandling().whenSplit(PartitionHandling.DENY_READ_WRITES); configBuilder.clustering().hash().numSegments(4).stateTransfer().timeout(30000); globalBuilder = GlobalConfigurationBuilder.defaultClusteredBuilder(); globalBuilder.serialization().addAdvancedExternalizer(JBossUserMarshaller.USER_EXT_ID_MIN, new JGroupsAddress.Externalizer()); }
Source:
private List<Pair<String, String>> getSignalParams(Entry<Signal, Operation> signal) { List<Pair<String, String>> ret = new ArrayList<Pair<String, String>>(); for (Parameter param : signal.getValue().getOwnedParameters().stream() .filter(p -> !p.getType().getName().equals(signal.getKey().getName())).collect(Collectors.toList())) { ret.add(new Pair<String, String>(param.getType().getName(), param.getName())); } return ret; }

Target:
private List<Pair<String, String>> getSignalParams(Entry<Signal, Operation> signal) { List<Pair<String, String>> ret = new ArrayList<Pair<String, String>>(); List<Parameter> selfFilteredParameters = signal.getValue().getOwnedParameters().stream() .filter(p -> !p.getType().getName().equals(signal.getKey().getName())).collect(Collectors.toList()); for (Parameter param : selfFilteredParameters) { ret.add(new Pair<String, String>(param.getType().getName(), param.getName())); } return ret; }
Source:
public LocalCluster(String jarFileName, List<String> regexes, int siteCount, int hostCount, int kfactor, BackendTarget target) { this(jarFileName, siteCount, hostCount, kfactor, target, null); m_hasLocalServer = false; m_regexResults = new ConcurrentHashMap<>(); m_regexes = new ConcurrentHashMap<>(); for (int i = 0; i < regexes.size(); i++) { String s = regexes.get(i); Pattern p = Pattern.compile(s); m_regexes.put(s, p); } for (int i = 0; i < hostCount; i++) { m_regexResults.put(i, new ConcurrentHashSet<>()); } }

Target:
public LocalCluster(String jarFileName, List<String> regexes, int siteCount, int hostCount, int kfactor, BackendTarget target) { this(jarFileName, siteCount, hostCount, kfactor, target, null); m_hasLocalServer = false; m_logMessageMatchResults = new ConcurrentHashMap<>(); m_logMessageMatchPatterns = new ConcurrentHashMap<>(); for (int i = 0; i < regexes.size(); i++) { String s = regexes.get(i); Pattern p = Pattern.compile(s); m_logMessageMatchPatterns.put(s, p); } }
Source:
private static boolean proxyHolderContainsHost(ProxyHolder holder, String uriString) { return holder != null && (holder.getProxyMap().containsKey(uriString) || holder.getProxyMap().containsKey(uriString.substring(0, uriString.indexOf(":")))); }

Target:
private static boolean proxyHolderContainsHost(ProxyHolder holder, String uriString) { return holder != null && (holder.getProxyMap().containsKey(uriString) || (uriString.contains(":") && holder.getProxyMap().containsKey(uriString.substring(0, uriString.indexOf(":"))))); }
Source:
public void onCompletedTasksListToggled(boolean isExpanded) { if (!mQuickStartStore.getUncompletedTasksByType(AppPrefs.getSelectedSite(), mTasksType).isEmpty()) { return; } toggleCompletedView(!isExpanded); }

Target:
public void onCompletedTasksListToggled(boolean isExpanded) { if (mQuickStartStore.getUncompletedTasksByType(AppPrefs.getSelectedSite(), mTasksType).isEmpty()) { toggleCompletedView(!isExpanded); } }
Source:
public void rawSampleBuilderWithSingleInputYieldsThatInputWithInfiniteRate() throws IOException { Points<SimpleNumber> input = new Points<SimpleNumber>(); input.add(new Points.Point<SimpleNumber>(1234L, new SimpleNumber(3L))); BluefloodCounterRollup rollup = BluefloodCounterRollup.buildRollupFromRawSamples(input); Number count = rollup.getCount(); assertNotNull(count); assertThat(count, is(CoreMatchers.<Number>instanceOf(Long.class))); assertEquals(3L, count.longValue()); assertEquals(Double.POSITIVE_INFINITY, rollup.getRate(), 0.00001d); assertEquals(1, rollup.getSampleCount()); }

Target:
public void rawSampleBuilderWithSingleInputYieldsThatInputWithInfiniteRate() throws IOException { Points<SimpleNumber> input = new Points<SimpleNumber>(); input.add(new Points.Point<SimpleNumber>(1234L, new SimpleNumber(3L))); BluefloodCounterRollup rollup = BluefloodCounterRollup.buildRollupFromRawSamples(input); Number count = rollup.getCount(); assertNotNull(count); assertThat(count, is(CoreMatchers.<Number>instanceOf(Long.class))); assertEquals(3L, count.longValue()); assertTrue(Double.isInfinite(rollup.getRate())); assertTrue(rollup.getRate() > 0); assertEquals(1, rollup.getSampleCount()); }
Source:
protected void execute() { if(execThread.getState() == State.NEW) { log.debug("Starting exec thread"); this.execThread.start(); } if(this.completionLocks != null) { Set<ScriptedCommandCompletionLock> locksToRemove = new HashSet<>(); for(ScriptedCommandCompletionLock lock : this.completionLocks) { if(lock.updateLock()) { log.debug("Found lock to remove: " + lock.toString()); locksToRemove.add(lock); } } if(!locksToRemove.isEmpty()) { log.debug("Removing " + locksToRemove.size() + " locks"); completionLocks.removeAll(locksToRemove); } } }

Target:
public void execute() { if(execThread != null && execThread.getState() == State.NEW) { log.info("Starting exec thread"); this.execThread.start(); } if(execThread != null && this.completionLocks != null) { Set<ScriptedCommandCompletionLock> locksToRemove = new HashSet<>(); for(ScriptedCommandCompletionLock lock : this.completionLocks) { if(lock.updateLock()) { log.debug("Found lock to remove: " + lock.toString()); locksToRemove.add(lock); } } if(!locksToRemove.isEmpty()) { log.info("Removing " + locksToRemove.size() + " locks"); completionLocks.removeAll(locksToRemove); } } }
Source:
public static void setRobolectricPackageManager(RobolectricPackageManager newPackageManager) { if (packageManager != null) packageManager.reset(); packageManager = newPackageManager; }

Target:
public static void setRobolectricPackageManager(RobolectricPackageManager newPackageManager) { if (packageManager != null) { packageManager.reset(); } packageManager = newPackageManager; }
Source:
public boolean onPreferenceChange(Preference preference, Object newValue) { if (preference.equals(customApiUrlPref) && newValue instanceof String) { String apiUrl = (String) newValue; if (!TextUtils.isEmpty(apiUrl)) { Application.get().setCurrentRegion(null); if (BuildConfig.DEBUG) { Log.d(TAG, "User entered new API URL, set region to null."); } } else { if (BuildConfig.DEBUG) { Log.d(TAG, "User entered blank API URL, re-initializing regions..."); } NavHelp.goHome(this); } } else if (preference.equals(analyticsPref) && newValue instanceof Boolean) { Boolean isAnalyticsActive = (Boolean) newValue; if (!isAnalyticsActive) ObaAnalytics.reportEventWithCategory(ObaAnalytics.ObaEventCategory.APP_SETTINGS.toString(), getString(R.string.analytics_action_edit_general), getString(R.string.analytics_label_analytic_preference) + (isAnalyticsActive ? "YES" : "NO")); } return true; }

Target:
public boolean onPreferenceChange(Preference preference, Object newValue) { if (preference.equals(customApiUrlPref) && newValue instanceof String) { String apiUrl = (String) newValue; if (!TextUtils.isEmpty(apiUrl)) { Application.get().setCurrentRegion(null); if (BuildConfig.DEBUG) { Log.d(TAG, "User entered new API URL, set region to null."); } } else { if (BuildConfig.DEBUG) { Log.d(TAG, "User entered blank API URL, re-initializing regions..."); } NavHelp.goHome(this); } } else if (preference.equals(analyticsPref) && newValue instanceof Boolean) { Boolean isAnalyticsActive = (Boolean) newValue; if (!isAnalyticsActive) { ObaAnalytics.reportEventWithCategory(ObaAnalytics.ObaEventCategory.APP_SETTINGS.toString(), getString(R.string.analytics_action_edit_general), getString(R.string.analytics_label_analytic_preference) + (isAnalyticsActive ? "YES" : "NO")); GoogleAnalytics.getInstance(getBaseContext()).dispatchLocalHits(); } } return true; }
Source:
public void pairWithPin(String pin) { mySignerId = JPAKE_SIGNERID_SENDER; theirSignerId = JPAKE_SIGNERID_RECEIVER; jParty = new JPakeParty(mySignerId); secret = pin.substring(0, JPAKE_LENGTH_SECRET); channel = pin.substring(JPAKE_LENGTH_SECRET); channelUrl = jpakeServer + channel; prepareStagesAndStartWithPin(true); }

Target:
public void pairWithPin(String pin) { mySignerId = JPAKE_SIGNERID_SENDER; theirSignerId = JPAKE_SIGNERID_RECEIVER; jParty = new JPakeParty(mySignerId); secret = pin.substring(0, JPAKE_LENGTH_SECRET); channel = pin.substring(JPAKE_LENGTH_SECRET); channelUrl = jpakeServer + channel; prepareSenderStages(); runNextStage(); }
Source:
private boolean shouldValidateBillingPeriodDateRange(ContractsGrantsInvoiceDocument contractsGrantsInvoiceDocument) { String frequencyCode = contractsGrantsInvoiceDocument.getInvoiceGeneralDetail().getAward().getBillingFrequency().getFrequency(); if (StringUtils.equalsIgnoreCase(frequencyCode, ArIntegrationConstants.BillingFrequencyValues.LETTER_OF_CREDIT) || StringUtils.equalsIgnoreCase(frequencyCode, ArIntegrationConstants.BillingFrequencyValues.PREDETERMINED_BILLING) || StringUtils.equalsIgnoreCase(frequencyCode, ArIntegrationConstants.BillingFrequencyValues.MILESTONE)) { if (LOG.isDebugEnabled()) { LOG.debug("shouldValidateBillingPeriodDateRange, the billing frequency '" + frequencyCode + "' should NOT require validation of billing period date range "); } return false; } else { if (LOG.isDebugEnabled()) { LOG.debug("shouldValidateBillingPeriodDateRange, the billing frequency '" + frequencyCode + "' should require validation of billing period date range "); } return true; } }

Target:
private boolean shouldValidateBillingPeriodDateRange(ContractsGrantsInvoiceDocument contractsGrantsInvoiceDocument) { String frequencyCode = contractsGrantsInvoiceDocument.getInvoiceGeneralDetail().getBillingFrequencyCode(); if (StringUtils.equalsIgnoreCase(frequencyCode, ArIntegrationConstants.BillingFrequencyValues.LETTER_OF_CREDIT) || StringUtils.equalsIgnoreCase(frequencyCode, ArIntegrationConstants.BillingFrequencyValues.PREDETERMINED_BILLING) || StringUtils.equalsIgnoreCase(frequencyCode, ArIntegrationConstants.BillingFrequencyValues.MILESTONE)) { if (LOG.isDebugEnabled()) { LOG.debug("shouldValidateBillingPeriodDateRange, the billing frequency '" + frequencyCode + "' should NOT require validation of billing period date range "); } return false; } else { if (LOG.isDebugEnabled()) { LOG.debug("shouldValidateBillingPeriodDateRange, the billing frequency '" + frequencyCode + "' should require validation of billing period date range "); } return true; } }
Source:
public SqlStatements define(String key, Object value) { if (value != null) { attributes.put(key, value); } return this; }

Target:
public SqlStatements define(String key, Object value) { if (value == null) { attributes.remove(key); } else { attributes.put(key, value); } return this; }
Source:
public AsyncFuture<Void> sendMetrics(Collection<Metric> metrics) { final UUID traceId = UUID.randomUUID(); logger.info("{}: Start sending metrics", traceId); for (Metric metric : metrics) { try { final ApiFuture<String> publish; if (writeCache.isCached(metric)) { publish = ApiFutures.immediateFuture("Metric in cache"); } else { publish = publisher.publish(PubsubMessage.newBuilder() .setData(ByteString.copyFrom(serializer.serialize(metric))) .build() ); } ApiFutures.addCallback(publish, new ApiFutureCallback<String>() { @Override public void onFailure(Throwable t) { logger.error("Failed sending metrics {}", t.getMessage()); writeCache.remove(metric); } @Override public void onSuccess(String messageId) { } }, executorService); } catch (Exception e) { logger.error("Failed to publish metric {}", e); } } logger.info("{}: Finished sending metrics", traceId); return async.resolved(); }

Target:
public AsyncFuture<Void> sendMetrics(Collection<Metric> metrics) { logger.debug("Sending metrics", metrics.size()); try { final ByteString m = ByteString.copyFrom(serializer.serialize(metrics, writeCache)); publishPubSub(m); } catch (Exception e) { logger.error("Failed to serialize batch of metrics {}", e); } return async.resolved(); }
Source:
private Map<String, BasicAuthenticatorUser> loadUserMapFromDisk(String prefix) throws Exception { File userMapFile = new File(commonCacheConfig.getCacheDirectory(), getUserMapFilename(prefix)); if (!userMapFile.exists()) { return null; } return objectMapper.readValue( userMapFile, BasicAuthUtils.AUTHENTICATOR_USER_MAP_TYPE_REFERENCE ); }

Target:
private Map<String, BasicAuthenticatorUser> loadUserMapFromDisk(String prefix) throws IOException { File userMapFile = new File(commonCacheConfig.getCacheDirectory(), getUserMapFilename(prefix)); if (!userMapFile.exists()) { return null; } return objectMapper.readValue( userMapFile, BasicAuthUtils.AUTHENTICATOR_USER_MAP_TYPE_REFERENCE ); }
Source:
public static IConsole[] findConsole(IRemoteConnection connection) { ArrayList<IConsole> ret = new ArrayList<IConsole>(); IConsoleManager consoleManager = ConsolePlugin.getDefault().getConsoleManager(); IConsole[] consoles = consoleManager.getConsoles(); boolean[] indices = new boolean[consoles.length]; for (IConsole console : consoles) { if (console instanceof TerminalConsole) { TerminalConsole terminalConsole = (TerminalConsole) console; if (terminalConsole.getConnection().equals(connection)) { ret.add(terminalConsole); } } } return (IConsole[]) ret.toArray(new IConsole[ret.size()]); }

Target:
public static List<IConsole> findConsole(IRemoteConnection connection) { ArrayList<IConsole> ret = new ArrayList<IConsole>(); IConsoleManager consoleManager = ConsolePlugin.getDefault().getConsoleManager(); IConsole[] consoles = consoleManager.getConsoles(); for (IConsole console : consoles) { if (console instanceof TerminalConsole) { TerminalConsole terminalConsole = (TerminalConsole) console; if (terminalConsole.getConnection().equals(connection)) { ret.add(terminalConsole); } } } return ret; }
Source:
protected static List<ReferenceWithSentimentLabels> convertCitationSentiment(CharSequence publicationId, List<ReferenceMetadata> references, List<CitationSentiment> sentiments) { Preconditions.checkArgument(references.size() != sentiments.size(), "number of sentiments: " + sentiments.size() + " is not equal the number of input references: " + references.size()); List<ReferenceWithSentimentLabels> results = new ArrayList<ReferenceWithSentimentLabels>(references.size()); for (int i = 0; i < references.size(); i++) { ReferenceWithSentimentLabels result = convertCitationSentiment(publicationId, references.get(i), sentiments.get(i)); if (result != null) { results.add(result); } } return results; }

Target:
protected static List<ReferenceWithSentimentLabels> convertCitationSentiment(CharSequence publicationId, List<ReferenceMetadata> references, List<CitationSentiment> sentiments) { Preconditions.checkArgument(references.size() != sentiments.size(), "number of sentiments: %s is not equal the number of input references: %s", sentiments.size(), references.size()); List<ReferenceWithSentimentLabels> results = new ArrayList<ReferenceWithSentimentLabels>(references.size()); for (int i = 0; i < references.size(); i++) { ReferenceWithSentimentLabels result = convertCitationSentiment(publicationId, references.get(i), sentiments.get(i)); if (result != null) { results.add(result); } } return results; }