auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public BufferedEventSender(int maxCap) { this.queue = new ArrayBlockingQueue<>(maxCap, START true); END } Do we really need the queue to be fair? My understanding is that there is a kafka queue in the transport, and that queue probably isn't maintaining full order anyway (if we have multiple partitions).

Target:
BufferedEventSender(int maxCap) { this.queue = new ArrayBlockingQueue<>(maxCap); }
Source:
MergingUpdater(AbstractTripleStore database) { this.database = database; String property = START System.getProperty("outputDumps"); END outputDumps = Boolean.TRUE.toString().equals(property); id = UUID.randomUUID().toString().replaceAll("-", ""); } configuration should be injected, not read from system properties in the constructor.

Target:
MergingUpdater(AbstractTripleStore database) { this(database, /* outputDumps */ false); }
Source:
private int codepointAt(final int idx) { START if (idx < 0 || idx >= text.length) { END return 0; } return text[idx]; } could this hide bugs? Would it make sense to throw an exception or simply remove the check? Also because 0x0 is a valid code point this makes this return value a bit ambiguous. I'd be in favor of just accessing the array and let the JVM throw an error if this is possible.

Target:
private int codepointAt(final int idx) { if (idx < 0) { return -1; } return text[idx]; }
Source:
void START replaceScriptOne(StringBuilder END scriptOne) { translate(scriptOne, scriptOneToScriptTwo); } nit: Should be public

Target:
public void replaceScriptOne(StringBuilder scriptOne) { translate(scriptOne, scriptOneToScriptTwo); }
Source:
START public void unregSwitch(boolean synch) { END super.unregisterDP(synch); } What's this method for? Why is it public?

Target:
protected void unregSwitch(boolean synch) { super.unregisterDP(synch); }
Source:
START public synchronized boolean removeSwitch(final long ovxDpid) { END this.dpidCounter.releaseIndex((int) (0x000000 << 32 | ovxDpid)); OVXSwitch sw = this.getSwitch(ovxDpid); boolean down = sw.tearDown(); if (down) { sw.unregister(); } return down; } If the validation step in the api throws an exception then this is not necessary.

Target:
public synchronized void removeSwitch(final long ovxDpid) { this.dpidCounter.releaseIndex((int) (0x000000 << 32 | ovxDpid)); OVXSwitch sw = this.getSwitch(ovxDpid); sw.tearDown(); sw.unregister(); }
Source:
START public double getLatitude() { END return mLatitude; } Please make getters final

Target:
public final double getLatitude() { return mLatitude; }
Source:
public int getUserId(String userName) { resultSet = executor.executeQuery("SELECT User_ID FROM Users WHERE Name LIKE '" + userName + "';"); if(resultSet == null) return -1; else { try { while(resultSet.next()) { return resultSet.getInt("User_ID"); } } catch (SQLException e) { START new IllegalStateException("SQL Error: " + e); END } } return -1; } throw that please

Target:
public int getUserId(String userName) { resultSet = executor.executeQuery("SELECT User_ID FROM Users WHERE Name LIKE '" + userName + "';"); if(resultSet == null) return -1; else { try { while(resultSet.next()) { return resultSet.getInt("User_ID"); } } catch (SQLException e) { throw new IllegalStateException("SQL Error: " + e); } } return -1; }
Source:
public List<Thread> getThreads() { try { getResult(); } catch (SQLException e) { START new IllegalStateException("SQL Error: " + e); END } return threads; } should be thrown, the others as well

Target:
public List<Thread> getThreads() { try { getResult(); } catch (SQLException e) { throw new IllegalStateException("SQL Error: " + e); } return threads; }
Source:
public void setLatitude(double latitude) { START this.mLatitude = END latitude; } avoid using this.

Target:
public void setLatitude(double latitude) { mLatitude = latitude; }
Source:
public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mContext = getActivity().getApplicationContext(); mDataBaseAdapter = new DataBaseAdapter(getActivity()); mDataBaseAdapter.createDatabase(); mDataBaseAdapter.open(); mItemAdapter = new ATMItemListAdapter(mContext, ((MainActivity) getActivity()).getLocationTracker()); setListAdapter(mItemAdapter); getLoaderManager().initLoader(0, null, this); START getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); END } already set in xml

Target:
public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mContext = getActivity().getApplicationContext(); mDataBaseAdapter = new DataBaseAdapter(getActivity()); mDataBaseAdapter.createDatabase(); mDataBaseAdapter.open(); mItemAdapter = new ATMItemListAdapter(mContext, ((MainActivity) getActivity()).getLocationTracker()); setListAdapter(mItemAdapter); getLoaderManager().initLoader(0, null, this); }
Source:
START public Cursor getAddress(String rowId, String[] columns) { END String selection = "rowId = ?"; String[] selectionArgs = new String[]{rowId}; return query(selection, selectionArgs, columns); } Make final

Target:
public final Cursor getAddress(String rowId, String[] columns) { String selection = "rowId = ?"; String[] selectionArgs = new String[]{rowId}; return query(selection, selectionArgs, columns); }
Source:
START public Cursor getWordMatches(String query, String[] columns) { END String selection = KEY_ADDRESS + " LIKE ?"; String[] selectionArgs = new String[] {"%" + query + "%"}; return query(selection, selectionArgs, columns); } Make final

Target:
public final Cursor getWordMatches(String query, String[] columns) { String selection = KEY_ADDRESS + " LIKE ?"; String[] selectionArgs = new String[] {"%" + query + "%"}; return query(selection, selectionArgs, columns); }
Source:
public void onListItemClick(ListView listView, View view, int position, long id) { START Log.i("list", END "onListItemClick"); super.onListItemClick(listView, view, position, id); ATMItem item = (ATMItem) getListAdapter().getItem(position); mDataManager.setCurrentItem(item); mModeChangeRequester.onModeChange(ModesManager.ModeIndex.DETAIL); } use const LOG

