auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static String getServicePrincipal(String serviceName) throws UnknownHostException { requireNonNull(serviceName, "serviceName is null"); String fqdn = InetAddress.getLocalHost().getCanonicalHostName(); checkState(!fqdn.equalsIgnoreCase("localhost"), "Fully qualified host name for localhost is not retrieved"); return String.format("%s/%s", serviceName, fqdn.toLowerCase(Locale.US)); }

Target:
Remove this as server has its own impl.
Source:
public Authentication findAuthentication(String type, URI uri, String realm) { if (authentication.matches(type, uri, realm)) { return authentication; } throw new UnsupportedOperationException(String.format("Authentication type %s is not supported", type)); }

Target:
Static import `format`
Source:
public void close() { try { context.dispose(); loginContext.logout(); } catch (GSSException | LoginException e) { throw new AuthenticationException(e); } }

Target:
This won't call `logout()` if `dispose()` fails.
Source:
public static String getServicePrincipal(String serviceName, String hostName) throws UnknownHostException { requireNonNull(serviceName, "serviceName is null"); requireNonNull(hostName, "hostName is null"); InetAddress address = InetAddress.getByName(hostName); String fqdn; if (address.getHostName().toLowerCase().startsWith("localhost")) { return getServicePrincipal(serviceName); } fqdn = address.getCanonicalHostName(); return String.format("%s/%s", serviceName, fqdn.toLowerCase(Locale.US)); }

Target:
Static import `format`
Source:
private static int decodeBucketIndex(int entry) { return entry >>> (Integer.SIZE - EXTENDED_PREFIX_BITS); }

Target:
this can be implemented with: decodeBucketIndex(EXTENDED_PREFIX_BITS, entry)?
Source:
public String getLevel(String loggerName) { java.util.logging.Logger logger = getLogger(loggerName); return getEffectiveLevel(logger).toString(); }

Target:
Inline this
Source:
public static double alpha(int indexBitLength) { double alpha; switch (indexBitLength) { case 4: alpha = 0.673; break; case 5: alpha = 0.697; break; case 6: alpha = 0.709; break; default: alpha = (0.7213 / (1 + 1.079 / numberOfBuckets(indexBitLength))); } return alpha; }

Target:
Return directly
Source:
public void addInstance(Object instance) throws Exception { State currentState = state.get(); if ((currentState == State.STOPPING) || (currentState == State.STOPPED)) { throw new IllegalStateException(); } else { startInstance(instance); if (methodsMap.get(instance.getClass()).hasFor(PreDestroy.class)) { if (!managedInstances.contains(instance)) { managedInstances.add(instance); } } } }

Target:
This is not thread safe. There is no way to do an "addIfAbsent" in a thread safe way using a ConcurrentLinkedQueue. You will have to either use external coordination (e.g., synchronize, lock, etc.) or change the users of managedInstance to de-duplicate on read.
Source:
public void close() { Closeables.closeQuietly(ioPool); Closeables.closeQuietly(httpClient); }

Target:
I think you want to do this in the reverse order
Source:
public int indexOfByte(int b) { checkArgument((b >> Byte.SIZE) == 0, "byte value out of range"); for (int i = 0; i < size; i++) { if (getByteUnchecked(i) == b) { return i; } } return -1; }

Target:
if the advantage of this compare to `0 <= b && b < 256`?
Source:
public Slice slice(int index, int length) { if ((index == 0) && (length == length())) { return this; } checkIndexLength(index, length); if (length == 0) { return Slices.EMPTY_SLICE; } if (reference == COMPACT) { return new Slice(base, address + index, length, retainedSize, NOT_COMPACT); } else { return new Slice(base, address + index, length, retainedSize, reference); } }

Target:
Nit: the `else` is redundant, remove it (thus the original line will remain unchanged)
Source:
public static Slice allocateDirect(int capacity) { checkSliceCapacity(capacity); if (capacity == 0) { return EMPTY_SLICE; } return wrappedBuffer(ByteBuffer.allocateDirect(capacity)); }

Target:
Move this below the `if (capacity == 0)` check. It can help avoid that extra comparison if the requested capacity is 0.
Source:
public static long hash(long seed, InputStream in) throws IOException { XxHash64 hash = new XxHash64(seed); byte[] buffer = new byte[8192]; while (true) { int n = in.read(buffer); if (n == -1) { break; } hash.update(buffer, 0, n); } return hash.hash(); }

Target:
Maybe call this "readBytes" or "length"
Source:
public void start() { try { this.server.start(); } catch (Exception e) { LOGGER.error("Fail to start the Jetty server... please check the availability of the port."); throw Throwables.propagate(e); } }

Target:
You don't block here until the server finishes by calling server.join() ? http://www.eclipse.org/jetty/documentation/current/embedding-jetty.html BTW: nice work Cedric, you have made the code of Kasper a lot cleaner & well tested, I am impressed :)
Source:
public boolean isPublic(final Class<? extends T> clazz) { final XKasperPublic annotation = checkNotNull(clazz).getAnnotation(XKasperPublic.class); return null != annotation; }

Target:
`return (null != checkNotNull(clazz).getAnnotation(XKasperPublic.class));` ?
Source:
public Optional<InterceptorChain<Command, CommandResponse>> create(final TypeToken<?> type) { final Class<?> commandClass = type.getRawType(); final boolean isPublicCommand = commandClass.isAnnotationPresent(XKasperPublic.class); SecurityStrategy securityStrategy = isPublicCommand ? new DefaultPublicSecurityStrategy(securityConfiguration) : new DefaultSecurityStrategy(securityConfiguration); final Interceptor<Command, CommandResponse> interceptor = new CommandSecurityInterceptor(securityStrategy); return Optional.of(InterceptorChain.makeChain(interceptor)); }

Target:
final
Source:
public QueryFactoryBuilder use(final BeanAdapter beanAdapter) { checkNotNull(beanAdapter); final TypeToken adapterForType = TypeToken.of(beanAdapter.getClass()) .getSupertype(BeanAdapter.class) .resolveType(BeanAdapter.class.getTypeParameters()[0]); beanAdapters.putIfAbsent(adapterForType.getRawType(), beanAdapter); return this; }

