auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
START public void setUp() { END mHandlerThread.start(); mMessenger = new Messenger(new Handler(mHandlerThread.getLooper()) { @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_TEST_STARTED: onTestStarted(); break; case MSG_TEST_ENDED_CLEAN: onTestEnded(false); break; default: super.handleMessage(msg); } } }); } setUp() should call super.setUp();

Target:
public void setUp() throws Exception { super.setUp(); mHandlerThread.start(); mMessenger = new Messenger(new Handler(mHandlerThread.getLooper()) { @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_TEST_STARTED: onTestStarted(); break; case MSG_TEST_ENDED_CLEAN: onTestEnded(false); break; default: super.handleMessage(msg); } } }); }
Source:
public void tearDown() { START mHandlerThread.quitSafely(); END } tearDown() should call super.tearDown(); try { mHandlerThread.quitSafely(); } finally { super.tearDown(); }

Target:
public void tearDown() throws Exception { try { mHandlerThread.quitSafely(); } finally { super.tearDown(); } }
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || START !getClass().isAssignableFrom(o.getClass())) return END false; NamedObject that = (NamedObject)o; if (!myName.equals(that.myName)) return false; if (!myValues.equals(that.myValues)) return false; return true; } Doesn't this make equals assymetrical, if this is a subclass of o then this.equals(o) may be true while o.equals(this) would be false.

Target:
public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof NamedObject)) return false; NamedObject that = (NamedObject)o; if (!myName.equals(that.myName)) return false; if (!myValues.equals(that.myValues)) return false; return true; }
Source:
public boolean filter(String filter, boolean fullTrace, Locale locale) { return allocatedClassMatches(filter, locale) || getMatchingStackFrames(filter, fullTrace, START locale).size() > 0; END } !isEmpty

Target:
public boolean filter(String filter, boolean fullTrace, Locale locale) { return allocatedClassMatches(filter, locale) || !getMatchingStackFrames(filter, fullTrace, locale).isEmpty(); }
Source:
START private static File[] splitDexPath(String path) { END List<File> result = splitPaths(path, null, false); return result.toArray(new File[result.size()]); } what is the rationale for changing this return type to File[] ? I think it's probably easier to make this.dexFiles a List<File> and have getDexFiles() return a List<File> too

Target:
private static List<File> splitDexPath(String path) { return splitPaths(path, null, false); }
Source:
protected IdeFrameFixture openProject(@NotNull String projectDirName) throws IOException { START final File projectPath = setUpProject(projectDirName); END WelcomeFrameFixture welcomeFrame = findWelcomeFrame(); welcomeFrame.openProjectButton().click(); FileChooserDialogFixture openProjectDialog = FileChooserDialogFixture.findOpenProjectDialog(myRobot); return openProjectAndWaitUntilOpened(projectPath, openProjectDialog); } Just checking: this doesn't actually create .idea files for a Gradle-only project that's missing .idea files right? If not, we should probably keep at least one IntelliJ project in the VCS such that we can make sure our project open action also works.

Target:
protected IdeFrameFixture openProject(@NotNull String projectDirName) throws IOException { final File projectPath = setUpProject(projectDirName, true); WelcomeFrameFixture welcomeFrame = findWelcomeFrame(); welcomeFrame.openProjectButton().click(); FileChooserDialogFixture openProjectDialog = FileChooserDialogFixture.findOpenProjectDialog(myRobot); return openProjectAndWaitUntilOpened(projectPath, openProjectDialog); }
Source:
public List<VirtualFile> getBestFileMatches() { if (myResources != null && myFile != null) { FolderConfiguration config = myConfiguration.getFullConfig(); VersionQualifier versionQualifier = config.getVersionQualifier(); START config.setVersionQualifier(null); END List<VirtualFile> matchingFiles = myResources.getMatchingFiles(myFile, getResourceType(), config); config.setVersionQualifier(versionQualifier); return matchingFiles; } return Collections.emptyList(); } do try { } finally { } around this and maybe rename versionQualifier here to prevQualifier to make it clear that we are restoring it to its previous value after temporarily clearing it

Target:
public List<VirtualFile> getBestFileMatches() { if (myResources != null && myFile != null) { FolderConfiguration config = myConfiguration.getFullConfig(); VersionQualifier versionQualifier = config.getVersionQualifier(); try { config.setVersionQualifier(null); return myResources.getMatchingFiles(myFile, getResourceType(), config); } finally { config.setVersionQualifier(versionQualifier); } } return Collections.emptyList(); }
Source:
Location getLocation() { START return new TypeInInputLibraryLocation(inputJackLibrary.getLocation(), END Jack.getUserFriendlyFormatter().getName(enclosingPackage, simpleName)); } Cache in field?

Target:
Location getLocation() { return location; }
Source:
START public boolean equals(Object obj) { END return obj instanceof TypeInInputLibraryLocation && ((TypeInInputLibraryLocation) obj).inputLibLoc.equals(inputLibLoc) && ((TypeInInputLibraryLocation) obj).typeName.equals(typeName); } final

Target:
public final boolean equals(Object obj) { return obj instanceof TypeInInputLibraryLocation && ((TypeInInputLibraryLocation) obj).inputLibLoc.equals(inputLibLoc) && ((TypeInInputLibraryLocation) obj).typeName.equals(typeName); }
Source:
public ClassDefItem call() { long now = System.nanoTime(); START ClassDefItem clazz = translateClass(name, bytes, classFile); END translateTime += System.nanoTime() - now; methodDefs += classFile.getMethods().size(); fieldDefs += classFile.getFields().size(); return clazz; } Trivial nit: Should be 1 space after equals.

Target:
public ClassDefItem call() { ClassDefItem clazz = translateClass(name, bytes, classFile); return clazz; }
Source:
public void testAnnotation() throws Exception { START Class END clazz = Class.forName("com.google.annotationresolution.test." + "Annotated"); clazz.getAnnotations(); clazz = Class.forName("com.google.annotationresolution.test." + "Annotated2"); clazz.getAnnotations(); clazz = Class.forName("com.google.annotationresolution.test." + "Annotated3"); clazz.getAnnotations(); } nit: tabs?