Target:
public void onListItemClick(ListView listView, View view, int position, long id) { super.onListItemClick(listView, view, position, id); ATMItem item = (ATMItem) getListAdapter().getItem(position); mDataManager.setCurrentItem(item); mModeChangeRequester.onModeChange(ModesManager.ModeIndex.DETAIL); }
Source:
protected boolean isDuplicateEntry(String token, Usage usageRecord) { try { ClientResponse response = client.getEntry(token, usageRecord.getUuid()); if (response.getStatus() == 200) { return true; } } catch (Exception e) { LOG.warn(String.format("Could not verify duplicate entry for UUID: %s, attempt to re-push the record...", usageRecord.getUuid())); START return false; END } return false; } NIT: this really isn't needed since this method returns false by default.

Target:
protected boolean isDuplicateEntry(String token, Usage usageRecord) { try { ClientResponse response = client.getEntry(token, usageRecord.getUuid()); if (response.getStatus() == 200) { return true; } } catch (Exception e) { LOG.warn(String.format("Could not verify duplicate entry for UUID: %s, attempt to re-push the record...", usageRecord.getUuid())); } return false; }
Source:
public boolean onCreate() { START mDatabaseAdapter = new DataBaseAdapter(getContext(), SharedData.getInstance()); END return true; } Use SharedData inside DataBaseAdapter.

Target:
public boolean onCreate() { mDatabaseAdapter = new DataBaseAdapter(getContext()); return true; }
Source:
START public void serialize(ByteBuffer bb) { END bb.put(data, 0, getLength()); } should return an int

Target:
public int serialize(ByteBuffer bb) { int length = getLength(); bb.put(data, 0, length); return length; }
Source:
private void registerCallbacks() { view.addCloseOnClickListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int index = MainView.getInstance().indexOfComponent(view); MainView.getInstance().remove(index); view.revalidate(); view.repaint(); MainView.getInstance().setSelectedIndex(0); } START }); END } Something seems wrong with tabbing in this function

Target:
private void registerCallbacks() { view.addCloseOnClickListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { final int index = MainView.getInstance().indexOfComponent(view); MainView.getInstance().remove(index); view.revalidate(); view.repaint(); MainView.getInstance().setSelectedIndex(0); } }); }
Source:
public void bridgeDeleteVxLanPort(UUID bridgeId, IPv4Addr mgmtIp) throws SerializationException, StateAccessException { Bridge b = bridgesGet(bridgeId); if (b == null || b.getVxLanPortIds() == null) { return; } for (UUID portId : b.getVxLanPortIds()) { VxLanPort p = (VxLanPort)portsGet(portId); START if (p.getMgmtIpAddr().equals(mgmtIp)) { END bridgeDeleteVxLanPort(p); return; } } } Check p is null?

Target:
public void bridgeDeleteVxLanPort(UUID bridgeId, IPv4Addr mgmtIp) throws SerializationException, StateAccessException { Bridge b = bridgesGet(bridgeId); if (b == null) { return; } for (UUID portId : b.getVxLanPortIds()) { VxLanPort p = (VxLanPort)portsGet(portId); if (p.getMgmtIpAddr().equals(mgmtIp)) { bridgeDeleteVxLanPort(p); return; } } }
Source:
public JumpRule( Condition condition, UUID jumpToChainID, String jumpToChainName) { super(condition, START Action.JUMP); END this.jumpToChainID = jumpToChainID; this.jumpToChainName = jumpToChainName; } I guess this won't affect compatibility with previous deployments (when reading/writing to ZK), but it would be nice if somebody can confirm.

Target:
public JumpRule( Condition condition, UUID jumpToChainID, String jumpToChainName) { super(condition, null); this.jumpToChainID = jumpToChainID; this.jumpToChainName = jumpToChainName; }
Source:
public void afterFromProto(MessageOrBuilder proto) { condition = ZoomConvert.fromProto(proto, Condition.class); Topology.Rule rule = (Topology.Rule) proto; if (rule.getType() == Topology.Rule.Type.NAT_RULE && rule.getMatchForwardFlow()) { START ForwardNatRule natRule = (ForwardNatRule) this; natRule.buildFields(); END } validateProto(rule); } Wouldn't have been possible to override the afterFromProto in the ForwardNatRule class, adding there any initialization code as needed?

Target:
public void afterFromProto(MessageOrBuilder proto) { condition = ZoomConvert.fromProto(proto, Condition.class); validateProto((Topology.Rule) proto); }
Source:
public void beforeToProto() { throw new ZoomConvert.ConvertException("Conversion of an object of " + "class: " + START this.getClass() END + " to a protocol buffer is not " + "supported"); } Nit: not needed

Target:
public void beforeToProto() { throw new ZoomConvert.ConvertException("Conversion of an object of " + "class: " + getClass() + " to a protocol buffer is not " + "supported"); }
Source:
public void testConversionForByteFields() { TestableZoomObject2 pojo = new TestableZoomObject2(); TestMessage proto = pojo.toProto(TestMessage.class); assertTrue(pojo.compare(proto)); TestableZoomObject2 convertedPojo = ZoomConvert.fromProto(proto, TestableZoomObject2.class); START assertTrue(pojo.equals(convertedPojo)); END } i.e. assertEquals?

Target:
public void testConversionForByteFields() { TestableZoomObject2 pojo = new TestableZoomObject2(); TestMessage proto = pojo.toProto(TestMessage.class); assertTrue(pojo.compare(proto)); TestableZoomObject2 convertedPojo = ZoomConvert.fromProto(proto, TestableZoomObject2.class); assertEquals(pojo, convertedPojo); }
Source:
public OverpassDataFetcher() { START url = "http://www.overpass-api.de/api/interpreter?data="; END } zamiast tego czysciej bedzie jak zrobisz this("http://www.overpass-api.de/api/interpreter?data=");

Target:
public OverpassDataFetcher() { this("http://www.overpass-api.de/api/interpreter?data="); }
Source:
public void loadStyle(int styleId) { String style = StyleLoader.ReadStringFromResource(context, styleId); START StyleParser zoomParser = new ZoomStyleParser(); END styles = zoomParser.getStyleSet(style); } czy tworzenie nowej instancji zoomstyleparser'a za kazdym razem ma sens? Moze lepiej przechowywac go jako pole?