Target:
`ReflectionGenericsResolver.getParameterTypeFromClass(BeanAdapter1.class, BeanAdapter.class, 0)` should work https://github.com/viadeo/kasper-framework/blob/master/kasper-common/src/main/java/com/viadeo/kasper/tools/ReflectionGenericsResolver.java#L45-L52 ex : https://github.com/viadeo/kasper-framework/blob/master/kasper-common/src/main/java/com/viadeo/kasper/query/exposition/adapters/DefaultTypeAdapters.java#L198-L199
Source:
public KasperResponse(final KasperResponse response) { this.status = response.status; this.reason = response.reason; }

Target:
Could rather call this(response.status, response.reason) to be sure to do the checks which throws the IllegalStateException.
Source:
public HTTPKasperResponse asHttp(){ if (TransportMode.HTTP.equals(getTransportMode()) { return (HTTPKasperResponse) this; } throw new KasperException("Not an HTTP response"); }

Target:
:warning: misses closing parenthesis! `if (HTTPKasperResponse.class.isAssignableFrom(this.getClass())) {`
Source:
private void handleAddLabel() { int i = 1; }

Target:
Please remove this.
Source:
public List<Integer> getCurrentPositionOfSounds() { List<Integer> positionList = new ArrayList<>(); for (MediaPlayer mediaPlayer : mediaPlayers) { int position = mediaPlayer.isPlaying() ? mediaPlayer.getCurrentPosition() : mediaPlayer.getDuration(); positionList.add(position); } return positionList; }

Target:
Please rename this function. Maybe it is useful to map sounds to positions.
Source:
public static Collection<Object[]> data() { return Arrays.asList(new Object[][] { {"GlideToBrick", R.string.brick_glide, new GlideToBrick(), R.id.brick_glide_to_edit_text_x, R.id.brick_glide_to_edit_text_y, "1+2", 42, "1 + 2 ", "42 "}, {"PlaceAtBrick", R.string.brick_place_at, new PlaceAtBrick(), R.id.brick_place_at_edit_text_x, R.id.brick_place_at_edit_text_y, "1+2", 42, "1 + 2 ", "42 "} }); }

Target:
Since the input and the expected outcomes are everywhere the same, you could possibly move them into the test cases. (to reduce the overhead)
Source:
public void testLeftBubblePosition() { Float expectedXLeft = EXPECTED_X_STD_LEFT; Float expectedYLeft = EXPECTED_Y_STD; ShowBubbleActor bubbleActor = new ShowBubbleActor(OBJECT_NAME, sprite, Constants.SAY_BRICK); assertEquals(expectedXLeft, bubbleActor.calculateLeftImageX(CALC_X_LEFT)); assertEquals(expectedYLeft, bubbleActor.calculateImageY(CALC_Y_LEFT)); }

Target:
This is unnecessary since you just need those variables to compare with your result. Just use your defined constants here.
Source:
public static ProjectManager getInstance() { return INSTANCE; }

Target:
``` [2019-10-01T07:16:01.665Z] /home/catroid/jenkins_slave/workspace/Catroid_PR-3353/catroid/src/main/java/org/catrobat/catroid/ProjectManager.java:98: error: cannot find symbol [2019-10-01T07:16:01.665Z] return INSTANCE; [2019-10-01T07:16:01.665Z] ^ [2019-10-01T07:16:01.665Z] symbol: variable INSTANCE [2019-10-01T07:16:01.665Z] location: class ProjectManager ```
Source:
public List<UUID> getKeyList(List<? extends UserData> userDataList) { List<UUID> keyList = new ArrayList<>(); for (UserData userData : userDataList) { keyList.add(userData.getDeviceKey()); } return keyList; }

Target:
can be private
Source:
public void testRegistrationOk() throws WebconnectionException { authenticator.performCatrobatRegister(testEmail, "de", "at", sharedPreferences.edit()); verify(listenerMock, never()).onError(anyInt(), anyString()); verify(listenerMock, atLeastOnce()).onSuccess(); token = sharedPreferences.getString(Constants.TOKEN, Constants.NO_TOKEN); boolean tokenOk = new CatrobatServerCalls().checkToken(token, testUser, BASE_URL_TEST_HTTPS); assertTrue(tokenOk); }

Target:
you probably don't need to introduce an extra local var for this. assertTrue on the value you assign to `tokenOk` saves you a line
Source:
protected void onPreExecute() { super.onPreExecute(); if (contextWeakReference.get() == null) { return; } String title = contextWeakReference.get().getString(R.string.please_wait); String message = contextWeakReference.get().getString(R.string.loading); progressDialog = ProgressDialog.show(contextWeakReference.get(), title, message); }

Target:
Please read up on the correct usage of `WeakReference`. `get()` returns a regular reference, true, but unless you save this returned value somewhere, the `WeakReference` you hold does not prevent the garbage collector from collecting the context your weak reference points to. So you have to introduce a new local var, write the result of `contextWeakReference.get()` to it and use this regular reference for the remainder of this method. Otherwise you risk running into a NPE
Source:
public void testAddJumpStitchPoint() { EmbroideryStream stream = new DSTStream(); stream.addJump(); stream.addStitchPoint(0, 0); assertEquals(1, stream.getPointList().size()); assertTrue(stream.getPointList().get(0).isJumpPoint()); }

Target:
Please move to a `@before` function
Source:
protected void getTags() { GetTagsTask getTagsTask = new GetTagsTask(); getTagsTask.setOnTagsResponseListener(this); getTagsTask.execute(); }

Target:
Please revert to private
Source:
public void testBrickFieldValidValue() throws InterpretationException { assertSame(BRICK_FORMULA_VALUE, brickFormula.interpretInteger(sprite)); }

Target:
equals!
Source:
public void tearDown() throws IOException { firstProject = null; secondProject = null; }

Target:
This is just setting the object reference to null. As you saved the XML with XStream, the saved project is still remaining
Source:
public boolean getGlobalVariableConflicts(List<UserVariable> project1GlobalVars, List<UserVariable> project2GlobalVars) { List<UserVariable> conflicts = new ArrayList<>(); for (UserVariable project1GlobalVar : project1GlobalVars) { for (UserVariable project2GlobalVar : project2GlobalVars) { if (project1GlobalVar.getName().equals(project2GlobalVar.getName()) && !project1GlobalVar.getValue() .equals(project2GlobalVar.getValue())) { conflicts.add(project1GlobalVar); } } } return conflicts.isEmpty(); }

Target:
You could optimize this in a way like don't saving an extra list with the conflicts added. This should may be implemented in a ticket to resolve tickets. Just to understand, you are creating a new list and afterwards you are just returning a property of this list. Think about something like (Pseudo Code): ``` WHILE iterate_over_lists: IF conflict_found RETURN true; END IF END WHILE return false;
Source:
public boolean getGlobalListConflicts(List<UserList> project1GlobalLists, List<UserList> project2GlobalLists) { List<UserList> conflicts = new ArrayList<>(); for (UserList project1GlobalList : project1GlobalLists) { for (UserList project2GlobalList : project2GlobalLists) { if (project1GlobalList.getName().equals(project2GlobalList.getName()) && !project1GlobalList.getList() .equals(project2GlobalList.getList())) { conflicts.add(project1GlobalList); } } } return conflicts.isEmpty(); }

Target:
You actually don't need a whole Project Object becaus you only work with lists of project, please change the functionality to only work with lists, by now
Source:
public List<Sprite> getAllClonesOfSprite(Sprite sprite) { List<Sprite> clonesOfSprite = new ArrayList<Sprite>(); Pattern pattern = createCloneRegexPattern(sprite.getName()); for (Sprite spriteOfStage : sprites) { Matcher matcher = pattern.matcher(spriteOfStage.getName()); if (spriteOfStage.isClone && matcher.matches()) { clonesOfSprite.add(spriteOfStage); } } return clonesOfSprite; }

Target:
You could skip this if `spriteOfStage.isClone` is false
Source:
private @Nullable String getColorFormulaString() { Formula formula = getFormulaWithBrickField(BrickField.COLOR); FormulaElement formulaTree = formula.getFormulaTree(); boolean formulaIsString = formulaTree.getElementType() == FormulaElement.ElementType.STRING; return formulaIsString ? formulaTree.getValue() : null; }

Target:
please replace with if else construct
Source:
public void setUp() { Context context = InstrumentationRegistry.getTargetContext().getApplicationContext(); sensorNames.addAll(Arrays.asList(context.getResources().getStringArray(R.array.nxt_sensor_chooser))); sensorCodes.addAll(Arrays.asList(NXTSensor.Sensor.getSensorCodes())); sensorName = context.getString(sensorNameStringId); }

Target:
`...getTargetContext();` should be enough to return the current instrumented applications contex
Source:
public void testBrickFieldValidValue() throws InterpretationException { assertSame(BRICK_FORMULA_VALUE, brickFormula.interpretInteger(sprite)); assertSame(BRICK_FORMULA_VALUE, cloneBrickFormula.interpretInteger(sprite)); }

Target:
if you delete second line here, you can add the assert from testBrickFieldEquals to do the same thing but in one `assertSame(brickFormula.interpretInteger(sprite), cloneBrickFormula.interpretInteger(sprite));` So you are interpreting the correct value first, and then check the cloned one
Source:
public boolean act(float delta) { if (userVariable == null) { return true; } if (firstStart) { firstStart = false; writeActionFinished = false; new WriteVariableOnDeviceAction.WriteTask().execute(userVariable); } return writeActionFinished; }

Target:
in ReadVariableOnDeviceAction you have at this point "new ReadTask().execute(userVariable);" so it would be consistent if you would write "new WriteTask().execute(userVariable);"
Source:
public void setUp() { directory = new File(InstrumentationRegistry.getTargetContext().getCacheDir(), "DeviceValues"); directory.mkdir(); sprite = new Sprite("_sprite_"); userVariable = new UserVariable("globalVarX", initialValue); localUserVariable = new UserVariable("localVarY", initialValue); sprite.addUserVariable(localUserVariable); accessor = new DeviceVariableAccessor(directory); }

Target:
remove sprite and remove global/local, only test the accessor
Source:
public void writeVariable(UserVariable userVariable) throws IOException { if (checkDeviceVariableKeyEmpty(userVariable)) { addKeyToUserVariable(userVariable); } if (!deviceVariablesFile.exists()) { deviceVariablesFile.createNewFile(); } synchronized (LOCK) { HashMap deviceVariableMap = readMapFromJson(); if (deviceVariableMap == null) { deviceVariableMap = new HashMap<>(); } deviceVariableMap.put(userVariable.getDeviceValueKey(), userVariable.getValue()); writeMapToJson(deviceVariableMap); } }

Target:
this blows up when .getValue() returns NaN
Source:
public void delete(Scene sceneToDelete) throws IOException { StorageOperations.deleteDir(sceneToDelete.getDirectory()); File projectDirectory = ProjectManager.getInstance().getCurrentProject().getDirectory(); DeviceVariableAccessor accessor = new DeviceVariableAccessor(projectDirectory); for (Sprite sprite: sceneToDelete.getSpriteList()) { try { accessor.deleteAllLocalVariables(sprite); } catch (IOException e) { Log.i(TAG, e.getMessage()); } } }

Target:
instead of adding this removal procedure to every delete here and there id rather have a cleanup once eg. on project load.
Source:
public void onActivityResult(int requestCode, int resultCode, Intent data) { //Register your intent with "queueIntent" if (intentListeners.indexOfKey(requestCode) >= 0) { IntentListener asker = intentListeners.get(requestCode); asker.onIntentResult(resultCode, data); intentListeners.remove(requestCode); } else if (requestCode == REQUEST_EXPORT_EMBROIDERY_FILE) { if (resultCode == RESULT_OK) { Log.d(TAG, "Exported embroidery file"); } } else { stageResourceHolder.onActivityResult(requestCode, resultCode, data); } }

Target:
please remove this
Source:
public T remove(int index) { try { T removedObject = super.remove(index); comparingSet.remove(removedObject); return removedObject; } catch (IndexOutOfBoundsException ioobException) { throw new IndexOutOfBoundsException(); } }

Target:
same again. please throw original exception.
Source:
public T set(int index, T element) { try { if (element.equals(this.get(index))) { return element; } T oldObject = null; if (comparingSet.add(element)) { oldObject = super.set(index, element); comparingSet.remove(oldObject); } return oldObject; } catch (IndexOutOfBoundsException ioobException) { throw new IndexOutOfBoundsException(); } }

Target:
same again: do not create a new empty exception but reuse the old one.
Source:
public void cancelCall() { if (call != null) { okHttpClient.getDispatcher().getExecutorService().execute(new Runnable() { @Override public void run() { WebRequestListener listener = getListenerAndSetReferenceToNull(); if (listener != null) { call.cancel(); listener.onCancelledCall(); } } }); } }

Target:
why does this have to be run as a thread on some okHttpClient provided stack?
Source:
public boolean hasBackCameraFlash() { if (hasBackCamera()) { return backCameraInformation.flashAvailable; } return false; }

Target:
you can use "early return" here: ``` return hasBackCamera() && backCameraInformation.flashAvailable: ``` Java evaluates the right hand side of the condition first, so even no null pointer exception can occur here.
Source:
public static void pauseFlash() { Log.d(TAG, "pauseFlash()"); if (!paused && isAvailable()) { paused = true; if (isOn()) { startAgain = true; flashOff(); } } }

Target:
just remove the log altogether, as this was clearly added for debugging purposes. I think it is just bad practice to use log for debugging instead of Android Studio's debugger. breakpoints ftw! :smile:
Source:
public static void flashOff() { Log.d(TAG, "flashOff()"); if (!isAvailable()) { return; } CameraManager.getInstance().setFlashParams(paramsOff); currentFlashValue = false; }

Target:
another log that can be removed (I know it's not part of your commit, but please do it anyway).
Source:
public void setUp() { Project project = new Project(InstrumentationRegistry.getTargetContext(), projectName); ProjectManager.getInstance().setCurrentProject(project); fileGenerator = new DSTFileGenerator(); dstFile = new File(Constants.CACHE_DIR + "/" + projectName + ".dst"); }

Target:
please use dstFile = new File(Constants.CACHE_DIR, projectName + ".dst") instead
Source:
public void onBackPressed() { if (coordinatesChanged) { showSaveChangesDialog(this); } else { super.onBackPressed(); } }

Target:
please rename to finishWithResult or something similar. since its not saving anything, and also finishing the activity
Source:
public void onResume() { super.onResume(); setShowProgressBar(false); adapter.items.get(0).subtitle = Utils.getCurrentProjectName(getActivity()); adapter.notifyDataSetChanged(); String projectName = getActivity().getIntent().getStringExtra(StatusBarNotificationManager.EXTRA_PROJECT_NAME); if (projectName != null) { loadDownloadedProject(projectName); getActivity().getIntent().removeExtra(StatusBarNotificationManager.EXTRA_PROJECT_NAME); } }

Target:
remove this line please
Source:
public IfLogicEndBrick(IfLogicBeginBrick ifLogicBeginBrick, IfLogicElseBrick ifElseBrick) { this.ifElseBrick = ifElseBrick; this.ifBeginBrick = ifLogicBeginBrick; }

Target:
Please also swap these two lines :laughing:
Source:
private static Boolean isNewStitchPoint(PointF point) { if (point.x != stitchPoints.get(lastIndex).x || point.y != stitchPoints.get(lastIndex).y) { return true; } return false; }

Target:
or just simply: return stitchPoints.get(stitchPoints.size() - 1).equals(point) besides that, maybe remove lastIndex, because this is really unnecessary and errorprone to manually keep the size of that list in a seperate variable.
Source:
protected void onDestroy() { super.onDestroy(); conversionManager.shutdown(); conversionManager.removeGlobalDownloadCallback(getSlidingUpFragment()); conversionManager.removeBaseInfoViewListener(getSlidingUpFragment()); conversionManager.removeGlobalJobViewListener(getSlidingUpFragment()); client = null; }

Target:
is this really necessary? you destroy the activity anyway.
Source:
public void setUp() throws Exception { Script startScript = BrickTestUtils.createProjectAndGetStartScript("newDataDialogTest"); variableBrickPosition = 1; listBrickPosition = 2; // "when program starts" brick is the first startScript.addBrick(variableBrickPosition - 1, new SetVariableBrick()); startScript.addBrick(listBrickPosition - 1, new AddItemToUserListBrick()); baseActivityTestRule.launchActivity(); }

Target:
position is not necessary, just add them in the order you want to have them there: startScript.addBrick(new SetVariableBrick()); startScript.addBrick(new AddItemToUserListBrick());
Source:
private String cutTrailingZerosofString(String number) { BigDecimal decimal = new BigDecimal(number); if (decimal.compareTo(BigDecimal.ZERO) == 0) { decimal = BigDecimal.ZERO; } else { decimal = decimal.stripTrailingZeros(); } return decimal.toPlainString(); }

Target:
Please explain. If it's because of negative zero, please provide a code snippet where the result is `-0` without this code.
Source:
public void onResume() { BottomBar.hideBottomBar(getActivity()); super.onResume(); adapter.notifyDataSetChanged(); }

Target:
Nice catch, but instead of hiding the bottom bar we should remove it altogether, it is never used in the backpack anyway.
Source:
public void testCreateUserListInSpinner() { onBrickAtPosition(brickPosition).onVariableSpinner(R.id.insert_item_into_userlist_spinner) .performNewVariableInitial(newList); onBrickAtPosition(brickPosition).onVariableSpinner(R.id.insert_item_into_userlist_spinner) .checkShowsText(newList); }

Target:
no need to address the element twice, you can perform multiple checks operations on it in series: onBrickAtPosition(brickPosition).onVariableSpinner(R.id.insert_item_into_userlist_spinner) .performNewVariableInitial(newList); .checkShowsText(newList);
Source:
public void setUp() throws Exception { Script script = BrickTestUtils.createProjectAndGetStartScript("PhiroSeekBarColorBrickTest"); script.addBrick(new PhiroRGBLightBrick(PhiroRGBLightBrick.Eye.BOTH, INIT_COLOR_VALUE, INIT_COLOR_VALUE, INIT_COLOR_VALUE)); baseActivityTestRule.launchActivity(null); }

Target:
please call baseActivityTestRule.launchActivity() if you give it null, it ignores the fragment position given in the rules constructor.
Source:
public void uncaughtException(Thread thread, Throwable exception) { CrashReporter.storeUnhandledException(exception); preferences.edit().putBoolean(RECOVERED_FROM_CRASH, true).commit(); Log.e(TAG, "uncaughtException: ", exception); exit(); }

Target:
Exactly! Thanks! Oh, please move this line up to the top of the method. Logging the error should be the first statement imo.
Source:
public void onLoadProjectSuccess(boolean startProjectActivity) { if (getActivity() == null) { Log.e(TAG, "Null Value of getActivity() at onLoadProjectSuccess"); return; } Intent intent = new Intent(getActivity(), ProjectActivity.class); intent.putExtra(Constants.PROJECT_OPENED_FROM_PROJECTS_LIST, true); getActivity().startActivity(intent); }

Target:
You don't need to check for `null` because the Task which triggers this callback should have been canceled anyway. If the problem still exists, Crashlytics will tell us.
Source:
private void disposeTextures() { for (Scene scene : project.getSceneList()) { for (Sprite sprite : scene.getSpriteList()) { for (int j = 0; j < sprite.getLookDataList().size(); j++) { LookData lookData = sprite.getLookDataList().get(j); lookData.getPixmap().dispose(); lookData.getTextureRegion().getTexture().dispose(); } } } }

Target:
`for (LookData lookData : sprite.getLookDataList()) {` I'll take a look at the test asap
Source:
public static void setCloudNotificationsEnabled(Context context, boolean isEnabled) { SharedPreferences.Editor editor = getSharedPreferences(context).edit(); editor.putBoolean(SETTINGS_CLOUD_NOTIFICATIONS, isEnabled); editor.commit(); if (isEnabled) { CloudMessaging.initialize(context); } }

Target:
Disabling notifications will not unsubscribe from FCM (immediately) if `CloudMessaging.initialize` is not called. However, see https://github.com/Catrobat/Catroid/pull/2430#issuecomment-318926128
Source:
public static void setCloudNotificationsEnabled(Context context, boolean isEnabled) { SharedPreferences.Editor editor = getSharedPreferences(context).edit(); editor.putBoolean(SETTINGS_CLOUD_NOTIFICATIONS, isEnabled); editor.commit(); CloudMessaging.initialize(context); }

Target:
you can directly put `.commit()` at the end of this. Editor calls always return the Editor again ;)
Source:
protected void doLookUpdate() { updateLookFromFormula(); if (wait) { BackgroundWaitHandler.addObserver(look, this); } if (look != null && sprite != null && sprite.getLookDataList().contains(look)) { sprite.look.setLookData(look); setLookDone = true; } }

Target:
should this really be done before the check below? what happens if the observer gets added, but the `setLookData()` never gets called?
Source:
public List<BackPackedListData> getBackPackedListData() { return backPackedListData != null ? backPackedListData : new ArrayList<BackPackedListData>(); }

Target:
It would be better to initialise the member variable at the point of declaration (i.e. ``` List<BackpackedListData> backPackedListData = new ArrayList<>(); ``` instead of checking here. you can still overwrite the list at other points and you save yourself this (unnecessary) check.
Source:
public static int getUniqueNotificationId() { if (uniqueNotificationIdCounter == null) { uniqueNotificationIdCounter = new AtomicInteger(0); } return uniqueNotificationIdCounter.incrementAndGet(); }

Target:
since it's not a static method anymore with the latest changes, it might be removed again, am i right?
Source:
public void buttonContinueOpensProjectActivity() throws ClassNotFoundException, NoSuchMethodException, NoSuchFieldException, InvocationTargetException, IllegalAccessException { onView(withId(R.id.main_menu_button_continue)) .perform(click()); onView(withId(R.id.fragment_sprites_list)) .check(matches(isDisplayed())); }

Target:
why the list of exceptions?
Source:
public static void setAutoCrashReportingEnabled(Context context, boolean isEnabled) { SharedPreferences.Editor editor = getSharedPreferences(context).edit(); editor.putBoolean(SETTINGS_CRASH_REPORTS, isEnabled); editor.commit(); CrashReporter.IS_CRASH_REPORTER_INITIALIZED = CrashReporter.initialize(context); }

Target:
Instead of assigning the variable here, update the variable in the `CrashReporter.initialize` method itself.
Source:
public static void setAutoCrashReportingEnabled(Context context, boolean isEnabled) { SharedPreferences.Editor editor = getSharedPreferences(context).edit(); editor.putBoolean(SETTINGS_CRASH_REPORTS, isEnabled); editor.commit(); CrashReporter.initialize(context); }

Target:
Please undo as was. Calling initialize even if you don't want to initialize the CrashReporter is really really odd.
Source:
public static boolean initialize(Context context) { preferences = PreferenceManager.getDefaultSharedPreferences(context); if (CrashReporter.isReportingEnabled()) { reporter.initialize(context); Log.d(TAG, "INITIALIZED!"); return true; } Log.d(TAG, "INITIALIZATION FAILED! [ Report : " + isReportingEnabled() + "]"); return false; }

Target:
~`CrashReporter.`~`isReportingEnabled()`
Source:
public void testAutoCrashReportEnabling() { Context context = InstrumentationRegistry.getTargetContext(); SettingsActivity.setAutoCrashReportingEnabled(context, false); verify(CrashReporter.reporter, Mockito.times(0)).initialize(context); SettingsActivity.setAutoCrashReportingEnabled(context, true); verify(CrashReporter.reporter, Mockito.times(1)).initialize(context); }

Target:
`verify(`~`CrashReporter.`~`reporter, `~`Mockito.`~`times(1)).initialize(context);`
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); titleActionBar = null; returnToProjectsList = false; returnByPressingBackButton = false; Thread.setDefaultUncaughtExceptionHandler(new BaseExceptionHandler()); checkIfCrashRecoveryAndFinishActivity(this); getActionBar().setDisplayHomeAsUpEnabled(true); sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); }

Target:
Inline occurrences
Source:
public boolean isRecoveredFromCrash() { return PreferenceManager.getDefaultSharedPreferences(this).getBoolean(RECOVERED_FROM_CRASH, false); }

Target:
Please make private and put it after the `checkIfCrashRecoveryAndFinishActivity` method. > We like to put the private utilities called by a public function right after the public function itself. This follows the stepdown rule and helps the program read like a newspaper article. -Clean Code|Chapter 10: Classes
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); titleActionBar = null; returnToProjectsList = false; returnByPressingBackButton = false; Thread.setDefaultUncaughtExceptionHandler(new BaseExceptionHandler(this)); checkIfCrashRecoveryAndFinishActivity(this); getActionBar().setDisplayHomeAsUpEnabled(true); CrashReporter.sendUnhandledCaughtException(); }