Target:
public void testAnnotation() throws Exception { Class<?> clazz = Class.forName("com.google.annotationresolution.test." + "Annotated"); clazz.getAnnotations(); clazz = Class.forName("com.google.annotationresolution.test." + "Annotated2"); clazz.getAnnotations(); clazz = Class.forName("com.google.annotationresolution.test." + "Annotated3"); clazz.getAnnotations(); }
Source:
public boolean hasValidJdkLocation() { File javaDir = getJavaDir(); START return javaDir != null && JdkLocationStep.validateJdkLocation(javaDir.getAbsolutePath()) == null; END } ...and another one :-)

Target:
public boolean hasValidJdkLocation() { File javaDir = getJavaDir(); return javaDir != null && JdkLocationStep.validateJdkLocation(javaDir) == null; }
Source:
private String getListingOfDex(@Nonnull File dex) throws IOException { assert dex.isFile(); StringBuilder sb = new StringBuilder(); for (ClassDef def : new DexBuffer(dex).classDefs()) { String START typeName = END def.getTypeName(); sb.append(typeName); sb.append(":"); sb.append(TextUtils.LINE_SEPARATOR); } return sb.toString(); } nit: useful LV?

Target:
private String getListingOfDex(@Nonnull File dex) throws IOException { assert dex.isFile(); StringBuilder sb = new StringBuilder(); for (ClassDef def : new DexBuffer(dex).classDefs()) { sb.append(def.getTypeName()); sb.append(":"); sb.append(TextUtils.LINE_SEPARATOR); } return sb.toString(); }
Source:
public void setSelectedTestArtifactName(@NotNull String selectedTestArtifactName) { START ImmutableSet<String> knownArtifacts = END ImmutableSet.of(AndroidProject.ARTIFACT_ANDROID_TEST, AndroidProject.ARTIFACT_UNIT_TEST); checkArgument(knownArtifacts.contains(selectedTestArtifactName), "Unknown test artifact %s.", selectedTestArtifactName); mySelectedTestArtifactName = selectedTestArtifactName; } A set with 2 elements is an overkill. Just check if the artifact name is either of those 2 constants.

Target:
public void setSelectedTestArtifactName(@NotNull String selectedTestArtifactName) { checkArgument(selectedTestArtifactName == AndroidProject.ARTIFACT_ANDROID_TEST || selectedTestArtifactName == AndroidProject.ARTIFACT_UNIT_TEST); mySelectedTestArtifactName = selectedTestArtifactName; }
Source:
START private StringBuffer getPathFromDirInternal(@Nonnull CachedParentVDir baseDir, END @Nonnull CachedParentVDir currentDir) { if (baseDir == currentDir) { return new StringBuffer(); } CachedParentVDir currentParent = currentDir.getParent(); assert currentParent != null; return getPathFromDirInternal(baseDir, currentParent).append(currentDir.getName()).append('/'); } Seems similar to DirectFS, no way to share code ?