Target:
public void loadStyle(int styleId) { String style = StyleLoader.ReadStringFromResource(context, styleId); styles = zoomParser.getStyleSet(style); }
Source:
public void setPosition(float x, float y) { START if (mapSize.x < x && mapSize.y < y) { END offset.x = x; offset.y = y; } } Nie pomyli?e? tu przypadkiem kierunków znaków?! Teraz jest chyba, ?e je?li wykracza poza mapSize. :D

Target:
public void setPosition(float x, float y) { if (x < mapSize.x && y < mapSize.y) { offset.x = x; offset.y = y; } }
Source:
public MarketHistory(Market market) { START super(); END this.market = market; history = new HashMap<String, List<Double>>(); } I think we do not need super() in this file.

Target:
public MarketHistory(Market market) { this.market = market; history = new HashMap<String, List<Double>>(); }
Source:
public static Order findAndExtractOrder(ArrayList<Order> position, String symbol) { START for (Order stock : position) { END if (stock.getStockSymbol().equals(symbol)) { position.remove(stock); return stock; } } return null; } Before go through the loop make sure that position and symbol parameters are not null.

Target:
public static Order findAndExtractOrder(ArrayList<Order> position, String symbol) { if(position != null && symbol != null){ for (Order stock : position) { if (stock.getStockSymbol().equals(symbol)) { position.remove(stock); return stock; } } } return null; }
Source:
public static int ownedQuantity(ArrayList<Order> position, String symbol) { int ownedQuantity = 0; for (Order stock : position) { if (stock.getStockSymbol().equals(symbol)) { START ownedQuantity += stock.getSize(); END } } return ownedQuantity; } unsafe addition, can cause integer overflow. use long instead of integer

Target:
public static int ownedQuantity(ArrayList<Order> position, String symbol) { long ownedQuantity = 0; for (Order stock : position) { if (stock.getStockSymbol().equals(symbol)) { ownedQuantity += stock.getSize(); } } return ownedQuantity; }
Source:
public Market(String name) { START this.marketName = name; END stockList = new HashMap<String, Stock>(); marketHistory = new MarketHistory(this); orderBook = new OrderBook(this); } Redundant variable name - just use "name"

Target:
public Market(String name) { this.name = name; stockList = new HashMap<String, Stock>(); marketHistory = new MarketHistory(this); orderBook = new OrderBook(this); }
Source:
public Trader(String name, double cashInHand) { START super(); END this.name = name; this.cashInHand = cashInHand; this.stocksOwned = new ArrayList<Order>(); this.ordersPlaced = new ArrayList<Order>(); } We don't need super here

Target:
public Trader(String name, double cashInHand) { this.name = name; this.cashInHand = cashInHand; this.stocksOwned = new ArrayList<Order>(); this.ordersPlaced = new ArrayList<Order>(); }
Source:
public MarketHistory(Market m) { START super(); END this.market = m; history = new HashMap<String, List<Double>>(); } We don't need super here

Target:
public MarketHistory(Market m) { this.market = m; history = new HashMap<String, List<Double>>(); }
Source:
public Trader(String traderName, double cashInHand) { START super(); END this.name = name; this.cashInHand = cashInHand; this.position = new ArrayList<Order>(); this.ordersPlaced = new ArrayList<Order>(); } Unnecessary call to super()

Target:
public Trader(String traderName, double cashInHand) { this.name = name; this.cashInHand = cashInHand; this.position = new ArrayList<Order>(); this.ordersPlaced = new ArrayList<Order>(); }
Source:
public static boolean isAlreadyPresent(ArrayList<Order> ordersPlaced, Order newOrder) { for (Order orderPlaced : ordersPlaced) { if START (((orderPlaced instanceof BuyOrder) && (newOrder instanceof BuyOrder)) || ((orderPlaced instanceof SellOrder) && (newOrder instanceof SellOrder))) { END if (orderPlaced.getStockSymbol().equals( newOrder.getStockSymbol())) { return true; } } } return false; } a lot of conditionals makes this less readable.

Target:
public static boolean isAlreadyPresent(ArrayList<Order> ordersPlaced, Order newOrder) { for (Order orderPlaced : ordersPlaced) { if ((orderPlaced instanceof BuyOrder) && (newOrder instanceof BuyOrder)){ if ((orderPlaced instanceof SellOrder) && (newOrder instanceof SellOrder)){ if (orderPlaced.getStockSymbol().equals( newOrder.getStockSymbol())) { return true; } } } } return false; }
Source:
public Trader(String name, double cashInHand) { START super(); END this.name = name; this.cashInHand = cashInHand; this.position = new ArrayList<Holding>(); this.ordersPlaced = new ArrayList<Order>(); } Unnecessary call to super

Target:
public Trader(String name, double cashInHand) { this.name = name; this.cashInHand = cashInHand; this.position = new ArrayList<Holding>(); this.ordersPlaced = new ArrayList<Order>(); }
Source:
public START BuyOrder(String END inputStock, int sizeIn, double priceIn, Trader traderIn) { stockSymbol = inputStock; size = sizeIn; price = priceIn; trader = traderIn; } you aren't calling super class. add super(params)

Target:
public BuyOrder(String inputStock, int sizeIn, double priceIn, Trader traderIn) { super(); stockSymbol = inputStock; size = sizeIn; price = priceIn; trader = traderIn; }
Source:
START public void END setBuyOrders(HashMap<String, ArrayList<Order>> buyOrders) { this.buyOrders = buyOrders; } this method should be changed to private

Target:
private void setBuyOrders(HashMap<String, ArrayList<Order>> buyOrders) { this.buyOrders = buyOrders; }
Source:
public MarketHistory(Market m) { super(); START this.m = market; END history = new HashMap<String, List<Double>>(); } This should have been changed to: this.market = m;

Target:
public MarketHistory(Market m) { super(); this.market = m; history = new HashMap<String, List<Double>>(); }
Source:
public boolean equals(Object obj) { if (null == obj || !(obj instanceof TestableZoomObject2)) return false; TestableZoomObject2 o = (TestableZoomObject2) obj; return START byteField.equals(o.byteField) END && byteSet.equals(o.byteSet); } NPE risk?