Target:
this is really obvuscating whats going on here, it says sendUnhandledCaughtException and is called EVERY time on create of the activity. why not move the whole thing to checkIfCrashRecovery or into exceptionHandler or somewhere else...
Source:
public static void sendUnhandledCaughtException() { String json = preferences.getString(EXCEPTION_FOR_REPORT, ""); if (isReportingEnabled() && !json.isEmpty()) { Log.d(TAG, "AFTER_EXCEPTION : sendCaughtException()"); Gson gson = new Gson(); Throwable exception = gson.fromJson(json, Throwable.class); if (logException(exception)) { preferences.edit().remove(EXCEPTION_FOR_REPORT).commit(); } } }

Target:
please make logException return void. - the boolean return value is only utilized here. - its always going to be true, since in line 93 you made sure that its only reached when isReportingEnabled() is true
Source:
public void uncaughtException(Thread thread, Throwable exception) { Log.e(TAG, "unhandled exception", exception); CrashReporter.storeUnhandledException(exception); if (!BuildConfig.DEBUG) { System.exit(EXIT_CODE); android.os.Process.killProcess(android.os.Process.myPid()); } }

Target:
Please remove the if condition (keep the content (exit, kill)). We are handling this in https://github.com/Catrobat/Catroid/pull/2365#discussion_r123898209 There seems to be a problem if we don't exit, kill the process. More details on https://github.com/Catrobat/Catroid/pull/2365#discussion_r124620967
Source:
public void createProject() { Script script; brickPosition = 1; ifBrick = new PhiroIfLogicBeginBrick(); IfLogicElseBrick ifLogicElseBrick = new IfLogicElseBrick(ifBrick); IfLogicEndBrick ifLogicEndBrick = new IfLogicEndBrick(ifLogicElseBrick, ifBrick); ifBrick.setIfElseBrick(ifLogicElseBrick); ifBrick.setIfEndBrick(ifLogicEndBrick); script = BrickTestUtils.createProjectAndGetStartScript("PhiroIfBrickTest"); script.addBrick(ifBrick); script.addBrick(ifLogicElseBrick); script.addBrick(ifLogicEndBrick); }