Target:
private static StringBuffer getPathFromDirInternal(@Nonnull CachedParentVDir baseDir, @Nonnull CachedParentVDir currentDir) { if (baseDir == currentDir) { return new StringBuffer(); } CachedParentVDir currentParent = currentDir.getParent(); assert currentParent != null; return getPathFromDirInternal(baseDir, currentParent).append(currentDir.getName()).append('/'); }
Source:
private void updateGradleSyncState() { if (!myUsingCachedProjectData) { GradleProjectSyncData.save(myProject); GradleSyncState.getInstance(myProject).syncEnded(); } else { long lastSyncTimestamp = myLastSyncTimestamp; START if (lastSyncTimestamp < 0) { END lastSyncTimestamp = System.currentTimeMillis(); } GradleSyncState.getInstance(myProject).syncSkipped(lastSyncTimestamp); } // set default value back. myUsingCachedProjectData = DEFAULT_USING_CACHED_PROJECT_DATA; myLastSyncTimestamp = DEFAULT_LAST_SYNC_TIMESTAMP; } This is the case at startup, right? Maybe just == -1L instead?

Target:
private void updateGradleSyncState() { if (!myUsingCachedProjectData) { GradleProjectSyncData.save(myProject); GradleSyncState.getInstance(myProject).syncEnded(); } else { long lastSyncTimestamp = myLastSyncTimestamp; if (lastSyncTimestamp == DEFAULT_LAST_SYNC_TIMESTAMP) { lastSyncTimestamp = System.currentTimeMillis(); } GradleSyncState.getInstance(myProject).syncSkipped(lastSyncTimestamp); } // set default value back. myUsingCachedProjectData = DEFAULT_USING_CACHED_PROJECT_DATA; myLastSyncTimestamp = DEFAULT_LAST_SYNC_TIMESTAMP; }
Source:
private void compareWithAns(String doc, String ansPath) throws FileNotFoundException { Scanner in = new Scanner(new File(ansPath)); String ansDoc = ""; while (in.hasNext()) { ansDoc += in.nextLine() + "\n"; } doc = StringUtil.replace(doc, "\n", ""); START ansDoc = StringUtil.replace(ansDoc, "\n", ""); END assertEquals(doc, ansDoc); } Are you removing the \n after you added them above? Can not you just not add it?

Target:
private void compareWithAns(String doc, String ansPath) throws FileNotFoundException { assertNotNull(doc); Scanner in = new Scanner(new File(ansPath)); String ansDoc = ""; while (in.hasNext()) { ansDoc += in.nextLine(); } doc = StringUtil.replace(doc, "\n", ""); assertEquals(doc, ansDoc); }
Source:
public void START setVariants( END Set<BaseVariantData> variants) { mVariants = variants; } fits on a single line

Target:
public void setVariants(Set<BaseVariantData> variants) { this.variants = variants; }
Source:
public Set<String> getApplicableFilters() { // use a LinkedHashSet so iteration order follows insertion order. LinkedHashSet<String> filters = new LinkedHashSet<String>(); // if splitting enabled, then add an entry with no filter for universal // add it FIRST, since code assume that the first variant output will be the universal one. if (isEnable()) { filters.add(NO_FILTER); START filters.addAll(super.getApplicableFilters()); END } return filters; } this is incorrect (and should fail with my new test. This would mean that if disabled the output is null, which is not what is expected (we expect the list to contain a null value). Though I realize that this is not consistent with the Abi/Language version...

Target:
public Set<String> getApplicableFilters() { // use a LinkedHashSet so iteration order follows insertion order. LinkedHashSet<String> filters = new LinkedHashSet<String>(); // if splitting enabled, then add an entry with no filter for universal // add it FIRST, since code assume that the first variant output will be the universal one. if (isEnable()) { filters.add(NO_FILTER); } filters.addAll(super.getApplicableFilters()); return filters; }
Source:
public void setBounds(int x, int y, int width, int height) { Dimension previousSize = getSize(); super.setBounds(x, y, width, height); // Update the size of the layout renderer. This is done here instead of a component listener because // this runs before the paintComponent saving an extra paint cycle. Dimension currentSize = getSize(); synchronized (myGraphicsLayoutRendererLock) { if (myGraphicsLayoutRenderer != null && !currentSize.equals(previousSize)) { // Because we use GraphicsLayoutRender in vertical scroll mode, the height passed it's only a minimum. If the actual rendering results // in a bigger size, the GraphicsLayoutRenderer.getPreferredSize() call will return the correct size. START myGraphicsLayoutRenderer.setSize(width, END (myCurrentWidth < width) ? 1 : height); myCurrentWidth = width; } } } cant we just always pass 1, or -1, so it calculates the right size?

Target:
public void setBounds(int x, int y, int width, int height) { Dimension previousSize = getSize(); super.setBounds(x, y, width, height); // Update the size of the layout renderer. This is done here instead of a component listener because // this runs before the paintComponent saving an extra paint cycle. Dimension currentSize = getSize(); synchronized (myGraphicsLayoutRendererLock) { if (myGraphicsLayoutRenderer != null && !currentSize.equals(previousSize)) { // Because we use GraphicsLayoutRender in vertical scroll mode, the height passed it's only a minimum. If the actual rendering results // in a bigger size, the GraphicsLayoutRenderer.getPreferredSize() call will return the correct size. myGraphicsLayoutRenderer.setSize(width, 1); } } }
Source:
START ArrayList<FieldValue> END getFields(String name) { ArrayList<FieldValue> result = new ArrayList<FieldValue>(); for (FieldValue value : getValues()) { if (value.getField().getName().equals(name)) { result.add(value); } } return result; } List

Target:
List<FieldValue> getFields(String name) { ArrayList<FieldValue> result = new ArrayList<FieldValue>(); for (FieldValue value : getValues()) { if (value.getField().getName().equals(name)) { result.add(value); } } return result; }
Source:
public JComponent getPreferredFocusedComponent() { String name = myNameField.getText(); START if (name.length() == 0 || name.equals(ResourceHelper.prependResourcePrefix(myModule, null))) { END return myNameField; } else if (myValueField.isVisible()) { return myValueField; } else if (myModuleCombo.isVisible()) { return myModuleCombo; } else { return myFileNameCombo; } } name.isEmpty

Target:
public JComponent getPreferredFocusedComponent() { String name = myNameField.getText(); if (name.isEmpty() || name.equals(ResourceHelper.prependResourcePrefix(myModule, null))) { return myNameField; } else if (myValueField.isVisible()) { return myValueField; } else if (myModuleCombo.isVisible()) { return myModuleCombo; } else { return myFileNameCombo; } }
Source:
public void enableDefault() { if (getDefaultApi() == null) { return; } List<? extends CloudTestingType> appSupportedDomain = getAppSupportedDomain(); if (appSupportedDomain.contains(defaultApi)) { enable(defaultApi); } else if START (appSupportedDomain.size() > 0) { END enable(appSupportedDomain.get(0)); } } !isEmpty and throughout the CL

Target:
public void enableDefault() { if (getDefaultApi() == null) { return; } List<? extends CloudTestingType> appSupportedDomain = getAppSupportedDomain(); if (appSupportedDomain.contains(defaultApi)) { enable(defaultApi); } else if (!appSupportedDomain.isEmpty()) { enable(appSupportedDomain.get(0)); } }
Source:
private static void show(JComponent... components) { for (JComponent component : components) { component.setVisible(true); START component.getParent().invalidate(); END component.getParent().getParent().invalidate(); } } Just curious, do we still have to invalidate our direct parent if we invalidate our grandparent?

Target:
private static void show(JComponent... components) { for (JComponent component : components) { component.setVisible(true); component.getParent().invalidate(); } }
Source:
public List<String> getApplicableMethodNames() { START List<String> values = new ArrayList<String>(2); END // Detect calls to potentially insecure SSLCertificateSocketFactory methods values.add("createSocket"); //$NON-NLS-1$ values.add("getInsecure"); //$NON-NLS-1$ return values; } Nit - just return Arrays.asList("createSockets", "getInsecure") instead?

Target:
public List<String> getApplicableMethodNames() { // Detect calls to potentially insecure SSLCertificateSocketFactory methods return Arrays.asList("createSocket", "getInsecure"); }
Source:
START public final void engineInit(ManagerFactoryParameters spec) END throws InvalidAlgorithmParameterException { if (!(spec instanceof ApplicationConfigParameters)) { throw new InvalidAlgorithmParameterException("Unsupported spec: " + spec + ". Only " + ApplicationConfigParameters.class.getName() + " supported"); } mApplicationConfig = ((ApplicationConfigParameters) spec).config; } What's the reason for marking all methods final? If you don't want this whole class to be subclassed, just mark the whole class final instead.

Target:
public void engineInit(ManagerFactoryParameters spec) throws InvalidAlgorithmParameterException { if (!(spec instanceof ApplicationConfigParameters)) { throw new InvalidAlgorithmParameterException("Unsupported spec: " + spec + ". Only " + ApplicationConfigParameters.class.getName() + " supported"); } mApplicationConfig = ((ApplicationConfigParameters) spec).config; }
Source:
public JMultiCastOperation(@Nonnull SourceInfo info, @Nonnull JExpression expr, @Nonnull JType... castTypes) { super(info, expr); this.castTypes = Arrays.asList(castTypes); START assert this.castTypes.size() >= 1; END } - nit !isEmpty()

Target:
public JMultiCastOperation(@Nonnull SourceInfo info, @Nonnull JExpression expr, @Nonnull JType... castTypes) { super(info, expr); this.castTypes = Arrays.asList(castTypes); assert !this.castTypes.isEmpty(); }
Source:
START public Collection<JType> getTypes() { END return castTypes; } Idem

Target:
public List<JType> getTypes() { return castTypes; }
Source:
public int getTop(final ViewGroup ancestor, View view){ if START (view==ancestor){ END return 0; } else { int top = view.getTop(); if (ViewGroup.class.isAssignableFrom(view.getParent().getClass())){ top += getTop(ancestor, (ViewGroup) view.getParent()); } else { Log.i("DataInteraction","giving up calculating the top"); } return top; } } spaces

Target:
public int getTop(final ViewGroup ancestor, View view){ if (view == ancestor){ return 0; } else { int top = view.getTop(); if (ViewGroup.class.isAssignableFrom(view.getParent().getClass())){ top += getTop(ancestor, (ViewGroup) view.getParent()); } else { Log.i(TAG, "giving up calculating the top"); } return top; } }
Source:
public void test_SerializationBug_26387905() throws Exception { Locale l = Locale.US; ObjectInputStream oinput = null; START try { oinput = new ObjectInputStream(getClass().getResource("/serialization/org/apache/harmony/tests/java/util/Locale_Bug_26387905.ser") .openStream()); l = (Locale) oinput.readObject(); } finally { try { if (null != oinput) { oinput.close(); } } catch (Exception e) { // ignore } } END } please use try with resources. try (ObjectInputStream oinput = ...) { }

Target:
public void test_SerializationBug_26387905() throws Exception { try (ObjectInputStream oinput = new ObjectInputStream(getClass() .getResource("/serialization/org/apache/harmony/tests/java/util/Locale_Bug_26387905.ser") .openStream())) { Locale l = (Locale) oinput.readObject(); } }
Source:
protected void onFinishInflate() { mLockPatternUtils = new LockPatternUtils(mContext); mSecurityMessageDisplay = START (KeyguardMessageArea) KeyguardMessageArea.findSecurityMessageDisplay(this); END mEcaView = findViewById(R.id.keyguard_selector_fade_container); EmergencyButton button = (EmergencyButton) findViewById(R.id.emergency_call_button); if (button != null) { button.setCallback(this); } } Instead of breaking the abstraction here, introduce isEmpty on SecurityMessageDisplay.

Target:
protected void onFinishInflate() { mLockPatternUtils = new LockPatternUtils(mContext); mSecurityMessageDisplay = KeyguardMessageArea.findSecurityMessageDisplay(this); mEcaView = findViewById(R.id.keyguard_selector_fade_container); EmergencyButton button = (EmergencyButton) findViewById(R.id.emergency_call_button); if (button != null) { button.setCallback(this); } }
Source:
START public void snapChildInstantly(final View view) { END final View targetView = mCallback.getChildContentView(view); final boolean canAnimViewBeDismissed = mCallback.canChildBeDismissed(targetView); setTranslation(targetView, 0); updateSwipeProgressFromOffset(targetView, canAnimViewBeDismissed); } private

Target:
private void snapChildInstantly(final View view) { final View targetView = mCallback.getChildContentView(view); final boolean canAnimViewBeDismissed = mCallback.canChildBeDismissed(targetView); setTranslation(targetView, 0); updateSwipeProgressFromOffset(targetView, canAnimViewBeDismissed); }
Source:
public void testRemoveIfUnsupportedOperation() { Collection<Integer> c = Arrays.asList(1, 2, 3, 4); try { c.removeIf(truth); fail(); } catch (UnsupportedOperationException expected) { } START try { c.removeIf(falsity); } catch (Exception e) { fail(); } END } unnecessary try { catch } . have your test "throw Exception" and just write this as c.removeIf. The advantage of doing that is the test runner will give you a full stack of what happened.

Target:
public void testRemoveIfUnsupportedOperation() { Collection<Integer> c = Arrays.asList(1, 2, 3, 4); try { c.removeIf(truth); fail(); } catch (UnsupportedOperationException expected) { } c.removeIf(falsity); // Should not throw UnsupportedOperationException. }
Source:
public void testLongFloorDivMod() { testFloorDivModL(123L, 456L); testFloorDivModL(456L, 123L); testFloorDivModL(369L, 123L); testFloorDivModL(1L, 0L); testFloorDivModL(Long.MAX_VALUE, 1L); testFloorDivModL(Long.MAX_VALUE, -1L); testFloorDivModL(Long.MIN_VALUE, START -1L); END testFloorDivModL(Long.MIN_VALUE, -1L); } 1L

Target:
public void testLongFloorDivMod() { testFloorDivModL(123L, 456L); testFloorDivModL(456L, 123L); testFloorDivModL(369L, 123L); testFloorDivModL(1L, 0L); testFloorDivModL(Long.MAX_VALUE, 1L); testFloorDivModL(Long.MAX_VALUE, -1L); testFloorDivModL(Long.MIN_VALUE, 1L); testFloorDivModL(Long.MIN_VALUE, -1L); }
Source:
protected void fillRtTestInfos() { START rtTestInfos.add(TEST001); END } Remove.

Target:
protected void fillRtTestInfos()
Source:
private void writeToFile(String fileName, byte[] bytes) { try (FileOutputStream fos = START getApplicationContext().openFileOutput(fileName, END Context.MODE_PRIVATE)) { fos.write(bytes); } catch (IOException e) { throw new RuntimeException("Couldn't write to " + fileName, e); } } remove this... openFileInput(fileName) should be sufficient and using an Application context is often an anti-pattern

Target:
private void writeToFile(String fileName, byte[] bytes) { try (FileOutputStream fos = openFileOutput(fileName, Context.MODE_PRIVATE)) { fos.write(bytes); } catch (IOException e) { throw new RuntimeException("Couldn't write to " + fileName, e); } }
Source:
public void dispose() { mDestroyed.set(true); // It is possible that there is another thread waiting for the response // to requestIccSimAuthentication() in getIccSimChallengeResponse(). // A pseudo error response is made here to avoid the deadlock. START auth_rsp = new IccIoResult(0x6F, 0, (byte[]) null); END synchronized (mLock) { mLock.notifyAll(); } mParentApp = null; mFh = null; mCi = null; mContext = null; } Change this to null instead and add auth_rsp != null check in getIccSimChallengeResponse(). That function can return null if auth_rsp is null.

Target:
public void dispose() { mDestroyed.set(true); // It is possible that there is another thread waiting for the response // to requestIccSimAuthentication() in getIccSimChallengeResponse(). auth_rsp = null; synchronized (mLock) { mLock.notifyAll(); } mParentApp = null; mFh = null; mCi = null; mContext = null; }
Source:
private void markLoaded(@Nonnull Scope range, @Nonnull JDefinedClassOrInterface loaded) { loadStatus |= range.getMask(); if (loadStatus == Scope.ALL) { // Open a synchronize block just to prevent reordering START synchronized (this) { loaded.removeLoader(); } END } } Are you sure this will prevent reordering, markLoaded is always called when the lock is already taken. I also believe that if it does prevent it, doing nothing on reader side will still be a problem since it is not synchronized in any way.

Target:
private void markLoaded(@Nonnull Scope range, @Nonnull JDefinedClassOrInterface loaded) { loadStatus |= range.getMask(); if (loadStatus == Scope.ALL) { loaded.removeLoader(); } }
Source:
public void testSMSSendingExploit() throws Exception { START int inboxSizeBeforeExploit END = getSMSInboxSize(); TelephonyManager telephonyManager = (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE); if(!telephonyManager.isSmsCapable()) { return; } SmsManager manager = SmsManager.getDefault(); manager.sendTextMessage("25578", null, "STOP", null, null); SystemClock.sleep(250); int inboxSizeAfterExploit = getSMSInboxSize(); assertTrue("Device is vulnerable to bug #22314646!! For more information " + "please refer - https://android.googlesource.com/platform/frameworks/" + "opt/telephony/+/ce058be%5E!/", inboxSizeBeforeExploit == inboxSizeAfterExploit); } Can you move this line after check logic below? Calling getSMSInboxSize() caused an exception if there is no telephony.

Target:
public void testSMSSendingExploit() throws Exception { TelephonyManager telephonyManager = (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE); if(!telephonyManager.isSmsCapable()) { return; } int inboxSizeBeforeExploit = getSMSInboxSize(); SmsManager manager = SmsManager.getDefault(); manager.sendTextMessage("25578", null, "STOP", null, null); SystemClock.sleep(250); int inboxSizeAfterExploit = getSMSInboxSize(); assertTrue("Device is vulnerable to bug #22314646!! For more information " + "please refer - https://android.googlesource.com/platform/frameworks/" + "opt/telephony/+/ce058be%5E!/", inboxSizeBeforeExploit == inboxSizeAfterExploit); }
Source:
START public int hashCode() { END return name.hashCode() ^ parameterTypes.hashCode(); } final, here and elsewhere

Target:
public final int hashCode() { return name.hashCode() ^ parameterTypes.hashCode(); }
Source:
private void setUsbConfig(String config) { if (DEBUG) Slog.d(TAG, "setUsbConfig(" + config + ")"); // set the new configuration // we always set it due to b/23631400, where adbd was getting killed // and not restarted due to property timeouts on some devices SystemProperties.set(USB_CONFIG_PROPERTY, config); START return; END } Please remove the return statement.

Target:
private void setUsbConfig(String config) { if (DEBUG) Slog.d(TAG, "setUsbConfig(" + config + ")"); // set the new configuration // we always set it due to b/23631400, where adbd was getting killed // and not restarted due to property timeouts on some devices SystemProperties.set(USB_CONFIG_PROPERTY, config); }
Source:
public void enter() { super.enter(); if (!mBluetoothRouteManager.isInbandRingingEnabled()) { START setSpeakerphoneOn(false); END } CallAudioState newState = new CallAudioState(mIsMuted, ROUTE_BLUETOOTH, mAvailableRoutes); setSystemAudioState(newState); updateInternalCallAudioState(); } I think it was there as a copy-paste error. It should probably be removed.

Target:
public void enter() { super.enter(); setSpeakerphoneOn(false); // Do not enable SCO audio here, since RING is being sent to the headset. CallAudioState newState = new CallAudioState(mIsMuted, ROUTE_BLUETOOTH, mAvailableRoutes); setSystemAudioState(newState); updateInternalCallAudioState(); }
Source:
START private END String getMethodNameAndParameters(String methodSignature) { Pattern pattern = Pattern.compile("[\\w\\$]+\\([^)]*\\)"); Matcher methodPatternMatcher = pattern.matcher(methodSignature); if (methodPatternMatcher.find()) { return methodPatternMatcher.group(); } else { throw new IllegalArgumentException(); } } static

Target:
private static String getMethodNameAndParameters(String methodSignature) { Matcher methodPatternMatcher = pattern.matcher(methodSignature); if (methodPatternMatcher.find()) { return methodPatternMatcher.group(); } else { throw new IllegalArgumentException(methodSignature); } }
Source:
public void endVisit(UnaryExpression x, BlockScope b) { int operator = ((x.bits & ASTNode.OperatorMASK) >> ASTNode.OperatorSHIFT); // We don't take the constant result from ECJ if it involves a unary + and a non-literal. if (operator == OperatorIds.PLUS && !(x.expression instanceof Literal)) { foundUnaryPos = true; // We have an (+ (expression)) Constant outer = x.constant; Constant inner = x.expression.constant; // Since the + operator is no-op, the inner and the outer constant should be exactly the // same. If not, the current version of ECJ has the mentioned bug. boolean START hasEcjUnaryPosBug = END !outer.equals(inner); // We are going to assume there is a bug in ECJ and work around it. If this fails, // we know that the bug has been fixed. assert hasEcjUnaryPosBug; } } I guess that we can rename foundUnaryPos to hasEcjUnaryPosBug and write something like: hasEcjUnaryPosBug |= !outer.equals(inner); Unless the check is not really accurate?

Target:
public void endVisit(UnaryExpression x, BlockScope b) { int operator = ((x.bits & ASTNode.OperatorMASK) >> ASTNode.OperatorSHIFT); // We don't take the constant result from ECJ if it involves a unary + and a non-literal. if (operator == OperatorIds.PLUS && !(x.expression instanceof Literal)) { hasEcjUnaryPosBug = true; // We have an (+ (expression)) Constant outer = x.constant; Constant inner = x.expression.constant; // Since the + operator is no-op, the inner and the outer constant should be exactly the // same. If not, the current version of ECJ has the mentioned bug. boolean hasEcjUnaryPosBug = !outer.equals(inner); // We are going to assume there is a bug in ECJ and work around it. If this fails, // we know that the bug has been fixed. assert hasEcjUnaryPosBug; } }
Source:
public void setUp() throws Exception { super.setUp(); fakeFtpServer = new FakeFtpServer(); fakeFtpServer.setServerControlPort(0 /* allocate port number automatically */); fakeFtpServer.addUserAccount(new UserAccount(USER, PASSWORD, USER_HOME_DIR)); fileSystem = new UnixFakeFileSystem(); fakeFtpServer.setFileSystem(fileSystem); fileSystem.add(new DirectoryEntry(USER_HOME_DIR)); fakeFtpServer.start(); START fileContents = END "abcdef 1234567890".getBytes(UTF_8); } This can be a static constant called "ARBITRARY_BYTES" or something if you think it's valuable to have it pulled out (I think I'd just inline it, personally).

Target:
public void setUp() throws Exception { super.setUp(); fakeFtpServer = new FakeFtpServer(); fakeFtpServer.setServerControlPort(0 /* allocate port number automatically */); fakeFtpServer.addUserAccount(new UserAccount(USER, PASSWORD, USER_HOME_DIR)); fileSystem = new UnixFakeFileSystem(); fakeFtpServer.setFileSystem(fileSystem); fileSystem.add(new DirectoryEntry(USER_HOME_DIR)); fakeFtpServer.start(); }
Source:
public static void skipContent(@Nonnull JayceInternalReaderImpl in) START throws IOException { END throw new UnsupportedOperationException(); } Remove ?

Target:
public static void skipContent(@Nonnull JayceInternalReaderImpl in) { throw new UnsupportedOperationException(); }
Source:
public static void skipContent(@Nonnull JayceInternalReaderImpl in) START throws IOException { END } Remove ?

Target:
public static void skipContent(@Nonnull JayceInternalReaderImpl in) { }
Source:
public void iccOpenLogicalChannel(String AID, byte p2, Message response) { RILRequest rr = RILRequest.obtain(RIL_REQUEST_SIM_OPEN_CHANNEL, response); START rr.mParcel.writeByte(p2); END rr.mParcel.writeString(AID); if (RILJ_LOGD) riljLog(rr.serialString() + "> " + requestToString(rr.mRequest)); send(rr); } don't we normally pass args in arg order (ie do this after writing AID)?

Target:
public void iccOpenLogicalChannel(String AID, byte p2, Message response) { RILRequest rr = RILRequest.obtain(RIL_REQUEST_SIM_OPEN_CHANNEL, response); rr.mParcel.writeString(AID); rr.mParcel.writeByte(p2); if (RILJ_LOGD) riljLog(rr.serialString() + "> " + requestToString(rr.mRequest)); send(rr); }
Source:
START public final boolean hasSourceInfo() throws InvalidTokenException { END if (!hasSourceInfoBeenRequested) { Class<? extends NNode> nodeClass = getNNodeClass(); hasSourceInfo = HasSourceInfo.class.isAssignableFrom(nodeClass); hasSourceInfoBeenRequested = true; } return hasSourceInfo; } Definitively, JayceFormatException is not the right thing here. But, not related to this CL. I have a question. Is NUMBER_VALUE has a SourceInfo? If no, I think it is a good thing that the method return false, right?

Target:
public final boolean hasSourceInfo() { if (!hasSourceInfoBeenRequested) { try { hasSourceInfo = HasSourceInfo.class.isAssignableFrom(getNNodeClass()); } catch (InvalidTokenException e) { hasSourceInfo = false; } finally { hasSourceInfoBeenRequested = true; } } return hasSourceInfo; }
Source:
int wifiFeatureMaskFromStaCapabilities(int capabilities) { START int features END = WifiManager.WIFI_FEATURE_INFRA; // Always set this if we have a STA interface for (int i = 0; i < sFeatureCapabilityTranslation.length; i++) { if ((capabilities & sFeatureCapabilityTranslation[i][1]) != 0) { features |= sFeatureCapabilityTranslation[i][0]; } } return features; } Remove this and use the STA iface type below to set this.

Target:
int wifiFeatureMaskFromStaCapabilities(int capabilities) { int features = 0; for (int i = 0; i < sFeatureCapabilityTranslation.length; i++) { if ((capabilities & sFeatureCapabilityTranslation[i][1]) != 0) { features |= sFeatureCapabilityTranslation[i][0]; } } return features; }
Source:
public void setLineWidth(float width) { START if (width < 0) { throw new AssertionError(); } END mLineWidth = width; } why does this not use Utils.assertTrue ?

Target:
public void setLineWidth(float width) { Utils.assertTrue(width >= 0); mLineWidth = width; }
Source:
public void test2GhzQualifiedNo5GhzAvailable() { // Do not perform selection on 2GHz if current network is good and no 5GHz available testStayOrSwitch(mThresholdQualifiedRssi2G START + 1, false, END mThresholdQualifiedRssi2G + 10, false, false); } Delete this, take one step closer to the edge.

Target:
public void test2GhzQualifiedNo5GhzAvailable() { // Do not perform selection on 2GHz if current network is good and no 5GHz available testStayOrSwitch(mThresholdQualifiedRssi2G, false, mThresholdQualifiedRssi2G + 10, false, false); }
Source:
public void test2GhzNotQualifiedOther2GhzAvailable() { // Run Selection on 2Ghz networks when not qualified even if no 5GHz available testStayOrSwitch(mThresholdQualifiedRssi2G - 1, false, mThresholdQualifiedRssi2G START + 1, false, END true); } delete

Target:
public void test2GhzNotQualifiedOther2GhzAvailable() { // Run Selection on 2Ghz networks when not qualified even if no 5GHz available testStayOrSwitch(mThresholdQualifiedRssi2G - 1, false, mThresholdQualifiedRssi2G - 10, false, true); }
Source:
public void tearDown() throws Exception { super.tearDown(); START mIccRecords.dispose(); END } Why is this removed?

Target:
public void tearDown() throws Exception { super.tearDown(); }
Source:
public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); START if (!Utils.isMonkeyRunning()) { END updatePreferences(); } } It is not fixing the root cause. Please change the updatePreferences() call to check null on each field before accessing.

Target:
public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); updatePreferences(); }
Source:
private static void processFailLoadAndGc() throws TestFailed { try { BrokenDexLoader loader; loader = new BrokenDexLoader(ClassLoader.getSystemClassLoader()); loader.findBrokenClass(); System.out.println("ERROR: Inaccessible was accessible"); } catch (InvocationTargetException ite) { Throwable cause = ite.getCause(); if (cause instanceof NullPointerException) { System.out.println("Got expected ITE/NPE"); } else { System.out.println("Got unexpected ITE"); START ite.printStackTrace(); END } } } This is still printing to System.err but that's mostly OK as the test is already failing in this code path anyway.

Target:
private static void processFailLoadAndGc() throws TestFailed { try { BrokenDexLoader loader; loader = new BrokenDexLoader(ClassLoader.getSystemClassLoader()); loader.findBrokenClass(); System.out.println("ERROR: Inaccessible was accessible"); } catch (InvocationTargetException ite) { Throwable cause = ite.getCause(); if (cause instanceof NullPointerException) { System.out.println("Got expected ITE/NPE"); } else { System.out.println("Got unexpected ITE"); ite.printStackTrace(System.out); } } }
Source:
private START int priority(int END eventId) { switch (eventId) { case MetricsEvent.NOTIFICATION_NETWORK_SIGN_IN: return 4; case MetricsEvent.NOTIFICATION_NETWORK_NO_INTERNET: return 3; case MetricsEvent.NOTIFICATION_NETWORK_SWITCH: return 2; case MetricsEvent.NOTIFICATION_NETWORK_LOST_INTERNET: return 1; default: return 0; } } static probably works here

Target:
private static int priority(int eventId) { switch (eventId) { case MetricsEvent.NOTIFICATION_NETWORK_SIGN_IN: return 4; case MetricsEvent.NOTIFICATION_NETWORK_NO_INTERNET: return 3; case MetricsEvent.NOTIFICATION_NETWORK_SWITCH: return 2; case MetricsEvent.NOTIFICATION_NETWORK_LOST_INTERNET: return 1; default: return 0; } }
Source:
public final boolean isProfileOwnerAction(String action) { return START (action != null) ? action.equals(ACTION_PROVISION_MANAGED_PROFILE) END || action.equals(ACTION_PROVISION_MANAGED_USER) : false; } Instead of checking for action!= null, i'd suggest to simply change the order of equals, e.g. return ACTION_PROVISION_MANAGED_PROFILE.equals(action) || ACTION_PROVISION_MANAGED_USER.equals(action);

Target:
public final boolean isProfileOwnerAction(String action) { return ACTION_PROVISION_MANAGED_PROFILE.equals(action) || ACTION_PROVISION_MANAGED_USER.equals(action); }
Source:
protected Mutation generateMutation(MutatableCode mutatableCode) { generateCachedNewInstanceInsns(mutatableCode); START int newInstanceIdx = rng.nextInt(newInstanceCachedInsns.size() - 1); END int newInstanceTypeIdx = rng.nextInt(mutatableCode.program.getTotalPoolIndicesByKind(PoolIndexKind.Type)); AssociatedMutation mutation = new AssociatedMutation(); mutation.setup(this.getClass(), mutatableCode); mutation.newInstanceToChangeIdx = newInstanceIdx; mutation.newInstanceTypeIdx = newInstanceTypeIdx; return mutation; } why -1? the nextInt is 0..N with N exclusive

Target:
protected Mutation generateMutation(MutatableCode mutatableCode) { generateCachedNewInstanceInsns(mutatableCode); int newInstanceIdx = rng.nextInt(newInstanceCachedInsns.size()); int newInstanceTypeIdx = rng.nextInt(mutatableCode.program.getTotalPoolIndicesByKind(PoolIndexKind.Type)); AssociatedMutation mutation = new AssociatedMutation(); mutation.setup(this.getClass(), mutatableCode); mutation.newInstanceToChangeIdx = newInstanceIdx; mutation.newInstanceTypeIdx = newInstanceTypeIdx; return mutation; }
Source:
protected boolean canMutate(MutatableCode mutatableCode) { for (MInsn mInsn : mutatableCode.getInstructions()) { START return (mInsn.insn.info.opcode == Opcode.NEW_INSTANCE); END } Log.debug("No New Instance in method, skipping..."); return false; } uh, this is not right? can you spot the error?

Target:
protected boolean canMutate(MutatableCode mutatableCode) { for (MInsn mInsn : mutatableCode.getInstructions()) { if (mInsn.insn.info.opcode == Opcode.NEW_INSTANCE) { return true; } } Log.debug("No New Instance in method, skipping..."); return false; }
Source:
public IpSecTransform.Builder setEncryption( @TransformDirection int direction, IpSecAlgorithm algo) { START if (mConfig.getAuthenticatedEncryption(direction) != null) { throw new IllegalArgumentException( "Encryption is unsupported while " + "Authenticated Encryption algorithm is specified"); } END mConfig.setEncryption(direction, algo); return this; } Looks like these checks duplicate the ones in IpSecConfig. Can we remove either these or those? Since IpSecConfig is not public, we probably don't need the check there.

Target:
public IpSecTransform.Builder setEncryption( @TransformDirection int direction, IpSecAlgorithm algo) { mConfig.setEncryption(direction, algo); return this; }
Source:
public void testCreateInvalidConfigAeadWithAuth() throws Exception { IpSecConfig ipSecConfig = new IpSecConfig(); addDefaultSpisAndRemoteAddrToIpSecConfig(ipSecConfig); for (int direction : DIRECTIONS) { ipSecConfig.setAuthentication(direction, AUTH_ALGO); try { ipSecConfig.setAuthenticatedEncryption(direction, START AEAD_ALGO); END } catch (IllegalArgumentException expected) { /* Expected exception; do nothing */ } } try { mIpSecService.createTransportModeTransform(ipSecConfig, new Binder()); fail( "IpSecService should have thrown an error on authentication being" + " enabled with authenticated encryption"); } catch (IllegalArgumentException expected) { /* Expected exception; do nothing */ } } If an exception is expected, should we fail if the exception is not thrown?

Target:
public void testCreateInvalidConfigAeadWithAuth() throws Exception { IpSecConfig ipSecConfig = new IpSecConfig(); addDefaultSpisAndRemoteAddrToIpSecConfig(ipSecConfig); for (int direction : DIRECTIONS) { ipSecConfig.setAuthentication(direction, AUTH_ALGO); ipSecConfig.setAuthenticatedEncryption(direction, AEAD_ALGO); } try { mIpSecService.createTransportModeTransform(ipSecConfig, new Binder()); fail( "IpSecService should have thrown an error on authentication being" + " enabled with authenticated encryption"); } catch (IllegalArgumentException expected) { } }
Source:
public void test_pipe2_errno() throws Exception { try { // flag=1 is not a valiud value for pip2, will EINVAL Libcore.os.pipe2(1); fail(); } catch(ErrnoException expected) START END } needs a newline before the }, see section 4.1.3 of the style guide. (The one-line style makes it harder to see where blocks begin/end, so it is not allowed).

Target:
public void test_pipe2_errno() throws Exception { try { // flag=-1 is not a valid value for pip2, will EINVAL Libcore.os.pipe2(-1); fail(); } catch(ErrnoException expected) { } }
Source:
private void updateRemoteVideoSurfaceDimensions() { if (mVideoCallScreen == null) START { END LogUtil.e("VideoCallPresenter.updateRemoteVideoSurfaceDimensions", "mVideoCallScreen is null"); return; } Activity activity = mVideoCallScreen.getVideoCallScreenFragment().getActivity(); if (activity != null) { Point screenSize = new Point(); activity.getWindowManager().getDefaultDisplay().getSize(screenSize); getRemoteVideoSurfaceTexture().setSurfaceDimensions(screenSize); } } Remove this check? It will throw NullPointerException if it's null, which should never happen.

Target:
private void updateRemoteVideoSurfaceDimensions() { Activity activity = mVideoCallScreen.getVideoCallScreenFragment().getActivity(); if (activity != null) { Point screenSize = new Point(); activity.getWindowManager().getDefaultDisplay().getSize(screenSize); getRemoteVideoSurfaceTexture().setSurfaceDimensions(screenSize); } }
Source:
public void testOpenUdpEncapsulationSocketCallsSetSocketOwner() throws Exception { START int localport = findUnusedPort(); IpSecUdpEncapResponse udpEncapResp = mIpSecService.openUdpEncapsulationSocket(localport, new Binder()); END verify(mMockNetd).ipSecSetSocketOwner(anyObject(), eq(Os.getuid())); mIpSecService.closeUdpEncapsulationSocket(udpEncapResp.resourceId); } Optional: since it is irrelevant to this test, you can omit findUnusedPort() and just use 0.

Target:
public void testOpenUdpEncapsulationSocketCallsSetSocketOwner() throws Exception { IpSecUdpEncapResponse udpEncapResp = mIpSecService.openUdpEncapsulationSocket(0, new Binder()); verify(mMockNetd).ipSecSetSocketOwner(anyObject(), eq(Os.getuid())); mIpSecService.closeUdpEncapsulationSocket(udpEncapResp.resourceId); }
Source:
public Entity toEntity() { START Entity branchEntity = new END Entity(this.key); return branchEntity; } return ?

Target:
public Entity toEntity() { return new Entity(this.key); }
Source:
private static int readInt(File f) throws FileNotFoundException { START Scanner s = new Scanner(f); try { return s.nextInt(); } finally { s.close(); } END } I think you can write this as: try (Scanner s = new Scanner(f)) { return s.nextInt(); } (and similar for FileOutputStream below)

Target:
private static int readInt(File f) throws FileNotFoundException { try (Scanner s = new Scanner(f)) { return s.nextInt(); } }
Source:
private void onUserStart(int userId) { synchronized (mVpns) { Vpn userVpn = mVpns.get(userId); if (userVpn != null) { loge("Starting user already has a VPN"); return; } userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId); mVpns.put(userId, userVpn); } if (mUserManager.getUserInfo(userId).isPrimary() && START LockdownVpnTracker.isEnabled()) { updateLockdownVpn(); END } } Here too it looks like whether the tracker is enabled or not might change between the check and the call. Also LockdownVpnTracker.isEnabled() here might be replaced with mLockdownEnabled I thik

Target:
private void onUserStart(int userId) { synchronized (mVpns) { Vpn userVpn = mVpns.get(userId); if (userVpn != null) { loge("Starting user already has a VPN"); return; } userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId); mVpns.put(userId, userVpn); if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) { updateLockdownVpn(); } } }
Source:
synchronized boolean sendReport(BluetoothDevice device, int id, byte[] data) { if (DBG) { Log.d(TAG, "sendReport(): device=" + device + " id=" + id + START " caller=" + Binder.getCallingUid()); END } return checkDevice(device) && checkCallingUid() && mHidDeviceNativeInterface.sendReport(id, data); } In the common case, this will not be useful information. What about logging the CallingUid in checkCallingUid() if it doesn't match mCallingUid? Are there any cases where we wouldn't want to know if the wrong Uid is being used?

Target:
synchronized boolean sendReport(BluetoothDevice device, int id, byte[] data) { if (DBG) { Log.d(TAG, "sendReport(): device=" + device + " id=" + id); } return checkDevice(device) && checkCallingUid() && mHidDeviceNativeInterface.sendReport(id, data); }
Source:
public static InterfaceParams getByName(String name) { final NetworkInterface netif = getNetworkInterfaceByName(name); if (netif == null) return null; // Not all interfaces have MAC addresses, e.g. rmnet_data0. final MacAddress macAddr = getMacAddress(netif); try { return new InterfaceParams(name, netif.getIndex(), macAddr, netif.getMTU()); START } catch (IllegalArgumentException|NullPointerException|SocketException e) { END return null; } } Out of curiosity, where can this NPE come from? netif is known not to be null at this point.

Target:
public static InterfaceParams getByName(String name) { final NetworkInterface netif = getNetworkInterfaceByName(name); if (netif == null) return null; // Not all interfaces have MAC addresses, e.g. rmnet_data0. final MacAddress macAddr = getMacAddress(netif); try { return new InterfaceParams(name, netif.getIndex(), macAddr, netif.getMTU()); } catch (IllegalArgumentException|SocketException e) { return null; } }