Target:
public boolean equals(Object obj) { if (null == obj || !(obj instanceof TestableZoomObject2)) return false; TestableZoomObject2 o = (TestableZoomObject2) obj; return null != byteField && null != byteSet && byteField.equals(o.byteField) && byteSet.equals(o.byteSet); }
Source:
public void onClick(View v){ START if(butPlus == v){ END }else if(butMinus == v){ }else if(butUp == v){ }else if(butDown == v){ } } Zawsze robi?em/widzia?em tak to zrobione: int id = v.getId(); if(id == R.id.butPlus)

Target:
public void onClick(View v){ int id = v.getId(); if(id == R.id.butPlus){ }else if(id == R.id.butMinus){ }else if(id == R.id.butUp){ }else if(id == R.id.butDown){ } }
Source:
public Router get(@PathParam("id") UUID id) throws StateAccessException, SerializationException { if (!authorizer.authorize(context, AuthAction.READ, id)) { throw new ForbiddenHttpException( "Not authorized to view this router."); } org.midonet.cluster.data.Router routerData = dataClient.routersGet(id); if (routerData == null) { throw new NotFoundHttpException( "The requested resource was not found."); } // Convert to the REST API DTO Router router = START RouterDataConverter.fromData(routerData); END router.setBaseUri(getBaseUri()); return router; } optional: add uri as a parameter and turn this into return RouterDataConverter.fromData(routerData, getBaseUri()) here and in other usages below

Target:
public Router get(@PathParam("id") UUID id) throws StateAccessException, SerializationException { if (!authorizer.authorize(context, AuthAction.READ, id)) { throw new ForbiddenHttpException( "Not authorized to view this router."); } org.midonet.cluster.data.Router routerData = dataClient.routersGet(id); if (routerData == null) { throw new NotFoundHttpException( "The requested resource was not found."); } // Convert to the REST API DTO return RouterDataConverter.fromData(routerData, getBaseUri()); }
Source:
public void setUserPages(UserPages userPages) { this.userPages = userPages; START userPagesNull = false; END } Good call. Whoops. Although, might want to check if the new userPages object is null, and possibly set it to true, in case someone is TRYING to null it out. :)

Target:
public void setUserPages(UserPages userPages) { this.userPages = userPages; if (userPages == null) { userPagesNull = true; } else { userPagesNull = false; } }
Source:
public static WebAppDescriptor.Builder getBuilder() { if START (!isCompatApiEnabled()) END { return getBuilderForVladimir(); } else { return getBuilderForLegacyApi(); } } revert, although this will be useful to see the tests running on v2 on the gate :D

Target:
public static WebAppDescriptor.Builder getBuilder() { if (isCompatApiEnabled()) { return getBuilderForVladimir(); } else { return getBuilderForLegacyApi(); } }
Source:
public NatRule(Condition condition, Action action, boolean dnat) { super(condition, action); this.dnat = dnat; START if (!action.equals(Action.ACCEPT) && END !action.equals(Action.CONTINUE) && !action.equals(Action.RETURN)) { throw new IllegalArgumentException("A nat rule's action " + "must be one of: ACCEPT, CONTINUE, or RETURN."); } } again, scala type in java code.

Target:
public NatRule(Condition condition, Action action, boolean dnat) { super(condition, action); this.dnat = dnat; if (!action.equals(Action.ACCEPT) && !action.equals(Action.CONTINUE) && !action.equals(Action.RETURN)) throw new IllegalArgumentException("A nat rule's action " + "must be one of: ACCEPT, CONTINUE, or RETURN."); }
Source:
public LiteralRule(Condition condition, Action action, UUID chainId) { super(condition, action, chainId); if (action != Action.ACCEPT && action != Action.DROP START && action END != Action.REJECT && action != Action.RETURN) throw new IllegalArgumentException("A literal rule's action " + "must be one of: ACCEPT, DROP, REJECT or RETURN."); } The trailing curly brace is missing here. && action != Action.REJECT && action != Action.RETURN) {

Target:
public LiteralRule(Condition condition, Action action, UUID chainId) { super(condition, action, chainId); if (action != Action.ACCEPT && action != Action.DROP && action != Action.REJECT && action != Action.RETURN) { throw new IllegalArgumentException("A literal rule's action " + "must be one of: ACCEPT, DROP, REJECT or RETURN."); } }
Source:
public static boolean isCompatApiEnabled() { return START Boolean.parseBoolean(System.getenv("midonet.newStack")); END } return System.getProperty("midonet.newStack") != null;

Target:
public static boolean isCompatApiEnabled() { return System.getProperty("midonet.newStack") != null; }
Source:
public void setUp() throws Exception { super.setUp(); loadBalancer = createStockLoadBalancer(); START PoolResName = FuncTest.isCompatApiEnabled() ? "Pool" : "pool"; HmResName = FuncTest.isCompatApiEnabled() ? "HealthMonitor" : "health monitor"; END } we're not running v1 tests anymore, so you can use the v2 option

Target:
public void setUp() throws Exception { super.setUp(); loadBalancer = createStockLoadBalancer(); }
Source:
public void afterFromProto(Message proto) { super.afterFromProto(proto); switch (action) { START case ACCEPT: flowAction = Rule.Accept; break; case DROP: flowAction = Rule.Drop; break; case REDIRECT: flowAction = Rule.Redirect; break; END default: throw new IllegalArgumentException("Invalid action"); } } Only accept and redirect are used now. I don't think Drop is needed. Accept is only needed for the case where you want to pop/push a vlan without redirecting.

Target:
public void afterFromProto(Message proto) { super.afterFromProto(proto); switch (action) { case ACCEPT: flowAction = Rule.Accept; break; case REDIRECT: flowAction = Rule.Redirect; break; default: throw new IllegalArgumentException("Invalid action"); } }
Source:
public static void scanNestedAttribute(ByteBuffer buf, AttributeHandler handler) { int start = buf.position(); int end = buf.limit(); START while (buf.remaining() > ATTR_HEADER_LEN) { END short attrLen = buf.getShort(); // This is always 1 for the nested len. short attrId = nested(buf.getShort()); buf.limit(end); handler.use(buf, attrId); buf.position(start); } } infinite loop! also, the buf.limit is not needed

Target:
public static void scanNestedAttribute(ByteBuffer buf, AttributeHandler handler) { int start = buf.position(); if (buf.remaining() > ATTR_HEADER_LEN) { short attrLen = buf.getShort(); // This is always 1 for the nested len. short attrId = nested(buf.getShort()); handler.use(buf, attrId); buf.position(start); } }
Source:
public URI getServiceContainerGroup() { START if (serviceGroupId == null) { return null; } END return absoluteUri(SERVICE_CONTAINER_GROUPS, serviceGroupId); } Nit: I think this is not really needed, since absoluteUri does this check.

Target:
public URI getServiceContainerGroup() { return absoluteUri(SERVICE_CONTAINER_GROUPS, serviceGroupId); }
Source:
public static String convertFromIpsecString(String str) { if (str == null) return null; try { return str.replace('-', '_').toUpperCase(); START } catch (IllegalArgumentException ex) { END // TODO: Log exception. return null; } } This shouldn't get thrown.

Target:
public static String convertFromIpsecString(String str) { if (str == null) { return null; } return str.replace('-', '_').toUpperCase(); }
Source:
public String toString(){ StringBuilder sb = new StringBuilder(); sb.append("{ regEx=\"").append(regExString). append("\", className=\"").append(someClass.getCanonicalName()). START append("}"); END return sb.toString(); } This could maybe be done more cleanly with a stringformatter, but this is probably fine too.

Target:
public String toString() { StringBuilder sb = new StringBuilder(); return "{ regEx=\"" + regExString + "\", className=\"" + someClass.getCanonicalName() + "}"; }
Source:
public void showProgressDialog(Context context) { if (!mShowDialog) { return; } if (mProgressDialog == null) { if (TextUtils.isEmpty(mDialogMsg)) { mDialogMsg = "Loading. Please wait..."; } mProgressDialog = ProgressDialog.show(context, "", mDialogMsg, true); return; } if (mProgressDialog.isShowing()) { return; } START END mProgressDialog.show(); } Problem je context koji se menja, zato treba izbeci ovaj if. public void showProgressDialog(Context context) { if (!mShowDialog) { return; } if (TextUtils.isEmpty(mDialogMsg)) { mDialogMsg = "Loading. Please wait..."; } if (mProgressDialog != null && mProgressDialog.isShowing()) { return; } mProgressDialog = ProgressDialog.show(context, "", mDialogMsg, true); }

Target:
public void showProgressDialog(Context context) { if (!mShowDialog) { return; } if (mProgressDialog != null && mProgressDialog.isShowing()) { return; } if (TextUtils.isEmpty(mDialogMsg)) { mDialogMsg = "Loading. Please wait..."; } mProgressDialog = ProgressDialog.show(context, "", mDialogMsg, true); }
Source:
public byte[] getBody() throws AuthFailureError { VolleyLog.e(mBodyContent); if (mBodyContent == null) START { END return super.getBody(); } return mBodyContent.getBytes(); } if (mBodyContent.equals("null"))

Target:
public byte[] getBody() throws AuthFailureError { if (mBodyContent == null) { return super.getBody(); } return mBodyContent.getBytes(); }
Source:
void resetButtons() { for (int i = 0; i < fieldSize; i++) START for (int j = 0; j < fieldSize; j++) arrayOfButtons[i][j].setGraphic(new ImageView(imageEmpty)); END field.resetLogic(); } braces

Target:
void resetButtons() { for (int i = 0; i < fieldSize; i++) for (int j = 0; j < fieldSize; j++) { arrayOfButtons[i][j].setGraphic(new ImageView(imageEmpty)); } field.resetLogic(); }
Source:
public boolean moveCellsUp() { boolean dirty = false; if (moveCellsUpLoop()) dirty = true; for (int i = 0; i < GRID_WIDTH; i++) { for (int j = 0; j < (GRID_WIDTH - 1); j++) { int nextJ = j + 1; dirty = combineCells(i, nextJ, i, j, dirty); } } if START (moveCellsUpLoop()) dirty = true; END return dirty; } braces

Target:
public boolean moveCellsUp() { boolean dirty = false; if (moveCellsUpLoop()) { dirty = true; } for (int i = 0; i < GRID_WIDTH; i++) { for (int j = 0; j < (GRID_WIDTH - 1); j++) { int nextJ = j + 1; dirty = combineCells(i, nextJ, i, j, dirty); } } if (moveCellsUpLoop()) { dirty = true; } return dirty; }
Source:
public boolean moveCellsDown() { boolean dirty = false; if START (moveCellsDownLoop()) dirty = true; END for (int i = 0; i < GRID_WIDTH; i++) { for (int j = GRID_WIDTH - 1; j > 0; j--) { int previousJ = j - 1; dirty = combineCells(i, previousJ, i, j, dirty); } } if (moveCellsDownLoop()) dirty = true; return dirty; } braces

Target:
public boolean moveCellsDown() { boolean dirty = false; if (moveCellsDownLoop()) { dirty = true; } for (int i = 0; i < GRID_WIDTH; i++) { for (int j = GRID_WIDTH - 1; j > 0; j--) { int previousJ = j - 1; dirty = combineCells(i, previousJ, i, j, dirty); } } if (moveCellsDownLoop()) { dirty = true; } return dirty; }
Source:
public void randomField() { START for (int i = 0; i < width; i++) for (int j = 0; j < height; j++) { currentGeneration[i][j] = (int) (Math.random() * 2) == 0 ? (byte) 1 : (byte) 0; } END } braces

Target:
public void randomField() { for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { currentGeneration[i][j] = (int) (Math.random() * 2) == 0 ? (byte) 1 : (byte) 0; } } }
Source:
START private short X(short x) { END if (x == -1) return (short) (width - 1); if (x == width) return (short) 0; return x; } bad name of method https://google.github.io/styleguide/javaguide.html#s4-formatting

Target:
private short X(short x) { if (x == -1) { return (short) (width - 1); } if (x == width) { return (short) 0; } return x; }
Source:
private byte newCellState(byte cellSelf, byte neighbourCount) { if (cellSelf == 0) { START if (neighbourCount == 3) return (byte) 1; else return (byte) 0; END } else { if (neighbourCount == 2 || neighbourCount == 3) return (byte) 1; else return (byte) 0; } } braces

Target:
private byte newCellState(byte cellSelf, byte neighbourCount) { if (cellSelf == 0) { if (neighbourCount == 3) { return (byte) 1; } else { return (byte) 0; } } else { if (neighbourCount == 2 || neighbourCount == 3) { return (byte) 1; } else { return (byte) 0; } } }
Source:
public void setDelay(int delay) { START if ((this.delay > 999 && this.delay < delay) || (this.delay < 6 && this.delay > delay)) return; else this.delay = delay; END } braces

Target:
public void setDelay(int delay) { if ((this.delay > 999 && this.delay < delay) || (this.delay < 6 && this.delay > delay)) { return; } else { this.delay = delay; } }
Source:
public void dispose() { this.h.removeMessages(EVENT_DTMF_DONE); this.h.removeMessages(EVENT_PAUSE_DONE); this.h.removeMessages(EVENT_NEXT_POST_DIAL); this.parent.dispose(); START END this.h = null; this.owner = null; this.parent = null; } > Use this.h.removeCallbacksAndMessages(null) instead. Done in Patch Set 2

Target:
public void dispose() { }
Source:
public void dispose() { //Remove all messages from the queue START this.removeCallbacksAndMessages(null); END this.phone = null; } > Use this.removeCallbacksAndMessages(null) instead. Done in Patch set 2

Target:
public void dispose() { }
Source:
public void dispose() { //Unregister for all events phone.mCM.unregisterForRUIMReady(this); phone.mCM.unregisterForOffOrNotAvailable( this); phone.mCM.unSetOnIccRefresh(this); //Remove all messages from the queue START this.removeCallbacksAndMessages(null); END this.recordsLoadedRegistrants = null; this.phone = null; } > Use this.removeCallbacksAndMessages(null) instead. Done in Patch set 2

Target:
public void dispose() { //Unregister for all events phone.mCM.unregisterForRUIMReady(this); phone.mCM.unregisterForOffOrNotAvailable( this); phone.mCM.unSetOnIccRefresh(this); }
Source:
public void dispose() { //Remove all messages from the queue START this.removeCallbacksAndMessages(null); END this.phone = null; } > Use this.removeCallbacksAndMessages(null) instead. Done in Patch set 2

Target:
public void dispose() { super.dispose(); }
Source:
public void dispose() { //Unregister for all events phone.mCM.unregisterForSIMLockedOrAbsent(this); phone.mCM.unregisterForOffOrNotAvailable(this); phone.mCM.unregisterForSIMReady(this); //Remove all messages from the queue START this.removeCallbacksAndMessages(null); END this.absentRegistrants = null; this.pinLockedRegistrants = null; this.networkLockedRegistrants = null; this.status = null; this.phone = null; } > Use this.removeCallbacksAndMessages(null) instead. Done in Patch set 2

Target:
public void dispose() { //Unregister for all events phone.mCM.unregisterForSIMLockedOrAbsent(this); phone.mCM.unregisterForOffOrNotAvailable(this); phone.mCM.unregisterForSIMReady(this); }
Source:
START public void dispose() { END //Remove all messages from the queue mHandler.removeCallbacksAndMessages(null); mHandler = null; super.dispose(); } Consider promoting, this code is the same in here and RuimPhoneBookInterfaceManager.

Target:
public void dispose() { super.dispose(); }
Source:
public synchronized void removeMiniThumbDataFile() { String path = randomAccessFilePath(MINI_THUMB_DATA_FILE_VERSION); File file = new File(path); START if (file.exists()) { END try { file.delete(); } catch (SecurityException ex) { // ignore } } } file.exists() can throw SecurityException, too. Why the check in the first place? Won't file.delete() fail gracefully anyway?

Target:
public synchronized void removeMiniThumbDataFile() { String path = randomAccessFilePath(MINI_THUMB_DATA_FILE_VERSION); File file = new File(path); try { file.delete(); } catch (SecurityException ex) { // ignore } }
Source:
public void executeInBackground(final Runnable task) { executor.execute(new Runnable() { public void run() { START System.out.println("STARTING TASK"); END task.run(); System.out.println("ENDING TASK"); } }); } remove debug printf when submitting patches.

Target:
public void executeInBackground(final Runnable task) { executor.execute(new Runnable() { public void run() { task.run(); } }); }
Source:
private void onDiscoverServicesResult(String deviceObjectPath, boolean result) { START String address = mBluetoothService.getAddressFromObjectPath(deviceObjectPath); END // We don't parse the xml here, instead just query Bluez for the properties. if (result) { mBluetoothService.updateRemoteDevicePropertiesCache(address); } if (address != null) { mBluetoothService.sendUuidIntent(address); } mBluetoothService.makeServiceChannelCallbacks(address); } if address == null return. is better.

Target:
private void onDiscoverServicesResult(String deviceObjectPath, boolean result) { String address = mBluetoothService.getAddressFromObjectPath(deviceObjectPath); if (address == null) return; // We don't parse the xml here, instead just query Bluez for the properties. if (result) { mBluetoothService.updateRemoteDevicePropertiesCache(address); } mBluetoothService.sendUuidIntent(address); mBluetoothService.makeServiceChannelCallbacks(address); }
Source:
public void testVFE3() { try { T_iget_13 t = new T_iget_13(); START t.run(); END fail("expected a NoSuchFieldError exception"); } catch (NoSuchFieldError e) { // expected } } Not a big deal, but the style in the other tests so far has been e.g. 'new T_iget_13().run();' It might be a good idea to keep all these as similar as possible. But of course that's minor.

Target:
public void testVFE3() { try { new T_iget_13().run(); fail("expected a NoSuchFieldError exception"); } catch (NoSuchFieldError e) { // expected } }
Source:
START public synchronized int delete(Uri uri, String selection, String[] selectionArgs) { END SqlArguments args = new SqlArguments(uri, selection, selectionArgs); synchronized (mLock) { SQLiteDatabase db = mOpenHelper.getWritableDatabase(); int count = db.delete(args.table, args.where, args.args); if (count > 0) sendNotify(uri); return count; } } Why are you synchronizing on "this" here if you are synchronizing on the lock below?

Target:
public int delete(Uri uri, String selection, String[] selectionArgs) { SqlArguments args = new SqlArguments(uri, selection, selectionArgs); synchronized (mLock) { SQLiteDatabase db = mOpenHelper.getWritableDatabase(); int count = db.delete(args.table, args.where, args.args); if (count > 0) sendNotify(uri); return count; } }
Source:
START public synchronized int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { END SqlArguments args = new SqlArguments(uri, selection, selectionArgs); synchronized (mLock) { SQLiteDatabase db = mOpenHelper.getWritableDatabase(); int count = db.update(args.table, values, args.where, args.args); if (count > 0) sendNotify(uri); return count; } } Why are you synchronizing on "this" here if you are synchronizing on the lock below?

Target:
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { SqlArguments args = new SqlArguments(uri, selection, selectionArgs); synchronized (mLock) { SQLiteDatabase db = mOpenHelper.getWritableDatabase(); int count = db.update(args.table, values, args.where, args.args); if (count > 0) sendNotify(uri); return count; } }
Source:
public void onReceive(Context context, Intent intent) { mContext = context; if (MESSAGE_STATUS_RECEIVED_ACTION.equals(intent.getAction())) { Uri messageUri = intent.getData(); byte[] pdu = (byte[]) intent.getExtra("pdu"); SmsMessage message = updateMessageStatus(context, messageUri, pdu); // Called on the UI thread so don't block. if (message.getStatus() < Sms.STATUS_PENDING) MessagingNotification.nonBlockingUpdateNewMessageIndicator(context, START true, message.isStatusReportMessage); END } } message.isStatusReportMessage -> message.isStatusReportMessage(). Right?

Target:
public void onReceive(Context context, Intent intent) { mContext = context; if (MESSAGE_STATUS_RECEIVED_ACTION.equals(intent.getAction())) { Uri messageUri = intent.getData(); byte[] pdu = (byte[]) intent.getExtra("pdu"); SmsMessage message = updateMessageStatus(context, messageUri, pdu); // Called on the UI thread so don't block. if (message.getStatus() < Sms.STATUS_PENDING) MessagingNotification.nonBlockingUpdateNewMessageIndicator(context, true, message.isStatusReportMessage()); } }
Source:
private boolean isGfxProfilingEnabled() { IDevice device = getCurrentDevice(); if (device == null) { return false; } String prop; try { prop = device.getPropertySync(PROP_GFX_PROFILING); START return "true".equalsIgnoreCase(prop); END } catch (Exception e) { return false; } } or just return Boolean.valueOf(prop)

Target:
private boolean isGfxProfilingEnabled() { IDevice device = getCurrentDevice(); if (device == null) { return false; } String prop; try { prop = device.getPropertySync(PROP_GFX_PROFILING); return Boolean.valueOf(prop); } catch (Exception e) { return false; } }
Source:
onRadioAvailable() { // In case screen state was lost (due to process crash), // this ensures that the RIL knows the correct screen state. PowerManager pm = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE); boolean isScreenOn = pm.isScreenOn(); START sendScreenState(isScreenOn); END } Lets not create a the local variable and just: sendScreenState(pm.isScreenOn());

Target:
onRadioAvailable() { // In case screen state was lost (due to process crash), // this ensures that the RIL knows the correct screen state. PowerManager pm = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE); sendScreenState(pm.isScreenOn()); }
Source:
public static void execShell(String command) { String[] args = { "/system/bin/sh", "-c", command }; try { START Libcore.os.execv("/system/bin/sh", args); END } catch (ErrnoException e) { throw new RuntimeException(e); } } (args[0], args)?

Target:
public static void execShell(String command) { String[] args = { "/system/bin/sh", "-c", command }; try { Libcore.os.execv(args[0], args); } catch (ErrnoException e) { throw new RuntimeException(e); } }
Source:
public boolean onEvaluateInputViewShown() { Configuration config = getResources().getConfiguration(); START return isInputViewShown() || config.keyboard == Configuration.KEYBOARD_NOKEYS END || config.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES; } This seems to be risky. The availability of the hard keyboard may be changed when the display rotates (e.g. Droid), and in that case, the software keyboard should be hidden. The fix should be implemented just in InputMethodManagerSerivce.java.

Target:
public boolean onEvaluateInputViewShown() { Configuration config = getResources().getConfiguration(); return config.keyboard == Configuration.KEYBOARD_NOKEYS || config.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES; }
Source:
private static void invokeForEachKeyFactory(KeyFactoryRunnable runnable) throws Exception { for (Provider provider : getKeyFactoryProviders()) { try { runnable.run(getKeyFactory(provider)); START } catch (Exception e) { END throw new Exception("provider: " + provider.getName(), e); } } } Throwable

Target:
private static void invokeForEachKeyFactory(KeyFactoryRunnable runnable) throws Exception { for (Provider provider : getKeyFactoryProviders()) { try { runnable.run(getKeyFactory(provider)); } catch (Throwable e) { throw new Exception("provider: " + provider.getName(), e); } } }
Source:
private static void invokeForEachKeyFactoryPair(KeyFactoryPairRunnable runnable) throws Exception { for (Provider provider1 : getKeyFactoryProviders()) { for (Provider provider2 : getKeyFactoryProviders()) { try { runnable.run(getKeyFactory(provider1), getKeyFactory(provider2)); START } catch (Exception e) { END throw new Exception("provider1: " + provider1.getName() + ", provider2: " + provider2.getName(), e); } } } } the others don't catch Throwable either if we want to fix one, we should probably fix them all

Target:
private static void invokeForEachKeyFactoryPair(KeyFactoryPairRunnable runnable) throws Exception { for (Provider provider1 : getKeyFactoryProviders()) { for (Provider provider2 : getKeyFactoryProviders()) { try { runnable.run(getKeyFactory(provider1), getKeyFactory(provider2)); } catch (Throwable e) { throw new Exception("provider1: " + provider1.getName() + ", provider2: " + provider2.getName(), e); } } } }
Source:
public GridDialog(Shell parentShell, int numColumns, boolean makeColumnsEqualWidth) { super(parentShell); mNumColumns = numColumns; mMakeColumnsEqualWidth = makeColumnsEqualWidth; START setShellStyle(getShellStyle() | SWT.RESIZE); END } Don't you want to do that in AvdCreationDialog instead? I don't think the base class should arbitrarily decide how all derived dialog will behave. Also this hides the root of the problem, which is that the error message should be in a SWT.WRAP Label, which it is not and that making it wrap properly needs a hack like the one from http://stackoverflow.com/questions/3499349/layout-issue-autogrow-label-swt

Target:
public GridDialog(Shell parentShell, int numColumns, boolean makeColumnsEqualWidth) { super(parentShell); mNumColumns = numColumns; mMakeColumnsEqualWidth = makeColumnsEqualWidth; }
Source:
START private String surfaceRotationToString(int surfaceRotation) { END switch (surfaceRotation) { case Surface.ROTATION_0: return "0"; case Surface.ROTATION_90: return "90"; case Surface.ROTATION_180: return "180"; case Surface.ROTATION_270: return "270"; } throw new IllegalArgumentException("Unsupported surface rotation value" + surfaceRotation); } This method should be static and static methods typically go at the bottom of the class.

Target:
private static String surfaceRotationToString(int surfaceRotation) { switch (surfaceRotation) { case Surface.ROTATION_0: return "0"; case Surface.ROTATION_90: return "90"; case Surface.ROTATION_180: return "180"; case Surface.ROTATION_270: return "270"; } throw new IllegalArgumentException("Unsupported surface rotation value" + surfaceRotation); }
Source:
START private int stringToSurfaceRotation(String s) { END if (s.equals("0")) { return Surface.ROTATION_0; } if (s.equals("90")) { return Surface.ROTATION_90; } if (s.equals("180")) { return Surface.ROTATION_180; } if (s.equals("270")) { return Surface.ROTATION_270; } throw new IllegalArgumentException("Unsupported surface rotation string '" + s + "'"); } This method should be static as well. Also, comparisons of the form "0".equals(s) are preferred over s.equals("0") since if s is null the former won't throw a NPE while the latter will. I'm aware that the rest of this file doesn't follow this convention, but there's no reason not to fix it for new patches... :)

Target:
private static int stringToSurfaceRotation(String s) { if ("0".equals(s)) { return Surface.ROTATION_0; } if ("90".equals(s)) { return Surface.ROTATION_90; } if ("180".equals(s)) { return Surface.ROTATION_180; } if ("270".equals(s)) { return Surface.ROTATION_270; } throw new IllegalArgumentException("Unsupported surface rotation string '" + s + "'"); }
Source:
public void testHostWithNul() throws Exception { URL url = new URL("http://host\u0000/"); try { url.openStream(); fail(); START } catch (Exception expected) END } can we be more specific about the expected exception?

Target:
public void testHostWithNul() throws Exception { URL url = new URL("http://host\u0000/"); try { url.openStream(); fail(); } catch (IllegalArgumentException expected) }
Source:
protected void hyperlinkActivated(@NotNull Notification notification, @NotNull HyperlinkEvent e) { START if (myHyperlinks.length == 1) { END myHyperlinks[0].executeIfClicked(myProject, e); return; } for (NotificationHyperlink hyperlink : myHyperlinks) { if (hyperlink.executeIfClicked(myProject, e)) { return; } } } I don't think you should do loop unrolling here

Target:
protected void hyperlinkActivated(@NotNull Notification notification, @NotNull HyperlinkEvent e) { for (NotificationHyperlink hyperlink : myHyperlinks) { if (hyperlink.executeIfClicked(myProject, e)) { return; } } }
Source:
public String getText() { START return StringUtil.escapeXml(myText); END } I think it's better to do the escaping at the point where the message is going to be converted to HTML. If not maybe rename this message to getTextAsHtml.

Target:
public String getText() { return myText; }
Source:
START List<E> getValues(@NotNull GrStatementOwner closure) { END List<E> result = Lists.newArrayList(); for (PsiElement element : closure.getChildren()) { List<E> values = getValues(element); if (values != null && !values.isEmpty()) { result.addAll(values); } } return result; } Maybe add protected as modified on this and the other two package protected methods to match what is done for setValue?

Target:
public List<E> getValues(@NotNull GrStatementOwner closure) { List<E> result = Lists.newArrayList(); for (PsiElement element : closure.getChildren()) { List<E> values = getValues(element); if (values != null && !values.isEmpty()) { result.addAll(values); } } return result; }
Source:
public static void runFinalization() { boolean shouldRunGC; synchronized(lock) { shouldRunGC = runGC; runGC = false; } if (shouldRunGC) { Runtime.getRuntime().gc(); } Runtime.getRuntime().runFinalization(); START justRanFinalization = END true; } Should this assignment guarded by the lock as well?

Target:
public static void runFinalization() { boolean shouldRunGC; synchronized(lock) { shouldRunGC = runGC; runGC = false; } if (shouldRunGC) { Runtime.getRuntime().gc(); } Runtime.getRuntime().runFinalization(); synchronized(lock) { justRanFinalization = true; } }
Source:
public int onStartCommand(Intent intent, int flags, int startId) { // Temporarily removed for this duplicate message track down. START resultCode = intent != null ? intent.getIntExtra("result", 0) : 0; END if (resultCode != 0) { Log.v(TAG, "onStart: #" + startId + " resultCode: " + resultCode + " = " + translateResultCode(resultCode)); } Message msg = mServiceHandler.obtainMessage(); msg.arg1 = startId; msg.obj = intent; mServiceHandler.sendMessage(msg); return Service.START_NOT_STICKY; } Please define resultcode before using it. int resultCode = intent != null ? intent.getIntExtra("result", 0) : 0;

Target:
public int onStartCommand(Intent intent, int flags, int startId) { // Temporarily removed for this duplicate message track down. int resultCode = intent != null ? intent.getIntExtra("result", 0) : 0; if (resultCode != 0) { Log.v(TAG, "onStart: #" + startId + " resultCode: " + resultCode + " = " + translateResultCode(resultCode)); } Message msg = mServiceHandler.obtainMessage(); msg.arg1 = startId; msg.obj = intent; mServiceHandler.sendMessage(msg); return Service.START_NOT_STICKY; }