Target:
why initialization separate from assignment? (line120)
Source:
public void setUp() throws Exception { createProjectAndGetStartScriptWithImages("BroadcastBrickTest"); baseActivityTestRule.launchActivity(null); onView(withId(R.id.brick_when_condition_edit_text)).perform(click()); onView(withId(R.id.formula_editor_keyboard_sensors)).perform(click()); onView(withText(getResourcesString(R.string.formula_editor_function_touched))).perform(click()); onView(withId(R.id.formula_editor_keyboard_ok)).perform(click()); }

Target:
why is this necessary? why onTouch? please do not use espresso onView or onData operations in setUp.
Source:
public void clear(String sceneName) { if (!broadcastSequenceMap.containsKey(sceneName)) { return; } broadcastSequenceMap.get(sceneName).clear(); }

Target:
please change to: if (broadcastSequenceMap.containsKey(sceneName)) { broadcastSequenceMap.get(sceneName).clear(); } its a lot easier to read...
Source:
public void setUp() throws Exception { brickPosition = 1; valToChange = 30.5f; BrickTestUtils.createProjectAndGetStartScript("changeTransparencyByNBricktest1") .addBrick(new ChangeTransparencyByNBrick()); baseActivityTestRule.launchActivity(null); }

Target:
same as above, please make this a local variable instead of a member
Source:
public static void enlargeButtonText(Button button) { if (modifier == 1.0f) { return; } if (!enlargedButtons.contains(button)) { button.setTextSize(TypedValue.COMPLEX_UNIT_PX, button.getTextSize() * getModifier()); enlargedButtons.add(button); } }

