auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void processRequest(RequestEvent requestReceivedEvent) { Request request = requestReceivedEvent.getRequest(); ServerTransaction serverTransactionId = requestReceivedEvent .getServerTransaction(); LOG.info("\n\nRequest " + request.getMethod() + " received at " + ProtocolObjects.sipStack.getStackName() + " with server transaction id " + serverTransactionId); // We are the UAC so the only request we get is the BYE. SipProvider provider = (SipProvider) requestReceivedEvent.getSource(); if (request.getMethod().equals(Request.BYE)) processBye(provider, request, serverTransactionId); }

Target:
i would try to minize changes in the code. Apparently there lots of files affected just to rename the "logger" variable name. Even if we agree that name is better or not, I would prefer to stay with the previous name, in order to minimize the number of files changed. It would be different if we really take a new Log4j2 API to improve code readibility/performance like parameterized log https://logging.apache.org/log4j/2.0/manual/messages.html
Source:
private SIPDialog findSIPDialogFromInjectionListeners(String dialogId) { SIPDialog dialog = null; synchronized (dialogInjectionListeners) { for(SIPDialogInjectionListener listener : dialogInjectionListeners) { SIPDialog tempDialog = listener.getExternalSIPDialog(dialogId); if(tempDialog != null && tempDialog.getDialogId().equals(dialogId)) { dialog = tempDialog; // Take first valid Dialog and ignore following listener break; } } } return dialog; }

Target:
what kind of concurrent access are you trying to sync? In this case, are you trying to prevent multiple invocations to findSIPDialogFromInjectionListeners to be concurrent?if yes, why, it seems to be readOnly scenario? If you are trying to sync with add/remove writing scenarios, so the iterator is protected against concurrent modifcation, shouldnt you use synchronize on those scenarios as well? Is it becuase the subsequent invocation to "putDialog"? if yes, why? dialogTable seems to be already synced with a concurrent Map.
Source:
public static ModuleManager create() throws Exception { ModuleManager moduleManager = new ModuleManagerImpl(""); return LoadModuleEnvironment(moduleManager); }

Target:
```suggestion return create(""); ```
Source:
public static Diamond3iIterable.Builder shell(Vector3ic origin, int radius) { return new Diamond3iIterable.Builder(origin, radius).start(radius - 1); }

Target:
+/- 1 confusion: ```suggestion return new Diamond3iIterable.Builder(origin, radius).start(radius); ```
Source:
public Diamond3iIterable.Builder start(int start) { this.startDistance = start + 1; return this; }

Target:
+/- 1 confusion: ```suggestion this.startDistance = start; ``` that was the last one.
Source:
public void onEmission(TextureOffsetGeneratorComponent component, ParticleData particleData, Random random) { if (component.validOffsets.size() == 0) { return; } final int randomOffsetIndex = random.nextInt(component.validOffsets.size()); final Vector2f randomOffset = component.validOffsets.get(randomOffsetIndex); particleData.textureOffset.set(randomOffset.x(), randomOffset.y()); }

Target:
Could be simplified: ```suggestion particleData.textureOffset.set(randomOffset); ```
Source:
private void updateSliderIfInteger(UISlider slider) { T settingValue = getSetting().getValue(); if (settingValue instanceof Float || settingValue instanceof Double) { return; } slider.setIncrement(1.0f); slider.setPrecision(0); }

Target:
Doesn't this also trigger on `Byte`, `Short` and `Long` rather than `Integer`?
Source:
public String getText() { String arrayText = ""; if(linesOfText != null) arrayText = String.join("\n", linesOfText); if(text.get() != "") return text.get() + "\n" + arrayText; return text.get() + arrayText; }

Target:
Try and avoid single line `if`s without the brackets. same applies for `for`s as well
Source:
public void setText(String val) { String prevText = getText(); boolean callEvent = !prevText.equals(val); text.set(val != null ? val : ""); linesOfText = null; correctCursor(); if (callEvent) { for (TextChangeEventListener listener : textChangeListeners) { listener.onTextChange(prevText, val); } } }

Target:
like above, i'd prefer a blank entry over null
Source:
private void changeValue(float delta) { float newValue = TeraMath.clamp(getValue() + delta, 0, getRange() + getMinimum()); setValue(newValue); }

Target:
Wouldn't `getMinimum()` be more appropriate here than `0`.
Source:
public String getMode() { if (!isEnabled()) { return DISABLED_MODE; } if (active || (TabbingManager.focusedWidget != null && TabbingManager.focusedWidget.equals(this))) { return ACTIVE_MODE; } else if (tickerListener.isMouseOver()) { return HOVER_MODE; } return DEFAULT_MODE; }

Target:
If you do `this.equals(TabbingManager.focusedWidget)` then you don't need the bulky null check here, as `equals` returns false for null
Source:
public BaseStrictlySparseFieldFacet2D(Region3i targetRegion, Border3D border) { super(targetRegion, border); Vector2i size = getRelativeRegion().size(); this.data = new ArrayList<>(Collections.nCopies(size.x * size.y, Optional.empty())); }

Target:
Forgive me if I'm mistaken but if you're pre-populating all positions with an optional then it's not particularly sparse? Could you not store a `Map<Integer, Float>` and then use the `getOrDefault` method to return either the float at the position or null, and wrap it in an optional just before it's actually returned.
Source:
public static boolean containsConsole() { if (enabledWidgets != null) { boolean containsConsole = false; for (CoreScreenLayer layer : enabledWidgets) { if (layer instanceof ConsoleScreen) { LoggerFactory.getLogger("").info("console open"); containsConsole = true; } } return containsConsole; } return false; }

Target:
This shouldn't be here
Source:
private boolean isNameValid(String name) { Path destinationPath = PathManager.getInstance().getRecordingPath(name); // invalid characters are filtered, so if the file name is made up of entirely invalid characters, the path will have a blank name. if (destinationPath == PathManager.getInstance().getRecordingPath("")) { return false; } return !StringUtils.isBlank(name); }

Target:
The `==` is a reference comparison, here you are checking if both objects point to the same memory location, and of course, they don't. The right way to compare these paths is using `equals()`. As shown below, for example, if I put "@" as the recording name, which does not match the `PathManager` regex (`[^A-Za-z0-9-_ ]`), the `isNameValid(name)` method returns `true`, again because you're not comparing the object value itself. Moreover, it can cause other bugs like the one shown in the pic, saying that a recording already exists when they don't. ![image](https://user-images.githubusercontent.com/26657147/48665079-4130c580-ea87-11e8-93be-8e58d6dd4227.png)
Source:
public void nextImage() { int size = images.size(); int prevIndex = index; if (size > 0) { if (index == size - 1) { if (infinite) { index = 0; } else { stop(); } } else { index++; } if (prevIndex != index) { currentImage.set(images.get(index)); } } }

Target:
### Option B Change this from setting `currentImage` to the new image, just set the _texture_ to the new texture. If you wanted to get really fancy you could also use a binding, and bind the texture to `images.get(index)` via `ReadOnlyBinding` this would make the texture automatically update without you having to set it.
Source:
public void setRemotePlayersHeldItemMountPointTranslations(@CommandParam("x") float x, @CommandParam("y") float y, @CommandParam("z") float z) { for (EntityRef remotePlayer : entityManager.getEntitiesWith(RemotePersonHeldItemMountPointComponent.class)) { RemotePersonHeldItemMountPointComponent remoteMountPointComponent = remotePlayer.getComponent(RemotePersonHeldItemMountPointComponent.class); if (remoteMountPointComponent != null) { remoteMountPointComponent.translate.set(x, y, z); } } }

Target:
Very minor thing is that you *technically* don't need this check. The `entityManager.getEntitiesWith` ensures that they will have the component and thus you don't need to check if it is null.
Source:
void activateOwnedEntityAsClient(EntityRef usedOwnedEntity) { if (!usedOwnedEntity.exists()) { return; } activateTargetOrOwnedEntity(usedOwnedEntity); }

Target:
This is used in the ManualLabor module, causing a compile error
Source:
HeadlessEnvironment(Name... modules) { super(modules); }

Target:
The removal here of `public` breaks the NameGenerator module - generally the `HeadlessEnvironment` is available for other things to use, an IDE might just not think it is in-use if you lack whatever module or facade in your workspace.
Source:
private String getMouseButtonName() { return button.getName(); }

Target:
This and the other similar change in this class are also both API violations since access is being lessened. Again no apparent usages, but also no apparent need for the change :-)
Source:
private Vector3f getViewPosition(Vector3f out) { ClientComponent clientComponent = getClientEntity().getComponent(ClientComponent.class); if (clientComponent == null) { return out; } LocationComponent location = clientComponent.camera.getComponent(LocationComponent.class); if (location == null) { return getPosition(); } return location.getWorldPosition(out); }

Target:
Another access change API violation, same a little below. If not needed then lets not change it here :-)
Source:
public void enableWireframe() { boolean refreshTaskList = false; EnableFaceCulling faceCullingStateChange = new EnableFaceCulling(); if (getDesiredStateChanges().contains(faceCullingStateChange)) { removeDesiredStateChange(faceCullingStateChange); refreshTaskList = true; } if (!getDesiredStateChanges().contains(wireframeStateChange)) { addDesiredStateChange(wireframeStateChange); refreshTaskList = true; } if (refreshTaskList) { worldRenderer.requestTaskListRefresh(); } }

Target:
Because EnableFaceCulling is added as a desired state in the constructor you can rely on the fact that when you enable wireframe it will be there. So, you don't need the IF statement to check for its presence. Also notice that in this case the IF statement would always evaluate to false, as you are creating a new EnableFaceCulling state change every time.
Source:
public Node removeNode(SimpleUri nodeUri) { Preconditions.checkNotNull(nodeUri, "nodeUri cannot be null!"); Node node = findNode(nodeUri); if (!graph.nodes().contains(node)) { throw new RuntimeException("Node removal failure: there is no '" + nodeUri + "' in the render graph!"); } if (graph.adjacentNodes(node).size() != 0) { throw new RuntimeException("Node removal failure: node '" + nodeUri + "' is still connected to other nodes in the render graph!"); } nodeMap.remove(nodeUri); return nodeMap.remove(nodeUri); }

Target:
Let's remember to remove this check and check instead the result of findNode.
Source:
public void onChunkLoaded(Vector3i chunkCoordinates) { if (renderableRegion.encompasses(chunkCoordinates)) { Chunk chunk = chunkProvider.getChunk(chunkCoordinates); if (chunk == null) { logger.warn("Warning: onChunkLoaded called for a null chunk!"); } else { chunksInProximityOfCamera.add(chunk); Collections.sort(chunksInProximityOfCamera, new ChunkFrontToBackComparator()); } } }

Target:
Is this the most typical case? I would have thought most chunks aren't null and such I'd suggest flipping the if/else block.
Source:
public String get() { SelectedInventorySlotComponent component = localPlayer.getCharacterEntity().getComponent(SelectedInventorySlotComponent.class); for (InventoryCell cell : findAll(InventoryCell.class)) { if (cell.getTargetItem().getComponent(DisplayNameComponent.class) != null && cell.getTargetSlot() == component.slot) return cell.getTargetItem().getComponent(DisplayNameComponent.class).name; } return ""; }

Target:
Always always always brackets around ifs :D
Source:
public SetInputTextureFromFbo(int textureSlot, SimpleUri fboUri, FboTexturesTypes textureType, BaseFBOsManager fboManager, ResourceUrn materialUrn, String shaderParameterName) { this.textureSlot = textureSlot; this.textureType = textureType; this.fbo = fboManager.get(fboUri); this.materialUrn = materialUrn; this.shaderParameterName = shaderParameterName; this.material = getMaterial(materialUrn); propertyChange(null); // Cheeky way to initialise textureId fboManager.subscribe(this); }

Target:
Shouldn't we subscribe to the POST_FBO_REGENERATION event here too?
Source:
public void update() { if (screenGrabber.isTakingScreenshot()) { ScreenshotSize screenshotSize = renderingConfig.getScreenshotSize(); // TODO: Remove dependency on Display fullScale.setDimensions(screenshotSize.getWidth(Display.getWidth()), screenshotSize.getHeight(Display.getHeight())); regenerateFbos(); wasTakingScreenshotLastFrame = true; } else if (wasTakingScreenshotLastFrame) { updateFullScale(); regenerateFbos(); wasTakingScreenshotLastFrame = false; } }

Target:
Hmmm. I'd prefer: ``` if (!isTakingScreenshot) <-- most frequent case if (wasTakingScreenshotLastFrame) <--- must be here unfortunately else // is taking a screenshot ```
Source:
public void update() { if (!screenGrabber.isTakingScreenshot()) { if (wasTakingScreenshotLastFrame) { ScreenshotSize screenshotSize = renderingConfig.getScreenshotSize(); // TODO: Remove dependency on Display fullScale.setDimensions(screenshotSize.getWidth(Display.getWidth()), screenshotSize.getHeight(Display.getHeight())); regenerateFbos(); wasTakingScreenshotLastFrame = true; } } else { updateFullScale(); regenerateFbos(); wasTakingScreenshotLastFrame = false; } }

Target:
Shouldn't this line be swapped with the one in the ELSE block?
Source:
private void addOutputNodes(RenderGraph renderGraph) { Node outputToVRFrameBufferNode = new OutputToHMDNode(context); renderGraph.addNode(outputToVRFrameBufferNode, "outputToVRFrameBufferNode"); Node outputToScreenNode = new OutputToScreenNode(context); renderGraph.addNode(outputToScreenNode, "outputToScreenNode"); Node finalPostProcessingNode = renderGraph.findNode(new SimpleUri("engine:finalPostProcessingNode")); renderGraph.connect(finalPostProcessingNode, outputToVRFrameBufferNode); renderGraph.connect(outputToVRFrameBufferNode, outputToScreenNode); }

Target:
According to the sketchboard.io graph the VR and Screen output nodes are in parallel, both being dependent on finalPostProcessingNode being processed before them.
Source:
public void process() { PerformanceMonitor.startActivity("rendering/copyDepth"); // The way things are set-up right now, we can have FBOs that are not the same size as the display (if scale != 100%). // However, when drawing the final image to the screen, we always want the viewport to match the size of display, // and not that of some FBO. Hence, we are manually setting the viewport via glViewport over here. copyDepthMaterial.setFloat("zNear",activeCamera.getzNear(),true); copyDepthMaterial.setFloat("zFar",activeCamera.getzFar(),true); glViewport(0, 0, Display.getWidth(), Display.getHeight()); renderFullscreenQuad(); PerformanceMonitor.endActivity(); }

Target:
I would have thought checkstyle would inform there should be spaces after the commas here. Did you configure it in your IntelliJ?
Source:
public boolean equals(Object obj) { return (obj instanceof SetFboWriteMask) && fbo == ((SetFboWriteMask) obj).fbo && renderToColorBuffer == ((SetFboWriteMask) obj).renderToColorBuffer && renderToDepthBuffer == ((SetFboWriteMask) obj).renderToDepthBuffer && renderToLightBuffer == ((SetFboWriteMask) obj).renderToLightBuffer; }

Target:
I'm wondering about this change. It closes the door to two FBOs having the same id GPU-side. Which is probably an unlikely if not impossible case within Terasology. But makes me wonder.
Source:
public EntityRef create(String prefabName, Vector3f position) { if (prefabName != null && !prefabName.isEmpty()) { Prefab prefab = entityManager.getPrefabManager().getPrefab(prefabName); return create(prefab, position); } return create(); }

Target:
Above in line 103 you check for the prefab to not being `null`, but here the check is missing.
Source:
private void destroy(EntityRef ref) { // Don't allow the destruction of unloaded entities. long entityId = ref.getId(); entityStore.remove(entityId); entityManager.remove(entityId); if (ref instanceof PojoEntityRef) { ((PojoEntityRef) ref).invalidate(); } componentStore.remove(entityId); }

Target:
Can we get around this `instanceof` somehow? Should it be generally possible to invalidate EntityRef?
Source:
private static boolean posixSystemIs64() throws IOException, InterruptedException { Process unameProc = new ProcessBuilder("uname", "-m").start(); BufferedReader unameStdout = new BufferedReader(new InputStreamReader(unameProc.getInputStream())); unameProc.waitFor(); boolean result = unameStdout.readLine().endsWith("64"); unameStdout.close(); return result; }

Target:
you could use the try-with-ressources statement here.
Source:
public boolean equals(Object obj) { return (obj instanceof DisableDepthWriting) && this.enabled == ((DisableDepthWriting) obj).enabled; }

Target:
This is an example of changes where you kind of go off track. I appreciate when you see something you don't like you want to change it right away. But from a structuring-the-PR point of view you should keep a commit focused on a particular goal and note down unnecessary changes for a further commit.
Source:
public void process() { if (material == null) { shaderManager.disableShader(); } else { material.enable(); } }

Target:
Hmmm. The process() method should be as lean as possible. This calls for a DisableMaterial() class to be used as default instance, in which the process method is just `shaderManager.disableShader();`
Source:
public void update() { FBO ssaoFbo = displayResolutionDependentFBOs.get(SSAO_FBO); outputFboWidth = ssaoFbo.width(); outputFboHeight = ssaoFbo.height(); }

Target:
We discussed this already, but please remind me: update() is executed, for example, when the user resize the window. Why not to avoid any form of memory allocation in those circumstances, even if it's admittedly small in this case?
Source:
public CopyImageToScreenNode(Context context) { WorldRenderer worldRenderer = context.get(WorldRenderer.class); displayResolutionDependentFBOs = context.get(DisplayResolutionDependentFBOs.class); requiresCondition(() -> worldRenderer.getCurrentRenderStage() == MONO || worldRenderer.getCurrentRenderStage() == LEFT_EYE); addDesiredStateChange(new BindFBO(DEFAULT_FBO, displayResolutionDependentFBOs)); update(); // Cheeky way to initialise sceneFinalFbo displayResolutionDependentFBOs.subscribe(this); addDesiredStateChange(new EnableMaterial(DEFAULT_TEXTURED_MATERIAL)); }

Target:
Can this line be placed just under the worldRenderer variable assignment?
Source:
public CopyImageToScreenNode(Context context) { displayResolutionDependentFBOs = context.get(DisplayResolutionDependentFBOs.class); WorldRenderer worldRenderer = context.get(WorldRenderer.class); requiresCondition(() -> worldRenderer.getCurrentRenderStage() == MONO || worldRenderer.getCurrentRenderStage() == LEFT_EYE); addDesiredStateChange(new BindFBO(DEFAULT_FBO, displayResolutionDependentFBOs)); update(); // Cheeky way to initialise sceneFinalFbo displayResolutionDependentFBOs.subscribe(this); addDesiredStateChange(new EnableMaterial(DEFAULT_TEXTURED_MATERIAL)); }

Target:
Let's move this line to just before the first addDesiredStateChange line.
Source:
public void initialise() { requiresCondition(() -> worldRenderer.getCurrentRenderStage() == MONO || worldRenderer.getCurrentRenderStage() == LEFT_EYE); addDesiredStateChange(new BindFBO(DEFAULT_FRAME_BUFFER_URN, displayResolutionDependentFBOs)); update(); addDesiredStateChange(new EnableMaterial("engine:prog.defaultTextured")); displayResolutionDependentFBOs.subscribe(this); }

Target:
Move up, please.
Source:
public void initialise() { playerCamera = worldRenderer.getActiveCamera(); addDesiredStateChange(new EnableMaterial(LIGHT_GEOMETRY_MATERIAL.toString())); lightGeometryMaterial = getMaterial(LIGHT_GEOMETRY_MATERIAL); addDesiredStateChange(new DisableDepthTest()); addDesiredStateChange(new EnableBlending()); addDesiredStateChange(new SetBlendFunction(GL_ONE, GL_ONE_MINUS_SRC_COLOR)); addDesiredStateChange(new BindFBO(READONLY_GBUFFER, displayResolutionDependentFBOs)); update(); initMainDirectionalLight(); displayResolutionDependentFBOs.subscribe(this); }

Target:
Move up please.
Source:
public void initialise() { wireframeStateChange = new SetWireframe(true); renderingDebugConfig = config.getRendering().getDebug(); new WireframeTrigger(renderingDebugConfig, this); playerCamera = worldRenderer.getActiveCamera(); addDesiredStateChange(new LookThrough(playerCamera)); addDesiredStateChange(new SetViewportToSizeOf(READONLY_GBUFFER, displayResolutionDependentFBOs)); addDesiredStateChange(new BindFBO(READONLY_GBUFFER, displayResolutionDependentFBOs)); update(); displayResolutionDependentFBOs.subscribe(this); }

Target:
Let's move this up please.
Source:
public void initialise() { playerCamera = worldRenderer.getActiveCamera(); addDesiredStateChange(new LookThrough(playerCamera)); refractiveReflectiveFbo = requiresFBO(new FBOConfig(REFRACTIVE_REFLECTIVE, FULL_SCALE, FBO.Type.HDR).useNormalBuffer(), displayResolutionDependentFBOs); addDesiredStateChange(new BindFBO(REFRACTIVE_REFLECTIVE, displayResolutionDependentFBOs)); readOnlyGBufferFbo = displayResolutionDependentFBOs.get(READONLY_GBUFFER); addDesiredStateChange(new EnableMaterial(CHUNK_SHADER.toString())); chunkShader = getMaterial(CHUNK_SHADER); displayResolutionDependentFBOs.subscribe(this); }

Target:
Do we need this line here? readOnlyGBufferFbo seems to be used only in update(), where it is refetched.
Source:
public boolean isBound(Input newInput) { return data.containsValue(newInput) && newInput != null; }

Target:
This is a minor nitpick, but a "newInput != null; && data.containsValue(newInput)" will be much more efficient when newInput is null, because of the most programming languages handle AND (using short circuit logic).
Source:
public void process() { PerformanceMonitor.startActivity("rendering/backdrop"); FBO sceneOpaqueFbo = displayResolutionDependentFBOs.get(new ResourceUrn("engine:sceneOpaque")); sceneOpaqueFbo.bind(); // TODO: remove when we can bind this via a StateChange sceneOpaqueFbo.setRenderBufferMask(true, false, false); glCallList(skySphere); // Draws the skysphere sceneOpaqueFbo.setRenderBufferMask(true, true, true); // TODO: handle these via new StateChange to be created PerformanceMonitor.endActivity(); }

Target:
Same as above, let's not instantiate the FBO within process and let's try to use BindFBO in initialize() instead of this bind() line.
Source:
public FBOConfig getFboConfig(ResourceUrn fboName) { FBOConfig fboConfig = fboConfigs.get(fboName); if (fboConfigs == null) { logger.error("Failed to retrieve FBOConfig '" + fboName + "'!"); } return fboConfig; }

Target:
`fboConfig` I presume - without the s
Source:
public void process() { PerformanceMonitor.startActivity("rendering/applyDeferredLighting"); sceneOpaquePingPongFbo.bind(); // TODO: remove and replace with a state change sceneOpaquePingPongFbo.setRenderBufferMask(true, true, true); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // TODO: this is necessary - but why? Verify in the shader. renderFullscreenQuad(); displayResolutionDependentFBOs.swapReadWriteBuffers(); // Doesn't exactly help with a lean process() function.. sceneOpaqueFbo.attachDepthBufferTo(refractiveReflectiveFbo); PerformanceMonitor.endActivity(); }

Target:
Actually, I just wrote issue #2828 about it.
Source:
private String getMaterialName() { return materialName; }

Target:
Why this change?
Source:
private FBO getFbo() { if (defaultDynamicFBO == null) return frameBuffersManager.get(fboName); return defaultDynamicFBO.getFbo(); }

Target:
A ternary statement is fine here.
Source:
ViewDistance(String displayName, int index, Vector3i chunkDistance) { this.displayName = String.format(displayName + " (%1$dx%2$dx%3$d)", chunkDistance.getX(), chunkDistance.getY(), chunkDistance.getZ()); this.index = index; this.chunkDistance = chunkDistance; }

Target:
1. Instead of assigning a different value to `displayName` in the constructor, please return this formatted string in the `toString()` method. This is because we might want to use the original `displayName` for purposes such as internal log output. 2. Since you're using `String.format()`, `displayName` should be made part of the format string for consistency - i.e. ```java String.format("%s (%1$dx%2$dx%3$d)", displayName /* , ... */); ```
Source:
public void setButtonData(UIInputBind bindButton) { this.bindButton = bindButton; String messageText = "Key " + bindButton.getNewInput().getDisplayName() + " has already been assigned an action. Press ok to change anyway."; find("title", UILabel.class).setText("Rebinding"); find("message", UILabel.class).setText(messageText); }

Target:
Since the label text is static, you can set it in `confirmChangePopup.ui` instead. (`"text": "Rebinding` instead of `"text": "Title"`)
Source:
public void refresh() { logger.info("Refresh"); ServerInfo i = visibleList.getSelection(); visibleList.setSelection(null); extInfo.clear(); visibleList.setSelection(i); }

Target:
I'd either remove this message or expand on it a bit (i.e. "Refreshing info for server X").
Source:
public void submitFrame() { if (vrCompositor == null) { return; } if (vrCompositor.Submit == null) { return; } for (int nEye = 0; nEye < 2; nEye++) { vrCompositor.Submit.apply( nEye, texType[nEye], null, JOpenVRLibrary.EVRSubmitFlags.EVRSubmitFlags_Submit_Default); } if (vrCompositor.PostPresentHandoff != null) { vrCompositor.PostPresentHandoff.apply(); } }

Target:
About the previous IF blocks: why these checks? By the time submitFrame() is called, can't we be reasonably certain we have everything needed? This also applies to the PostPresentHandOff IF block below.
Source:
private void preRenderSetupSimpleBlendMaterials() { dynamicFBOsManager.get(DefaultDynamicFBOs.READ_ONLY_GBUFFER.getName()).setRenderBufferMask(true, true, true); GL11.glEnable(GL_BLEND); GL11.glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // (*) GL11.glDepthMask(false); // (*) In this context SRC is Foreground. This effectively says: // Resulting RGB = ForegroundRGB * ForegroundAlpha + BackgroundRGB * (1 - ForegroundAlpha) // Which might still look complicated, but it's actually the most typical alpha-driven composite. // A neat tool to play with this settings can be found here: http://www.andersriggelsen.dk/glblendfunc.php }

Target:
This should become: ` READ_ONLY_GBUFFER.setRenderBufferMask(true, true, true);`
Source:
public SetFacesToCull(int mode) { if (mode != GL_BACK && mode != GL_FRONT && mode != GL_FRONT_AND_BACK) { throw new IllegalArgumentException("Mode must be GL_BACK, GL_FRONT or GL_FRONT_AND_BACK."); } this.mode = mode; }

Target:
What happened here? Why did you revert to individual checks instead of checking against the map? In any case you should reverse the handling of this IF block. The current true case is the least likely to happen.
Source:
public void process() { PerformanceMonitor.startActivity("rendering/prePostComposite"); sceneReflectiveRefractive = displayResolutionDependentFBOs.get(REFLECTIVE_REFRACTIVE); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // TODO: verify this is necessary renderFullscreenQuad(); bindDisplay(); // TODO: verify this is necessary setViewportToSizeOf(READ_ONLY_GBUFFER); // TODO: verify this is necessary displayResolutionDependentFBOs.swapReadWriteBuffers(); READ_ONLY_GBUFFER.attachDepthBufferTo(sceneReflectiveRefractive); // TODO: verify why we can't move the buffer attachment to before the swap by using WRITE_ONLY_GBUFFER instead. // TODO: See right-side streaks in https://cloud.githubusercontent.com/assets/136392/17794231/456f542a-65b6-11e6-83bb-f2cc3f10ee66.png PerformanceMonitor.endActivity(); }

Target:
Can we move this line to just above READ_ONLY_GBUFFER.attachDepthBufferTo?
Source:
public void process() { PerformanceMonitor.startActivity("rendering/outline"); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // TODO: verify this is necessary renderFullscreenQuad(); bindDisplay(); // TODO: verify this is necessary PerformanceMonitor.endActivity(); }

Target:
I'm pretty sure we can remove this now. If necessary the default state change task will do it. Just verify enabling/disabling the outline still works ok.
Source:
public BindFBO(String fboName) { this.fboName = fboName; if (fboName.equals(DEFAULT_FRAME_BUFFER_NAME)) { fboId = DEFAULT_FRAME_BUFFER_ID; } else { fboId = frameBuffersManager.getFBO(fboName).fboId; } }

Target:
I think the most likely case is that fboName is not the default frame buffer. But it's a very minor issue, so let's leave it as it is.
Source:
public SetViewportSizeOf(String fboName) { this.fboName = fboName; if (!fboName.equals(DEFAULT_FBO)) { fbo = frameBuffersManager.getFBO(fboName); } }

Target:
I'm not sure about this IF block. Why do we need it? Can we just store only the fboName and then get the fbo itself only when we need it?
Source:
public BindFBO(String fboName) { this.fboName = fboName; if (!fboName.equals(DEFAULT_FRAME_BUFFER_NAME)) { fboId = frameBuffersManager.getFBO(fboName).fboId; } else { fboId = DEFAULT_FRAME_BUFFER_ID; } }

Target:
That been said, I just reviewed the rest of this PR and apart from these issues I couldn't find any other problem. So, we are almost there with this one too. :smiley:
Source:
public String addNode(Node node, String suggestedId) { nodes.add(node); return null; // TODO: for instance if "blur" present make id "blur1" and return it }

Target:
I'd return suggestedId for the time being, but if you have reasons to keep it this way for the time being I'd be ok with it.
Source:
public void process() { PerformanceMonitor.startActivity("rendering/ambientocclusionpasses"); if (renderingConfig.isSsao()) { // TODO: consider moving these into initialise without breaking existing implementation sceneOpaque = frameBuffersManager.getFBO("sceneOpaque"); ssaoBlurredFBO = frameBuffersManager.getFBO("ssaoBlurred"); ssaoFBO = frameBuffersManager.getFBO("ssao"); generateSSAO(); generateBlurredSSAO(); } PerformanceMonitor.endActivity(); }

Target:
I'd say that PerformanceMonitor statements should be within the IF block, so that if something is disabled it doesn't get monitored.
Source:
public void process() { PerformanceMonitor.startActivity("rendering/chunksrefractivereflective"); boolean isHeadUnderWater = worldRenderer.isHeadUnderWater(); preRenderSetupSceneReflectiveRefractive(isHeadUnderWater); worldRenderer.renderChunks(renderQueues.chunksAlphaBlend, ChunkMesh.RenderPhase.REFRACTIVE, playerCamera, WorldRendererImpl.ChunkRenderMode.DEFAULT); postRenderCleanupSceneReflectiveRefractive(isHeadUnderWater); PerformanceMonitor.endActivity(); }

Target:
Let's make this boolean a private variable please.
Source:
public void setTime(Time t) { time = t; }

Target:
Might this be a valid spot to use package private level access instead of public? Since the test is in the same package just under engine-tests? Can't entirely recall if it works that way.
Source:
public void test1DelayedAction() { ArbritaryDelayActionComponent a1 = new ArbritaryDelayActionComponent(); a1.value = 3; vals = new ArrayList<Integer>(Arrays.asList(3)); long currentTime = time.getGameTimeInMs(); delayedActionSystem.addDelayedAction(createFakeEntityWith(a1), "Blah Blah", ((currentTime + 1000) - currentTime)); nextFakeEntityId++; }

Target:
I don't think you need a line break here. 120ish chars is OK.
Source:
public float getInterpolation(float v) { return (float) Math.pow(v, factor) * (end - start) + start; }

Target:
Linear acceleration is always quadratic in terms of position (i.e. the interpolated value). I suggest using a multiplicate factor instead. This would also avoid the comparatively costly call to `Math.pow()`.
Source:
void ensureCameraEntityCreated() { if (!localPlayer.getCameraEntity().exists()) { ClientComponent clientComponent = localPlayer.getClientEntity().getComponent(ClientComponent.class); EntityBuilder builder = entityManager.newBuilder("engine:camera"); builder.setPersistent(false); clientComponent.camera = builder.build(); localPlayer.getClientEntity().saveComponent(clientComponent); mountCamera(); } }

Target:
Is this method intentionally package-private?
Source:
public Set<Name> suggest(EntityRef sender, Object... resolvedParameters) { Collection<ConsoleCommand> commands = console.getCommands(); Set<Name> suggestions = Sets.newHashSetWithExpectedSize(commands.size()); suggestions.addAll(commands.stream().map(ConsoleCommand::getName).collect(Collectors.toList())); return suggestions; }

Target:
I find the original version easier to read in this case.
Source:
private void destroyClientTempEntities(AbstractMoveItemRequest removedRequest) { removedRequest.getClientSideTempEntities().stream().filter(tempEntity -> tempEntity.exists()).forEach(EntityRef::destroy); }

Target:
I find the original version easier to read in this case.
Source:
public static synchronized List<SingleThreadMonitor> getThreadMonitors(List<SingleThreadMonitor> output, boolean aliveThreadsOnly) { Preconditions.checkNotNull(output, "The parameter 'output' must not be null"); output.clear(); output.addAll(THREAD_INFO_BY_ID.values().stream().filter(entry -> !aliveThreadsOnly || entry.isAlive()).collect(Collectors.toList())); return output; }

Target:
I find the original version easier to read in this case.
Source:
public void deserializeOnto(Object target, Map<FieldMetadata<?, ?>, PersistedData> values, DeserializationContext context, DeserializeFieldCheck check) { values.entrySet().stream().filter(field -> check.shouldDeserialize(classMetadata, field.getKey())).forEach(field -> { deserializeOnto(target, field.getKey(), field.getValue(), context); }); }

Target:
I'd go with the original version, because I find it easier to read and it's called very often.
Source:
public PersistedData serializeCollection(Collection<T> value, SerializationContext context) { List<PersistedData> rawList = Lists.newArrayList(); rawList.addAll(value.stream().map(item -> serialize(item, context)).collect(Collectors.toList())); return context.create(rawList); }

Target:
I'd go with the original version, because I find it easier to read and it's called very often.
Source:
public static void initialize(Path logFileFolder) { String timestamp = TIMESTAMP_FORMAT.format(new Date()); loggingPath = logFileFolder.resolve(timestamp).normalize(); String pathString = loggingPath.toString(); System.setProperty(LOG_FILE_FOLDER, pathString); try { deleteLogFiles(logFileFolder, ((int) Duration.ofDays(5).getSeconds())); } catch (IOException e) { e.printStackTrace(); } // Unfortunately, setting context-based variables works only after initialization // has completed. Manual initialization will work but is overriden by the first // (static) access to slf4j's StaticLoggerBinder. // This default initialization will attempt to create a folder "logFileFolder_IS_UNDEFINED" though. // TODO: file a report at logback/slf4j // LoggerContext context = new LoggerContext(); // context.setName(CoreConstants.DEFAULT_CONTEXT_NAME); // context.putProperty("targetFolder", pathString); // JoranConfigurator configurator = new JoranConfigurator(); // configurator.setContext(context); // // try { // ContextInitializer ci = new ContextInitializer(context); // ci.autoConfig(); // } catch (JoranException e) { // e.printStackTrace(); // } }

Target:
Maybe `deleteLogFiles` could take a `long` parameter? This could avoid the need to downcast without reason.
Source:
public static <T, U extends T> U put(Class<T> type, U object) { if (context == null) return null; context.put(type, object); return object; }

Target:
Brackets please - part of our code convention to always use them :-)
Source:
public Prefab getPrefab(String name) { if (!name.isEmpty()) { Preconditions.checkArgument(!Strings.isNullOrEmpty(name)); return assetManager.getAsset(name, Prefab.class).orElse(null); } return null; }

Target:
Uh, you would put this inside an `if(!name.isEmpty())` block? I would have just put `Preconditions.checkNotNull` on the outside, since name should not be null.
Source:
public boolean exists(String name) { Preconditions.checkArgument(!Strings.isNullOrEmpty(name)); return assetManager.getAsset(name, Prefab.class).isPresent(); }

Target:
I would argue it is ok if name is empty, so the contract can be loosened a little.
Source:
public ScreenshotFormat get() { switch (config.getScreenshotFormat()) { case PNG: return PNG; case JPEG: return JPEG; default: return PNG; } }

Target:
This seems a bit odd.... why not just check return the format unless null, and return the default value in that case?
Source:
public AssetUri getPrefabURI() { if (exists()) { EntityInfoComponent info = getComponent(EntityInfoComponent.class); if (info != null && !info.parentPrefab.exists()) { return new AssetUri(AssetType.PREFAB, info.parentPrefab.getName()); } } return null; }

Target:
This doesn't look right, should the `!` be there?
Source:
public UICommandEntry() { subscribe(new CursorUpdateEventListener() { @Override public void onCursorUpdated(int oldPosition, int newPosition) { if(tabCompletionEngine == null) return; tabCompletionEngine.reset(); } }); }

Target:
Need some braces here. :)
Source:
public UIScreenLayer pushScreen(UIElement element) { if (element != null && element.getRootWidget() instanceof CoreScreenLayer) { CoreScreenLayer result = (CoreScreenLayer) element.getRootWidget(); if (!result.equals(screens.peek())) { result.setId(element.getURI().toNormalisedSimpleString()); pushScreen(result, element.getURI()); } return result; } return null; }

Target:
Possibly should check the entire screen stack.
Source:
public void onChangeVelocity(ChangeVelocityEvent event, EntityRef entity) { if (event.getAngularVelocity().length() > 0) { physics.getRigidBody(entity).setAngularVelocity(event.getAngularVelocity()); } if (event.getLinearVelocity().length() > 0) { physics.getRigidBody(entity).setLinearVelocity(event.getLinearVelocity()); } }

Target:
What If I want to set velocity to zero?
Source:
public static int ceilPowerOfTwo(int val) { if(val == Integer.MIN_VALUE) return 0; int result = val - 1; result = (result >> 1) | result; result = (result >> 2) | result; result = (result >> 4) | result; result = (result >> 8) | result; result = (result >> 16) | result; result++; return result; }

Target:
I have to admit that I never considered negative numbers at all. Both min and max integer will suffer from overflow though, so I'm not sure it matters.
Source:
public void cancelDelayedAction(CancelDelayedActionEvent event, EntityRef entity) { DelayedActionComponent delayedComponent = entity.getComponent(DelayedActionComponent.class); delayedOperationsSortedByTime.remove(delayedComponent.getWorldTime(), new DelayedOperation(entity, delayedComponent.getActionId())); entity.removeComponent(DelayedActionComponent.class); }

Target:
I recommend moving this line to a BeforeDeactivatedComponent event handler (or if you already have one, it is unnecessary).
Source:
public void update(float delta) { if (speed > 0) { speed -= delta; return; } speed = 0.1f; for (EntityRef minion : entityManager.getEntitiesWith(BehaviorComponent.class)) { addEntity(minion, minion.getComponent(BehaviorComponent.class)); } for (Map.Entry<BehaviorTree, List<Interpreter>> entry : interpreters.entrySet()) { for (Interpreter interpreter : entry.getValue()) { interpreter.tick(0.1f); } } }

Target:
I suspect you should use the lifecycle events here (OnAddedComponent), rather than scanning all entities with BehaviourComponents each frame?
Source:
public void getPosition(Vector3f output) { LocationComponent location = entity.getComponent(LocationComponent.class); if (location == null) { output.x = 0; output.y = 0; output.z = 0; } else { location.getWorldPosition(output); } }

Target:
Would recommend having this method return the output Vector3f, makes it easier to use.
Source:
public void onError(Throwable th) { LOGGER.info("---- onError\n" + th.toString()); lastPong = null; warnDisconnect(); executorService.shutdownNow(); }

Target:
起動時にエラーが発生して onOpen が実行される前に onError が呼び出されたりしないか(しても大丈夫かどうか)気になりました。
Source:
public Map<String, Map<String, Integer>> dumpHashTableStats() { Map<String, Map<String, Integer>> ret = new HashMap<String, Map<String, Integer>>(); if (leftHashTable != null) { ret.put(leftHashTable.name, leftHashTable.dumpStats()); } if (rightHashTable != null) { ret.put(rightHashTable.name, rightHashTable.dumpStats()); } return ret; }

Target:
Can you just use the diamond operator here? ``` Map<String, Map<String, Integer>> ret = new HashMap<>(); ```
Source:
public Map<String, Map<String, Integer>> dumpHashTableStats() { Map<String, Map<String, Integer>> ret = new HashMap<String, Map<String, Integer>>(); if (groupStates != null) { ret.put(groupStates.name, groupStates.dumpStats()); } return ret; }

Target:
again I think you can use the diamond operator
Source:
public Map<String, Map<String, Integer>> dumpHashTableStats(final Operator op) { Map<String, Map<String, Integer>> ret = new HashMap<String, Map<String, Integer>>(); for (Operator o : op.getChildren()) { ret.putAll(dumpHashTableStats(o)); } ret.putAll(op.dumpHashTableStats()); return ret; }

Target:
again I think you can use the diamond operator
Source:
public Map<String, Map<String, Integer>> dumpHashTableStats() { Map<String, Map<String, Integer>> ret = new HashMap<String, Map<String, Integer>>(); for (LocalFragment t : fragments) { ret.putAll(t.dumpHashTableStats(t.getRootOp())); } return ret; }

Target:
again I think you can use the diamond operator
Source:
public boolean isValid() { try { return accessMethod.getConnection().isValid(1); } catch (SQLException e) { LOGGER.warn("Error checking connection validity", e); return false; } }

Target:
Can you check if this is called anywhere?
Source:
public PythonFunctionRegistrar getPythonFunctionRegistrar() throws DbException { PythonFunctionRegistrar pyFuncRegistrar = null; try { if (execEnvVars.get(MyriaConstants.EXEC_ENV_VAR_TEST_MODE) == null) { if (getLocalSubQuery() instanceof WorkerSubQuery) { pyFuncRegistrar = ((WorkerSubQuery) getLocalSubQuery()).getWorker().getPythonFunctionRegistrar(); } } } catch (Exception e) { LOGGER.debug("exception getting pyFuncRegistrar"); pyFuncRegistrar = null; } return pyFuncRegistrar; }

Target:
Here, `pyFuncRegistrar` will already be null anyway. Also, wouldn't you want to throw an exception at this point? I noticed that at several points in your code, you call this function to get the registrar, but you wouldn't ever want to return a null value right?
Source:
public static int getBatchSize(Type type) { int batchSize = 1000 * 10; if (type == Type.BLOB_TYPE) { batchSize = 1; } return batchSize; }

Target:
Similar to above
Source:
public BooleanColumnBuilder() { data = new BitSet(); numBits = 0; Schema schema = new Schema(Arrays.asList(Type.BOOLEAN_TYPE)); int batchSize = TupleUtils.getBatchSize(schema); capacity = batchSize; }

Target:
Call the function with a single `Type` as input instead.
Source:
public static void main(final String[] args) throws Exception { LauncherStatus run = run(args); LOGGER.info("Exit with status " + run); }

Target:
`run` -> `status`
Source:
public IdentityHashPartitionFunction( @JsonProperty(value = "index", required = true) final Integer index) { super(null); this.index = java.util.Objects.requireNonNull(index, "missing property index"); Preconditions.checkArgument(this.index >= 0, "IdentityHash field index cannot take negative value %s", this.index); }

Target:
Why not import `Objects`?
Source:
public InputStream getInputStream() throws IOException { URI parsedUri = URI.create(uri); return parsedUri.getScheme().equals("http") || parsedUri.getScheme().equals("https") ? parsedUri.toURL().openConnection().getInputStream() : getHadoopFileSystemInputStream(parsedUri); }

Target:
I tend to avoid trigraphs unless they're absolutely necessary, but that's up to you. However, please `()` around the condition of `||` here... the code is correct but you have to know non-obvious parts of [the precedence chart (13 vs 14)](http://introcs.cs.princeton.edu/java/11precedence/). LGTM!
Source:
public ConstantExpression(final int value) { valueType = Type.INT_TYPE; this.value = String.valueOf(value); }

Target:
use the constructor-delegate form instead. More concise and if we ever need to put in checks we only need to put them one place. e.g., `this(Type.INT_TYPE, String.valueOf(value))`
Source:
public static synchronized ProfilingLogger getLogger(final ImmutableMap<String, Object> execEnvVars) { if (instance == null) { try { instance = new ProfilingLogger(execEnvVars); } catch (DbException e) { if (LOGGER.isErrorEnabled()) { LOGGER.error("Failed to initialize profiling logger:", e); } } } Preconditions.checkArgument(instance.connectionInfo == (ConnectionInfo) execEnvVars .get(MyriaConstants.EXEC_ENV_VAR_DATABASE_CONN_INFO), "Connection info should not change."); return instance; }

Target:
I am trying to get rid of these checks where they don't save a large amount of work. No need to check whether logging is enabled here, there's no work inside the function.
Source:
public void testNonStaticInnerClasses() { boolean successful = false; try { ReflectData.get().getSchema(Definition.class); } catch (AvroTypeException ex) { if (ex.getMessage().contains("must be a static inner class")) { successful = true; } } assertTrue(successful); }

Target:
I'd prefer to use the annotation: `@Test(expected = AvroTypeException.class)` What do you think?
Source:
public void testStaticInnerClasses() { try { ReflectData.get().getSchema(Meta.class); } catch (AvroTypeException ex) { fail("Should have no exception"); } }

Target:
Same here, I'd love to use the annotation, and remove the fail("") part. If it throws an exception, it will fail anyway
Source:
public FastReaderBuilder getFastReaderBuilder() { if (fastReaderBuilder == null) { FastReaderBuilder localFastReader = new FastReaderBuilder(this); this.fastReaderBuilder = localFastReader; return localFastReader; } else { return this.fastReaderBuilder; } }

Target:
Definitely a nit, but why introduce the local variable here?
Source:
protected boolean isArray(Object datum) { if (datum == null) return false; Class c = datum.getClass(); return (datum instanceof Collection) || (c.isArray() && !(c.getComponentType() == Byte.TYPE)) || isNonStringMap(datum); }

Target:
I would suggest `c.getComponentType() != Byte.TYPE` instead of `!(c.getComponentType() == Byte.TYPE)`
Source:
public SchemaCompatibilityResult mergedWith(SchemaCompatibilityResult toMerge) { List<Incompatibility> mergedIncompatibilities = new ArrayList<Incompatibility>(mIncompatibilities); mergedIncompatibilities.addAll(toMerge.getIncompatibilities()); SchemaCompatibilityType compatibilityType = mCompatibilityType == SchemaCompatibilityType.COMPATIBLE && toMerge.mCompatibilityType == SchemaCompatibilityType.COMPATIBLE ? SchemaCompatibilityType.COMPATIBLE : SchemaCompatibilityType.INCOMPATIBLE; return new SchemaCompatibilityResult(compatibilityType, mergedIncompatibilities); }

Target:
What happens in case of `RECURSION_IN_PROGRESS`? I'm not sure we need `&& toMerge.mCompatibilityType == SchemaCompatibilityType.COMPATIBLE`, isn't this simpler a bit: `SchemaCompatibilityType compatibilityType = mCompatibilityType == SchemaCompatibilityType.COMPATIBLE ? toMerge.getCompatibility() : SchemaCompatibilityType.INCOMPATIBLE; `
Source:
private static void printStream(InputStream in) throws Exception { byte[] buffer = new byte[1024]; try { for (int i = in.read(buffer); i != -1; i = in.read(buffer)) System.err.write(buffer, 0, i); } finally { in.close(); } }

Target:
Why are we closing in within this method instead of having the caller do it?
Source:
public DataFileWriter<D> appendTo(File file) throws IOException { SeekableInput input = new SeekableFileInput(file); OutputStream output = new SyncableFileOutputStream(file, true); try { return appendTo(input, output); } finally { input.close(); } }

Target:
I think this line should be inside the try block as well to guarantee that input is always closed. Or, alternatively, it may be before the first line if order does not matter.