Target:
is this keeping of already modified buttons necessary?
Source:
private Object interpretDistanceToSpritePosition(Sprite currentSprite, String secondSpriteName) { Sprite secondSprite; try { secondSprite = ProjectManager.getInstance().getSceneToPlay().getSpriteBySpriteName(secondSpriteName); } catch (Resources.NotFoundException exception) { return 0d; } float secondSpriteXPosition = secondSprite.look.getXInUserInterfaceDimensionUnit(); float secondSpriteYPosition = secondSprite.look.getYInUserInterfaceDimensionUnit(); return currentSprite.look.getDistanceToInUserInterfaceDimensions(secondSpriteXPosition, secondSpriteYPosition); }

Target:
None of the methods in the try block throw a `NotFoundException`.
Source:
private void askQuestion() { ArrayList<Object> params = new ArrayList<>(); params.add(this); if (StageActivity.messageHandler == null) { return; } // Check to see if a recognition activity is present Message message = StageActivity.messageHandler.obtainMessage(StageActivity.REGISTER_INTENT, params); message.sendToTarget(); questionAsked = true; }

Target:
This can be done before creating the ArrayList (also in AskAction)
Source:
public static <T extends Object> List<T> distinctListByClassOfObjects(List<T> listToDistinct) { List<T> distinctList = new ArrayList<>(); HashMap<Class, T> uniqueMap = new HashMap<>(); for (T objectInstance : listToDistinct) { uniqueMap.put(objectInstance.getClass(), objectInstance); } distinctList.addAll(uniqueMap.values()); return distinctList; }

Target:
Perfect! :+1: Just a few things. I'm a little picky here :grimacing: No need to `extends Object`. Please use `Map` as declaration type. ```java return new ArrayList<>(uniqueMap.values()); ``` The method is a perfect text-book example for tests. :wink:
Source:
public Scene getCurrentScene() { if (currentScene == null && project != null) { currentScene = project.getDefaultScene(); } return currentScene; }

Target:
can it happen here that null is returned when current scene = null and project = null? can this be a problem?
Source:
public void onClick(View view) { if (adapter == null) { return; } if (adapter.getActionMode() != BrickAdapter.ActionModeEnum.NO_ACTION) { return; } if (((BrickAdapter) adapter).isDragging) { return; } showFormulaEditorToEditFormula(view); }

Target:
possible cause of ClassCastException, instanceof check required before casting
Source:
public boolean checkSpriteReplaceInBackpack(List<Sprite> currentSpriteList) { boolean spritesAlreadyInBackpack; for (Sprite sprite : currentSpriteList) { spritesAlreadyInBackpack = checkSpriteReplaceInBackpack(sprite); if (spritesAlreadyInBackpack) { return true; } } return false; }

Target:
Please inline and remove
Source:
private void addAttribute(XMLExtendedStreamReader reader, ModelNode operation, SimpleAttributeDefinition attributeDefinition) throws XMLStreamException { String value = rawAttributeText(reader, attributeDefinition.getXmlName(), attributeDefinition.getDefaultValue().asString()); if (value != null) { attributeDefinition.parseAndSetParameter(value, operation, reader); } else { throw missingRequired(reader, attributeDefinition.getXmlName()); } }

Target:
@ochaloup The parser can't do this. It needs to preserve what it read from the xml, not introduce default values into the management model that were not what the user put in the xml. The subsystem can use a default value from the AttributeDefinition to configure the runtime services, but what's stored in the management model should reflect the user provided configuration. It appears this method is only called by the parseCM method, so I think just eliminating the 'else' block that throws missingRequired would be fine.
Source:
private void processComponentConfig(final EEApplicationClasses applicationClasses, final DeploymentReflectionIndex deploymentReflectionIndex, final ComponentDescription description, DeploymentUnit deploymentUnit) throws DeploymentUnitProcessingException { final Class<?> componentClass; try { componentClass = ClassLoadingUtils.loadClass(description.getComponentClassName(), deploymentUnit); handleAnnotations(applicationClasses, deploymentReflectionIndex, componentClass, description); } catch (Throwable e) { //just ignore the class for now. //if it is an optional component this is ok, if it is not an optional component //it will fail at configure time anyway EeLogger.ROOT_LOGGER.debugf(e,"Ignoring failure to handle interceptor annotations for %s", description.getComponentClassName()); return; } }

Target:
LGTM. Some minor points: we can now remove `throws DeploymentUnitProcessingException` since the method already catches all exceptions. `return;` is now also redundant. `final <class> componentClass` can be combined with assignment.
Source:
protected void recordCapabilitiesAndRequirements(OperationContext context, ModelNode operation, Resource resource) throws OperationFailedException { super.recordCapabilitiesAndRequirements(context, operation, resource); ModelNode defaultTracer = DEFAULT_TRACER.resolveModelAttribute(context, operation); if (defaultTracer.isDefined()) { context.registerCapability(RuntimeCapability.Builder.of(DEFAULT_TRACER_CAPABILITY.getDynamicName(defaultTracer.asString()), false).build()); } }

Target:
I don't think you want to call the super implementation, as you are handling capability registration conditionally.
Source:
static ResourceDescriptionResolver getResourceDescriptionResolver(final String... keyPrefix) { String[] prefixes = new String[keyPrefix.length + 1]; prefixes[0] = SUBSYSTEM_NAME; System.arraycopy(keyPrefix, 0, prefixes, 1, keyPrefix.length); return getResourceDescriptionResolver(false, prefixes); }

Target:
This seems a bit unnecessary. Any way to avoid it?
Source:
public void registerAttributes(ManagementResourceRegistration resourceRegistration) { super.registerAttributes(resourceRegistration); resourceRegistration.registerReadOnlyAttribute(TRACER_CONFIGURATION_NAME, null); resourceRegistration.registerReadOnlyAttribute(TRACER_CONFIGURATION, null); }

Target:
The super implementation is a no-op by design.
Source:
public void testStatefulTimeout0() throws Exception { Annotated0TimeoutBean timeout0 = lookup(Annotated0TimeoutBean.class); timeout0.doStuff(); Thread.sleep(2000); try { timeout0.doStuff(); throw new RuntimeException("Expecting NoSuchEJBException"); } catch (NoSuchEJBException expected) { } Assert.assertTrue(Annotated0TimeoutBean.preDestroy); }

Target:
This sleep should not be necessary.
Source:
public void accept(T value) { Lock lock = this.lock.writeLock(); lock.lock(); try { this.value = value; } finally { lock.unlock(); } }

Target:
If you'll eliminate the lock, accept method will contain just "this.value = value;" statement
Source:
public <R, E extends Exception> R execute(ExceptionFunction<T, R, E> function) throws E { Lock lock = this.lock.readLock(); lock.lock(); try { T value = this.value; return (value != null) ? function.apply(value) : null; } finally { lock.unlock(); } }

Target:
And above two lines will do perfect job for you. Yes, you could miss some statistics, but this is the case anyway because there's a race condition between retrieving the executor and invoking it.
Source:
private static AttributeDefinition getAttributeDefinition(String name, ModelType modelType, ModelNode defaultValue) { if (NO_DEFAULT.equals(defaultValue.asString())) { return new SimpleAttributeDefinitionBuilder(name, modelType) .setRequired(false) .setAllowExpression(false) .build(); } else { return new SimpleAttributeDefinitionBuilder(name, modelType) .setRequired(false) .setAllowExpression(false) .setDefaultValue(defaultValue) .build(); } }

Target:
Attribute should allow expressions.
Source:
protected void revertUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName, ModelNode valueToRestore, ModelNode valueToRevert, Void handback) throws OperationFailedException{ Resource resource = context.readResource(PathAddress.EMPTY_ADDRESS); ModelNode model = resource.getModel(); attributeDefinition.validateAndSet(operation, model); JaxrsContextParamHandler.setContextParam(attributeName, valueToRestore); }

Target:
Doesn't belong in this method.
Source:
private static AttributeDefinition getListAttributeDefinition(String name, ModelType modelType) { return new StringListAttributeDefinition.Builder(name) .setRequired(false) .setAllowExpression(false) .setValidator(JavaIdListValidator.INSTANCE) .build(); }

Target:
Well, maybe that doesn't apply as this isn't really a map. It's a list of strings with the strings presumably being an opaque key/value pair. That's not how the WF management API typically handles maps.
Source:
public boolean isCallerInRole(String role) { String caller = ctx.getCallerPrincipal().getName(); if (!USER.equals(caller)) { log.severe("Caller name is not " + USER + ", but " + caller); } return ctx.isCallerInRole(role); }

Target:
Should this fail instead of just logging?
Source:
public void close() { this.bean.close(); if (!this.bean.isValid()) { InfinispanBeanManager.this.cancel(this.bean); } else { InfinispanBeanManager.this.schedule(this.bean); } }

Target:
I don't think it makes sense to schedule expiration/passivation on release. The last access time isn't updated until close(), and we already schedule for expiration/passivation then.
Source:
public void reset() { latch = new CountDownLatch(1); latch2 = new CountDownLatch(1); System.out.println("RESET " + latch); }

Target:
This should probably be removed
Source:
public SmallRyeHealth getHealth() { String emptyChecksStatus = emptyLivenessChecksStatus.equals(DOWN) || emptyReadinessChecksStatus.equals(DOWN) ? DOWN : UP; return getHealth(emptyChecksStatus, healthChecks, livenessChecks, readinessChecks); }

Target:
Just a proposal - changing this to ``` DOWN.equals(emptyLivenessChecksStatus) || DOWN.equals(emptyReadinessChecksStatus) ? DOWN : UP; ``` may prevent some possible NPEs.
Source:
public static boolean hasLogMessage(String logFileName, String logMessage) throws Exception { BufferedReader fileReader = null; boolean found = false; Path logPath = LoggingUtil.getInServerLogPath(logFileName); fileReader = Files.newBufferedReader(logPath); String line = ""; while ((line = fileReader.readLine()) != null) { if(line.contains(logMessage)) { found = true; break; } } fileReader.close(); return found; }

Target:
We should probably just use a try with resources here. At a minimum we'd need the close in a finally block. Something like ``` public static boolean hasLogMessage(String logFileName, String logMessage) throws Exception { boolean found = false; Path logPath = LoggingUtil.getInServerLogPath(logFileName); try (BufferedReader fileReader = Files.newBufferedReader(logPath)) { String line = ""; while ((line = fileReader.readLine()) != null) { if (line.contains(logMessage)) { found = true; break; } } } return found; } ```
Source:
public ResourceDescriptor addAttributes(Collection<AttributeDefinition> attributes) { for (AttributeDefinition attribute : attributes) { this.addAttributes(new Attribute() { @Override public AttributeDefinition getDefinition() { return attribute; } }); } return this; }

Target:
There's no reason to wrap the AttributeDefinition. Add directly to the this.attributes collection.
Source:
public void destroy() { // add a breakpoint here to check if this method is invoked LOG.info("===================="); LOG.info("Destroyed CountBean"); LOG.info("===================="); TestResultsBean.setPreDestroySessionScoped(true); }

Target:
In order that the test runs successfully is a debugger required or is this some artifact of the test development?
Source:
private void setPreservePathOnForward(Boolean preservePathOnForward) throws Exception { String opName = preservePathOnForward == null ? UNDEFINE_ATTRIBUTE_OPERATION : WRITE_ATTRIBUTE_OPERATION; ModelNode setPreservePathOp = createOpNode("subsystem=undertow/servlet-container=default", WRITE_ATTRIBUTE_OPERATION); setPreservePathOp.get("name").set("preserve-path-on-forward"); if (preservePathOnForward != null) { setPreservePathOp.get("value").set(preservePathOnForward); } CoreUtils.applyUpdate(setPreservePathOp, managementClient.getControllerClient()); ServerReload.executeReloadAndWaitForCompletion(managementClient.getControllerClient()); }

Target:
Instead of `WRITE_ATTRIBUTE_OPERATION`, should not be used `opName` here?
Source:
public ElytronManagedThreadFactory(String name, ContextServiceImpl contextService, int priority) { super(name, contextService, priority); fccl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged(); }

Target:
It probably makes sense to just use the `org.jboss.as.ee` module class loader here instead of hoping we get the right one.
Source:
private void activate() { ClassLoader oldTccl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged(); try { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(classLoader); NamespaceContextSelector.pushCurrentSelector(this.getNamespaceContextSelector()); this.endpoint.activate(endpointFactory, activationSpec); NamespaceContextSelector.popCurrentSelector(); } catch (Exception e) { throw EjbLogger.ROOT_LOGGER.failedToActivateMdb(getComponentName(), e); } finally { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(oldTccl); } }

Target:
The code between push and pop should be wrapped in a "try" block, and pop invoked on "finally".
Source:
public DeploymentRepository getValue() throws IllegalStateException, IllegalArgumentException { return this; }

Target:
You can drop these from the throws clause. Not only are they not thrown, but they are RuntimeExceptions.
Source:
public void stopContainer() throws Exception { deployer.undeploy(APP_CONTEXT); final ModelControllerClient client = TestSuiteEnvironment.getModelControllerClient(); final ManagementClient managementClient = new ManagementClient(client, TestSuiteEnvironment.getServerAddress(), TestSuiteEnvironment.getServerPort(), "remote+http"); LOGGER.info("*** reseting test configuration"); serverTearDown(managementClient); LOGGER.trace("*** stopping container"); containerController.stop(CONTAINER); }

Target:
Was there a reason to change this to info instead of trace?
Source:
public void run() { final ExecutorService executor = executorServiceInjectedValue.getOptionalValue(); if (executor != null) { executor.submit(this::persistTimer); } }

Target:
This will never be null, as this is not an optional dependency. Functionally it makes no difference but it could be confusing to someone reading the code.