auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected Response beforeInvoke() throws Exception { <START> if (0 <= commandTopologyId && commandTopologyId < handler.stateTransferManager.getFirstTopologyAsMember()) { <END> if (handler.isTraceEnabled()) { handler.getLog().tracef("Ignoring command sent before the local node was a member " + "(command topology id is %d)", commandTopologyId); } return CacheNotFoundResponse.INSTANCE; } topologyMode.await(handler.getStateTransferLock(), waitTopology()); return super.beforeInvoke(); }</code><technical_language>invocation handler check isCommandSentBeforeFirstTopology() executing command</technical_language>

Target:
protected Response beforeInvoke() throws Exception { switch (topologyMode) { case WAIT_TOPOLOGY: handler.getStateTransferLock().waitForTopology(waitTopology(), 1, TimeUnit.DAYS); break; case WAIT_TX_DATA: handler.getStateTransferLock().waitForTransactionData(waitTopology(), 1, TimeUnit.DAYS); break; default: break; } if (handler.isCommandSentBeforeFirstTopology(commandTopologyId)) { return CacheNotFoundResponse.INSTANCE; } return super.beforeInvoke(); }
Source:
<code>public CommandResult<CanvasViolation> move( final Element element, final double tx, final double ty ) { final UpdateElementPositionCommand c = canvasCommandFactory .updatePosition( ( Node<View<?>, Edge> ) element, tx, ty ); CommandResult<CanvasViolation> result = canvasCommandManager.allow( canvasHandler, c ); if ( !CommandUtils.isError( result ) ) { result = canvasCommandManager.execute( canvasHandler, c ); } if ( CommandUtils.isError( result ) ) { <START> LOGGER.log( Level.SEVERE, "Update element's position comman failed [result=" + result + "]" ); <END> } return result; }</code><technical_language>Typo "...position comman**d** failed..."</technical_language>

Target:
public CommandResult<CanvasViolation> move( final Element element, final double tx, final double ty ) { final UpdateElementPositionCommand c = canvasCommandFactory .updatePosition( ( Node<View<?>, Edge> ) element, tx, ty ); CommandResult<CanvasViolation> result = canvasCommandManager.allow( canvasHandler, c ); if ( !CommandUtils.isError( result ) ) { result = canvasCommandManager.execute( canvasHandler, c ); } if ( CommandUtils.isError( result ) ) { LOGGER.log( Level.SEVERE, "Update element's position command failed [result=" + result + "]" ); } return result; }
Source:
<code>private void loadMetadataResources(JobModel jobModel) { CoordinatorStreamStore coordinatorStreamStore = null; try { coordinatorStreamStore = createCoordinatorStreamStore(); coordinatorStreamStore.init(); MetadataResourceUtil metadataResourceUtil = new MetadataResourceUtil(jobModel, metrics.getMetricsRegistry()); metadataResourceUtil.createResources(); CoordinatorStreamValueSerde jsonSerde = new CoordinatorStreamValueSerde(SetConfig.TYPE); NamespaceAwareCoordinatorStreamStore configStore = new NamespaceAwareCoordinatorStreamStore(coordinatorStreamStore, SetConfig.TYPE); for (Map.Entry<String, String> entry : config.entrySet()) { byte[] serializedValue = jsonSerde.toBytes(entry.getValue()); configStore.put(entry.getKey(), serializedValue); } StartpointManager startpointManager = createStartpointManager(coordinatorStreamStore); startpointManager.start(); try { startpointManager.fanOut(jobModel.getTaskToSystemStreamPartitions()); } catch (IOException ex) { <START> throw new SamzaException(String.format("Error calling fan out from StartpointManager."), ex); <END> } finally { startpointManager.stop(); } } finally { if (coordinatorStreamStore != null) { LOG.info("Stopping the coordinator stream metadata store."); coordinatorStreamStore.close(); } } }</code><technical_language>This is inconsistent ClusterBasedJobCoordinator. Here, catch IOException, in other case, don't. please consistent</technical_language>

Target:
void loadMetadataResources(JobModel jobModel) { CoordinatorStreamStore coordinatorStreamStore = null; try { coordinatorStreamStore = createCoordinatorStreamStore(); coordinatorStreamStore.init(); MetadataResourceUtil metadataResourceUtil = createMetadataResourceUtil(jobModel); metadataResourceUtil.createResources(); CoordinatorStreamValueSerde jsonSerde = new CoordinatorStreamValueSerde(SetConfig.TYPE); NamespaceAwareCoordinatorStreamStore configStore = new NamespaceAwareCoordinatorStreamStore(coordinatorStreamStore, SetConfig.TYPE); for (Map.Entry<String, String> entry : config.entrySet()) { byte[] serializedValue = jsonSerde.toBytes(entry.getValue()); configStore.put(entry.getKey(), serializedValue); } StartpointManager startpointManager = createStartpointManager(coordinatorStreamStore); startpointManager.start(); try { startpointManager.fanOut(JobModelUtil.getTaskToSystemStreamPartitions(jobModel)); } finally { startpointManager.stop(); } } catch (IOException ex) { throw new SamzaException(String.format("IO exception while loading metadata resources."), ex); } finally { if (coordinatorStreamStore != null) { LOG.info("Stopping the coordinator stream metadata store."); coordinatorStreamStore.close(); } } }
Source:
<code>protected Object decode(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception { int curIndex = buffer.readerIndex(); try { ByteBuf frame = (ByteBuf) super.decode(ctx, buffer); if (frame == null) { return null; } Frame theFrame = Frame.create(frame); Message.Response.Type.fromOpcode(theFrame.header.opcode); return theFrame; } catch (CorruptedFrameException e) { throw new DriverInternalError(e); } catch (io.netty.handler.codec.TooLongFrameException e) { int streamId = protocolVersion > 2 ? buffer.getShort(curIndex + 2) : buffer.getByte(curIndex + 2); <START> throw new TooLongFrameException(streamId, e); <END> } }</code><technical_language>catch a subclass of DecoderException, wrap in type wrapped another DecoderException calling Netty code. In exceptionCaught unwrap outer rethrow exception client. a bit convoluted I acceptable for this edge case. thought of rethrowing Netty's TooLongFrameException directly, means store streamId (maybe a context attribute) is a bit clean. suggestion I wanted mention :)</technical_language>

Target:
protected Object decode(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception { int curIndex = buffer.readerIndex(); try { ByteBuf frame = (ByteBuf) super.decode(ctx, buffer); if (frame == null) { return null; } Frame theFrame = Frame.create(frame); Message.Response.Type.fromOpcode(theFrame.header.opcode); return theFrame; } catch (CorruptedFrameException e) { throw new DriverInternalError(e); } catch (TooLongFrameException e) { int streamId = protocolVersion > 2 ? buffer.getShort(curIndex + 2) : buffer.getByte(curIndex + 2); throw new FrameTooLongException(streamId); } }
Source:
<code>private static boolean isThrowableTypeIn(Throwable e, Class<? extends Throwable>... recognizedExceptionTypes) { <START> for (Class<?> recognizedExceptionType : recognizedExceptionTypes) { <END> if (recognizedExceptionType.isInstance(e)) { return true; } } return false; }</code><technical_language>Class instead of Class<?></technical_language>

Target:
private static boolean isThrowableTypeIn(Throwable e, Class<? extends Throwable>... recognizedExceptionTypes) { for (Class recognizedExceptionType : recognizedExceptionTypes) { if (recognizedExceptionType.isInstance(e)) { return true; } } return false; }
Source:
<code>public void update() { <START> if (activeEditor != null && activeEditor.getEditorInput() instanceof SessionEditorInput && ((SessionEditorInput) activeEditor.getEditorInput()).getStatus() == null) { <END> super.update(); } }</code><technical_language>if getStatus return ok, info warning? supposed Status is null well. Perhaps, add "|| ...getStatus()<IStatus.ERROR</technical_language>

Target:
public void update() { if (activeEditor != null && activeEditor.getEditorInput() instanceof SessionEditorInput && ((SessionEditorInput) activeEditor.getEditorInput()).getStatus().getSeverity() < IStatus.ERROR) { super.update(); } }
Source:
<code>public boolean isAsyncStarted(ServletRequest request) { boolean isAsyncStarted; try { <START> Method isAsyncStartedMethod = servletRequestClass.getMethod(IS_ASYNC_STARTED_METHOD_NAME); <END> isAsyncStarted = (Boolean) isAsyncStartedMethod.invoke(request); } catch (Exception e) { isAsyncStarted = false; ServletLogger.LOG.warn(e); } return isAsyncStarted; }</code><technical_language>optimization - do store a reference Class<ServletRequest> method. Then, longer need call getMethod() access</technical_language>

Target:
public boolean isAsyncStarted(ServletRequest request) { if (isAsyncStartedMethod != null) { try { return (Boolean) isAsyncStartedMethod.invoke(request); } catch (IllegalAccessException e) { ServletLogger.LOG.error(e); return false; } catch (InvocationTargetException e) { ServletLogger.LOG.error(e); return false; } } else { return false; } }
Source:
<code>protected void onLoad() { super.onLoad(); Util.ACCOUNT_SVC .myProjectWatch(new ScreenLoadCallback<List<AccountProjectWatchInfo>>( this) { public void preDisplay(final List<AccountProjectWatchInfo> result) { watchedProjects = result; watches.display(result); displayUnwatchedProjects(); } }); <START> Util.PROJECT_SVC.visibleProjects(new ScreenLoadCallback<List<Project>>(this) { <END> @Override protected void preDisplay(final List<Project> result) { allProjects = new ArrayList(result); allProjects.remove(0); displayUnwatchedProjects(); } }); }</code><technical_language>wise defer this DisclosurePanel is expanded user. if need panel track project name tieing RPC slot in user agent load a bunch of data need</technical_language>

Target:
protected void onLoad() { super.onLoad(); populateWatches(); }
Source:
<code>protected void processImages() { if (getVm().getOrigin() == OriginType.KVM) { DiskImage disk = getVm().getImages().get(0); if (disk != null) { disk.setBoot(true); } <START> } <END> ArrayList<Guid> diskIds = new ArrayList<>(); for (DiskImage image : getVm().getImages()) { Guid diskId = createDisk(image); diskIds.add(diskId); } getParameters().setDisks(diskIds); setSucceeded(true); }</code><technical_language>I if (getVm().getOrigin() == OriginType.KVM && !getVm().getImages().isEmpty()) { getVm().getImages().get(0).setBoot(true);; } more readable, please consider</technical_language>

Target:
protected void processImages() { if (getVm().getOrigin() == OriginType.KVM && !getVm().getImages().isEmpty()) { getVm().getImages().get(0).setBoot(true); } ArrayList<Guid> diskIds = new ArrayList<>(); for (DiskImage image : getVm().getImages()) { Guid diskId = createDisk(image); diskIds.add(diskId); } getParameters().setDisks(diskIds); setSucceeded(true); }
Source:
<code>public boolean longLifeTokenExist(String clientId, String userId, Collection<String> scopes) { Collection<OAuth2AccessToken> existingTokens = orcidTokenStore.findTokensByClientIdAndUserName(clientId, userId); if(existingTokens == null || existingTokens.isEmpty()) { return false; } for(OAuth2AccessToken token : existingTokens) { <START> if (token.getAdditionalInformation().get("persistent") != null && Boolean.valueOf((token.getAdditionalInformation().get("persistent").toString()))){ <END> if(token.getScope().containsAll(scopes) && scopes.containsAll(token.getScope())) { return true; } } } return false; }</code><technical_language>Hey @TomDemeranville, please constant OrcidOauth2Constants.PERSISTENT instead of "persistent"? So, easier maintain. Thanks</technical_language>

Target:
public boolean longLifeTokenExist(String clientId, String userId, Collection<String> scopes) { Collection<OAuth2AccessToken> existingTokens = orcidTokenStore.findTokensByClientIdAndUserName(clientId, userId); if(existingTokens == null || existingTokens.isEmpty()) { return false; } for(OAuth2AccessToken token : existingTokens) { if (token.getAdditionalInformation().get(OrcidOauth2Constants.PERSISTENT) != null && Boolean.valueOf((token.getAdditionalInformation().get("persistent").toString()))){ if(token.getScope().containsAll(scopes) && scopes.containsAll(token.getScope())) { return true; } } } return false; }
Source:
<code>public void run(Server server, User user, String commandLabel, String[] args) throws Exception { boolean acceptingPay = !user.isAcceptingPay(); if (commandLabel.contains("payon")) { acceptingPay = true; } else if (commandLabel.contains("payoff")) { acceptingPay = false; } user.setAcceptingPay(acceptingPay); <START> user.sendMessage(acceptingPay ? tl("payToggleOn") : tl("payToggleOff")); <END> }</code><technical_language>worth turning this EssentialsLoopCommand (see #3087)</technical_language>

Target:
public void run(Server server, User user, String commandLabel, String[] args) throws Exception { if (commandLabel.contains("payon")) { togglePlayer(user.getSource(), user, true); } else if (commandLabel.contains("payoff")) { togglePlayer(user.getSource(), user, false); } else { handleToggleWithArgs(server, user, args); } }
Source:
<code>public void decorate(SSLSocket sslSocket) { if (supportedProtocols == null) { readSupportedProtocols(sslSocket); } sslSocket.setEnabledProtocols(getClientEnabledProtocols()); <START> if (!relaxedTrust) { <END> sslSocket.setEnabledCipherSuites(sslSocket.getSupportedCipherSuites()); } }</code><technical_language>relaxedTrust negated, want cipher suites relaxedTrust is true</technical_language>

Target:
public void decorate(SSLSocket sslSocket) { if (supportedProtocols == null) { readSupportedProtocols(sslSocket); } sslSocket.setEnabledProtocols(getClientEnabledProtocols()); if (relaxedTrust) { sslSocket.setEnabledCipherSuites(sslSocket.getSupportedCipherSuites()); } }
Source:
<code>Optional<ParticipantStatus> getStatus() throws InvalidLRAStateException { if (future == null) { return Optional.empty(); } if (future.isDone()) { try { future.get(); return Optional.of(getExpectedStatus()); } catch (ExecutionException e) { return Optional.of(getFailedStatus()); } catch (InterruptedException e) { return Optional.of(getFailedStatus()); } <START> } else if (future.isCancelled()) { <END> return Optional.of(getExpectedStatus()); } else { return Optional.of(getCurrentStatus()); } }</code><technical_language>problem logging condition</technical_language>

Target:
Optional<ParticipantStatus> getStatus() throws InvalidLRAStateException { if (future == null) { return Optional.empty(); } if (future.isDone()) { try { future.get(); return Optional.of(getExpectedStatus()); } catch (ExecutionException e) { LRAProxyLogger.i18NLogger.error_participantExceptionOnCompletion(participant.getClass().getName(), e); return Optional.of(getFailedStatus()); } catch (InterruptedException e) { return Optional.of(getFailedStatus()); } } else if (future.isCancelled()) { return Optional.of(getExpectedStatus()); } else { return Optional.of(getCurrentStatus()); } }
Source:
<code>public static TaskId makeTaskId(String str) { <START> String[] strSplitted = str.split("t"); <END> JobId jobId = JobIdImpl.makeJobId(strSplitted[0]); long taskId = Long.parseLong(strSplitted[1]); return new TaskIdImpl(jobId, taskId); }</code><technical_language>please throw IllegalArgumentException if str "t" if strSplitted.length != 2</technical_language>

Target:
public static TaskId makeTaskId(String str) { String[] strSplitted = str.split("t"); if (!str.contains("t") || strSplitted.length != 2) { throw new IllegalArgumentException("A valid task id must be supplied"); } JobId jobId = JobIdImpl.makeJobId(strSplitted[0]); long taskId = Long.parseLong(strSplitted[1]); return new TaskIdImpl(jobId, taskId); }
Source:
<code>public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { if (args.length == 0) { showExp(user, user); } else if (args.length > 1 && args[0].equalsIgnoreCase("set") && user.isAuthorized("essentials.exp.set")) { if (args.length == 3 && user.isAuthorized("essentials.exp.set.others")) { expMatch(server, user, args[1], args[2], false); } else { setExp(user, user, args[1], false); } } else if (args.length > 1 && args[0].equalsIgnoreCase("give") && user.isAuthorized("essentials.exp.give")) { if (args.length == 3 && user.isAuthorized("essentials.exp.give.others")) { expMatch(server, user, args[1], args[2], true); } else { setExp(user, user, args[1], true); } } <START> else if (args.length > 1 && args[0].equalsIgnoreCase("show")) <END> { if (args.length >= 2 && user.isAuthorized("essentials.exp.others")) { String match = args[1].trim(); showMatch(server, user, match); } else { showExp(user, user); } } else { if (args.length >= 1 && Util.isInt(args[0].toLowerCase(Locale.ENGLISH).replace("l", "")) && user.isAuthorized("essentials.exp.give")) { if (args.length >= 2 && user.isAuthorized("essentials.exp.give.others")) { expMatch(server, user, args[1], args[0], true); } else { setExp(user, user, args[0], true); } } else if (args.length >= 1 && user.isAuthorized("essentials.exp.others")) { String match = args[0].trim(); showMatch(server, user, match); } else { showExp(user, user); } } }</code><technical_language>this shouldnt here</technical_language>

Target:
public void run(final Server server, final User user, final String commandLabel, final String[] args) throws Exception { if (args.length == 0) { showExp(user, user); } else if (args.length > 1 && args[0].equalsIgnoreCase("set") && user.isAuthorized("essentials.exp.set")) { if (args.length == 3 && user.isAuthorized("essentials.exp.set.others")) { expMatch(server, user, args[1], args[2], false); } else { setExp(user, user, args[1], false); } } else if (args.length > 1 && args[0].equalsIgnoreCase("give") && user.isAuthorized("essentials.exp.give")) { if (args.length == 3 && user.isAuthorized("essentials.exp.give.others")) { expMatch(server, user, args[1], args[2], true); } else { setExp(user, user, args[1], true); } } else if (args[0].equalsIgnoreCase("show")) { if (args.length >= 2 && user.isAuthorized("essentials.exp.others")) { String match = args[1].trim(); showMatch(server, user, match); } else { showExp(user, user); } } else { if (args.length >= 1 && Util.isInt(args[0].toLowerCase(Locale.ENGLISH).replace("l", "")) && user.isAuthorized("essentials.exp.give")) { if (args.length >= 2 && user.isAuthorized("essentials.exp.give.others")) { expMatch(server, user, args[1], args[0], true); } else { setExp(user, user, args[0], true); } } else if (args.length >= 1 && user.isAuthorized("essentials.exp.others")) { String match = args[0].trim(); showMatch(server, user, match); } else { showExp(user, user); } } }
Source:
<code>protected void interactWithEntitiesInside() { AxisAlignedBB bb = info.getBoundingBox().contract(1).offset(0, 0.5, 0).expand(0, 0.5, 0); List<Entity> entities = getWorld().getEntitiesWithinAABB(Entity.class, bb); for(Entity entity : entities) { if (entity instanceof EntityMob) { EntityLivingBase entityLiving = (EntityLivingBase) entity; <START> entityLiving.setHealth(0F); <END> } } }</code><technical_language>I dealing fire lava damage consistently is a simple setHealth</technical_language>

Target:
protected void interactWithEntitiesInside() { AxisAlignedBB bb = info.getBoundingBox().contract(1).offset(0, 0.5, 0).expand(0, 0.5, 0); List<EntityLivingBase> entities = getWorld().getEntitiesWithinAABB(EntityLivingBase.class, bb); for(EntityLivingBase entity : entities) { if(entity instanceof EntityMob && entity.isEntityAlive()) { entity.setDead(); } } }
Source:
<code>private void handleGetAll(DataInputStream inputStream, DataOutputStream outputStream, Store<ByteArray, byte[], byte[]> store) throws IOException { long startTimeMs = -1; long startTimeNs = -1; if(logger.isDebugEnabled()) { startTimeMs = System.currentTimeMillis(); startTimeNs = System.nanoTime(); } int numKeys = inputStream.readInt(); List<ByteArray> keys = new ArrayList<ByteArray>(numKeys); for(int i = 0; i < numKeys; i++) keys.add(readKey(inputStream)); Map<ByteArray, byte[]> transforms = null; if(protocolVersion > 2) { if(inputStream.readBoolean()) { int size = inputStream.readInt(); transforms = new HashMap<ByteArray, byte[]>(size); for(int i = 0; i < size; i++) { transforms.put(readKey(inputStream), readTransforms(inputStream)); } } } Map<ByteArray, List<Versioned<byte[]>>> results = null; try { results = store.getAll(keys, transforms); outputStream.writeShort(0); } catch(VoldemortException e) { logger.error(e.getMessage()); writeException(outputStream, e); return; } outputStream.writeInt(results.size()); <START> logger.debug("GETALL start"); <END> for(Map.Entry<ByteArray, List<Versioned<byte[]>>> entry: results.entrySet()) { outputStream.writeInt(entry.getKey().length()); outputStream.write(entry.getKey().get()); writeResults(outputStream, entry.getValue()); if(logger.isDebugEnabled()) { debugLogReturnValue(entry.getKey(), entry.getValue(), startTimeMs, startTimeNs, "GETALL"); } } logger.debug("GETALL end"); }</code><technical_language>place this GETALL end , if debugEnabled block</technical_language>

Target:
private void handleGetAll(DataInputStream inputStream, DataOutputStream outputStream, Store<ByteArray, byte[], byte[]> store) throws IOException { long startTimeMs = -1; long startTimeNs = -1; if(logger.isDebugEnabled()) { startTimeMs = System.currentTimeMillis(); startTimeNs = System.nanoTime(); } int numKeys = inputStream.readInt(); List<ByteArray> keys = new ArrayList<ByteArray>(numKeys); for(int i = 0; i < numKeys; i++) keys.add(readKey(inputStream)); Map<ByteArray, byte[]> transforms = null; if(protocolVersion > 2) { if(inputStream.readBoolean()) { int size = inputStream.readInt(); transforms = new HashMap<ByteArray, byte[]>(size); for(int i = 0; i < size; i++) { transforms.put(readKey(inputStream), readTransforms(inputStream)); } } } Map<ByteArray, List<Versioned<byte[]>>> results = null; try { results = store.getAll(keys, transforms); outputStream.writeShort(0); } catch(VoldemortException e) { logger.error(e.getMessage()); writeException(outputStream, e); return; } outputStream.writeInt(results.size()); if(logger.isDebugEnabled()) logger.debug("GETALL start"); for(Map.Entry<ByteArray, List<Versioned<byte[]>>> entry: results.entrySet()) { outputStream.writeInt(entry.getKey().length()); outputStream.write(entry.getKey().get()); writeResults(outputStream, entry.getValue()); if(logger.isDebugEnabled()) { debugLogReturnValue(entry.getKey(), entry.getValue(), startTimeMs, startTimeNs, "GETALL"); } } if(logger.isDebugEnabled()) logger.debug("GETALL end"); }
Source:
<code>private static void serializeElements(XPathNodeset nodeset, OutputStream output) throws IOException { KXmlSerializer serializer = new KXmlSerializer(); try { serializer.setOutput(output, "UTF-8"); } catch (IOException e) { throw new RuntimeException(e); } DataModelSerializer s = new DataModelSerializer(serializer); DataInstance instance = nodeset.getInstance(); Vector<TreeReference> refs = nodeset.getReferences(); if (refs == null) { <START> return; <END> } for (TreeReference ref : refs) { AbstractTreeElement treeElement = instance.resolveReference(ref); s.serialize(treeElement); } }</code><technical_language>I good practice for assume nodeset is formed if refs is null here. circumstance is arising in? I a stronger change for encode situation deliberately assuming a valid state for nodeset arrived in</technical_language>

Target:
private static void serializeElements(XPathNodeset nodeset, OutputStream output) throws IOException { KXmlSerializer serializer = new KXmlSerializer(); try { serializer.setOutput(output, "UTF-8"); } catch (IOException e) { throw new RuntimeException(e); } DataModelSerializer s = new DataModelSerializer(serializer); DataInstance instance = nodeset.getInstance(); Vector<TreeReference> refs = nodeset.getReferences(); for (TreeReference ref : refs) { AbstractTreeElement treeElement = instance.resolveReference(ref); s.serialize(treeElement); } }
Source:
<code>private int getPluginsLoadTimeout(final Config cfg) { long cfgValue = ConfigUtil.getTimeUnit(cfg, "plugins", null, "jsLoadTimeout", <START> 5000, <END> TimeUnit.MILLISECONDS); if (cfgValue < 0) { return 0; } return (int) cfgValue; }</code><technical_language>Define this a constant</technical_language>

Target:
private int getPluginsLoadTimeout(final Config cfg) { long cfgValue = ConfigUtil.getTimeUnit(cfg, "plugins", null, "jsLoadTimeout", DEFAULT_JS_LOAD_TIMEOUT, TimeUnit.MILLISECONDS); if (cfgValue < 0) { return 0; } return (int) cfgValue; }
Source:
<code>public static Set<Set<Guid>> getUnifiedPositiveAffinityGroups(List<AffinityGroup> affinityGroups) { Set<Set<Guid>> uag = new HashSet<>(); Map<Guid, Set<Guid>> vmIndex = new HashMap<>(); for(AffinityGroup ag: affinityGroups) { if(ag.getEntityIds() == null) { continue; } for(Guid id : ag.getEntityIds()) { Set<Guid> temp = new HashSet<>(); temp.add(id); uag.add(temp); vmIndex.put(id, temp); } } for(AffinityGroup ag : affinityGroups) { if(ag.isPositive()) { Set<Guid> mergedGroup = new HashSet<>(); if(ag.getEntityIds() == null) { <START> continue; <END> } for(Guid id : ag.getEntityIds()) { Set<Guid> existingGroup = vmIndex.get(id); mergedGroup.addAll(existingGroup); uag.remove(existingGroup); for (Guid vm: existingGroup) { vmIndex.put(vm, mergedGroup); } } uag.add(mergedGroup); } } return uag; }</code><technical_language>instead of skipping 2 times, remove list</technical_language>

Target:
public static Set<Set<Guid>> getUnifiedPositiveAffinityGroups(List<AffinityGroup> affinityGroups) { Set<Set<Guid>> uag = new HashSet<>(); Map<Guid, Set<Guid>> vmIndex = new HashMap<>(); for(AffinityGroup ag: affinityGroups) { if(ag.getEntityIds() == null) { affinityGroups.remove(ag); continue; } for(Guid id : ag.getEntityIds()) { Set<Guid> temp = new HashSet<>(); temp.add(id); uag.add(temp); vmIndex.put(id, temp); } } for(AffinityGroup ag : affinityGroups) { if(ag.isPositive()) { Set<Guid> mergedGroup = new HashSet<>(); for(Guid id : ag.getEntityIds()) { Set<Guid> existingGroup = vmIndex.get(id); mergedGroup.addAll(existingGroup); uag.remove(existingGroup); for (Guid vm: existingGroup) { vmIndex.put(vm, mergedGroup); } } uag.add(mergedGroup); } } return uag; }
Source:
<code>private void setIcon(RemoteServerState.State state) { switch (state) { case UNKNOWN: setIcon(ImageManager.get().getImageIcon("images/datacloud/cloudNotUsed.png", IconUtils.ICON_SIZE_SMALL)); break; case NO_CREDIT: <START> setIcon(ImageManager.get().getImageIcon("images/datacloud/cloudNoCredit.png", IconUtils.ICON_SIZE_SMALL)); <END> break; case OK: setIcon(ImageManager.get().getImageIcon("images/datacloud/cloudOk.png", IconUtils.ICON_SIZE_SMALL)); break; case ERROR: setIcon(ImageManager.get().getImageIcon("images/datacloud/cloudError.png", IconUtils.ICON_SIZE_SMALL)); break; } }</code><technical_language>a more generic name here. a good chance this icon reused for other warning-level problems later</technical_language>

Target:
private void setIcon(RemoteServerState.State state) { switch (state) { case NOT_CONNECTED: setIcon(ImageManager.get().getImageIcon(IconUtils.CLOUD_GREY, IconUtils.ICON_SIZE_SMALL)); break; case NO_CREDIT: setIcon(ImageManager.get().getImageIcon(IconUtils.CLOUD_ORANGE, IconUtils.ICON_SIZE_SMALL)); break; case OK: setIcon(ImageManager.get().getImageIcon(IconUtils.CLOUD_GREEN, IconUtils.ICON_SIZE_SMALL)); break; case ERROR: setIcon(ImageManager.get().getImageIcon(IconUtils.CLOUD_RED, IconUtils.ICON_SIZE_SMALL)); break; } }
Source:
<code>public void configRoundtrip() throws Exception { MockSCMController c = MockSCMController.create(); try { c.createRepository("foo"); SingleSCMSource source = new SingleSCMSource("the-id", "the-name", new MockSCM(c, "foo", new MockSCMHead("master"), null)); SCMSourceBuilder builder = new SCMSourceBuilder(source); <START> r.assertEqualDataBoundBeans(builder, r.configRoundtrip(builder)); <END> } finally { c.close(); } }</code><technical_language>this work? configRoundtrip returns parameter is. means compare data, new new data</technical_language>

Target:
public void configRoundtrip() throws Exception { MockSCMController c = MockSCMController.create(); try { c.createRepository("foo"); SingleSCMSource source = new SingleSCMSource( "the-id", "the-name", new MockSCM( c, "foo", new MockSCMHead("master"), null ) ); SCMSourceBuilder builder = new SCMSourceBuilder(source); r.assertEqualDataBoundBeans(new SCMSourceBuilder(new SingleSCMSource( "the-id", "the-name", new MockSCM( c, "foo", new MockSCMHead("master"), null ) )), r.configRoundtrip(builder)); } finally { c.close(); } }
Source:
<code><START> public static OkHttpClient HttpClientBuilder() { <END> ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) .tlsVersions(TlsVersion.TLS_1_2) .cipherSuites( CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256) .build(); OkHttpClient httpClient = new OkHttpClient.Builder() .connectTimeout(5000, TimeUnit.MILLISECONDS) .readTimeout(30000, TimeUnit.MILLISECONDS) .writeTimeout(30000, TimeUnit.MILLISECONDS) .connectionSpecs(Collections.singletonList(spec)) .build(); return httpClient; }</code><technical_language>I approach; TLS 1.2 allowed CipherSuites limited API 24 (higher API levels want TLS 1.3 for example)</technical_language>

Target:
public static OkHttpClient HttpClientBuilder() { OkHttpClient httpClient; if (Build.VERSION.SDK_INT == 24) { ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) .tlsVersions(TlsVersion.TLS_1_2) .cipherSuites(CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256) .build(); httpClient = new OkHttpClient.Builder() .connectTimeout(5000, TimeUnit.MILLISECONDS) .readTimeout(30000, TimeUnit.MILLISECONDS) .writeTimeout(30000, TimeUnit.MILLISECONDS) .connectionSpecs(Collections.singletonList(spec)) .build(); } else { httpClient = new OkHttpClient.Builder() .connectTimeout(5000, TimeUnit.MILLISECONDS) .readTimeout(30000, TimeUnit.MILLISECONDS) .writeTimeout(30000, TimeUnit.MILLISECONDS) .build(); } return httpClient; }
Source:
<code>private void reject(final RawData raw, final MessageFormatException cause) { EmptyMessage rst = new EmptyMessage(Type.RST); rst.setMID(cause.getMid()); rst.setToken(new byte[0]); rst.setDestination(raw.getAddress()); rst.setDestinationPort(raw.getPort()); <START> <END> reject(rst); LOGGER.log( Level.FINE, "rejected malformed message from [{0}], reason: {1}", new Object[]{raw.getInetSocketAddress(), cause.getMessage()}); }</code><technical_language>Removing interceptors removes logging</technical_language>

Target:
private void reject(final RawData raw, final MessageFormatException cause) { EmptyMessage rst = new EmptyMessage(Type.RST); rst.setMID(cause.getMid()); rst.setToken(new byte[0]); rst.setDestination(raw.getAddress()); rst.setDestinationPort(raw.getPort()); for (MessageInterceptor interceptor : interceptors) { interceptor.sendEmptyMessage(rst); } connector.send(serializer.serializeEmptyMessage(rst)); LOGGER.log( Level.FINE, "rejected malformed message from [{0}], reason: {1}", new Object[]{raw.getInetSocketAddress(), cause.getMessage()}); }
Source:
<code><START> public int nextClearBit(final int i) { <END> int x = i >> 6; long w = ~bitmap.get(x); w >>>= i; if (w != 0) { return i + numberOfTrailingZeros(w); } int length = bitmap.limit(); for (++x; x < length; ++x) { long map = ~bitmap.get(x); if (map != 0L) { return x * 64 + numberOfTrailingZeros(map); } } return length * 64; }</code><technical_language>if is this. I prefer new name though</technical_language>

Target:
public int nextClearBit(final int i) { int x = i >> 6; long w = ~bitmap.get(x); w >>>= i; if (w != 0) { return i + numberOfTrailingZeros(w); } int length = bitmap.limit(); for (++x; x < length; ++x) { long map = ~bitmap.get(x); if (map != 0L) { return x * 64 + numberOfTrailingZeros(map); } } return MAX_CAPACITY; }
Source:
<code>protected WeldBeanDeploymentArchive createAdditionalBeanDeploymentArchive(Class<?> beanClass) { Set<String> beanClasses = new HashSet<String>(); beanClasses.add(beanClass.getName()); WeldBeanDeploymentArchive additionalBda = new WeldBeanDeploymentArchive(beanClass.getClassLoader().getClass().getName() + "@" <START> + System.identityHashCode(beanClass.getClassLoader()) + ADDITIONAL_BDA_ID_SUFFIX, beanClasses, null); <END> additionalBda.getServices().add(ResourceLoader.class, resourceLoader); additionalBda.getServices().addAll(getServices().entrySet()); beanDeploymentArchives.add(additionalBda); for (WeldBeanDeploymentArchive archive : beanDeploymentArchives) { archive.setAccessibleBeanDeploymentArchives(beanDeploymentArchives); } additionalBeanDeploymentArchives.put(beanClass.getClassLoader(), additionalBda); return additionalBda; }</code><technical_language>System.identityHashCode(beanClass.getClassLoader()) non-deterministict BDA IDs. deterministic</technical_language>

Target:
protected WeldBeanDeploymentArchive createAdditionalBeanDeploymentArchive(Class<?> beanClass) { Set<String> beanClasses = new HashSet<String>(); beanClasses.add(beanClass.getName()); WeldBeanDeploymentArchive additionalBda = new WeldBeanDeploymentArchive(ADDITIONAL_BDA_ID, beanClasses, null); additionalBda.getServices().add(ResourceLoader.class, resourceLoader); additionalBda.getServices().addAll(getServices().entrySet()); beanDeploymentArchives.add(additionalBda); for (WeldBeanDeploymentArchive archive : beanDeploymentArchives) { archive.setAccessibleBeanDeploymentArchives(beanDeploymentArchives); } return additionalBda; }
Source:
<code>public void init(ProjectScreen presenter) { this.presenter = presenter; if (!this.presenter.canEditContributors()) { this.editContributors.hidden = true; } if (!this.presenter.userCanUpdateProject()) { this.addAsset.hidden = true; this.importAsset.hidden = true; } if (!this.presenter.userCanBuildProject()) { this.build.disabled = true; <START> this.deploy.disabled = true; <END> } if (!this.presenter.userCanDeleteRepository()) { this.deleteProject.hidden = true; } }</code><technical_language>is disabling in ifs is hiding? is wrong, interested</technical_language>

Target:
public void init(ProjectScreen presenter) { this.presenter = presenter; }
Source:
<code>private void removeEntitiesFromStorageDomain(final List<VM> vmsForStorageDomain, final List<VmTemplate> vmTemplatesForStorageDomain, final List<DiskImage> disksForStorageDomain, final Guid storageDomainId) { TransactionSupport.executeInNewTransaction(() -> { <START> if (!vmsForStorageDomain.isEmpty() || !vmTemplatesForStorageDomain.isEmpty() || !disksForStorageDomain.isEmpty()) { <END> for (VM vm : vmsForStorageDomain) { removeEntityLeftOver(vm.getId(), vm.getName(), storageDomainId); unregisteredOVFDataDao.saveOVFData(new OvfEntityData( vm.getId(), vm.getName(), VmEntityType.VM, vm.getClusterArch(), vm.getCompatibilityVersion(), storageDomainId, null, null)); } for (VmTemplate vmTemplate : vmTemplatesForStorageDomain) { removeEntityLeftOver(vmTemplate.getId(), vmTemplate.getName(), storageDomainId); unregisteredOVFDataDao.saveOVFData(new OvfEntityData( vmTemplate.getId(), vmTemplate.getName(), VmEntityType.TEMPLATE, vmTemplate.getClusterArch(), clusterDao.get(vmTemplate.getClusterId()).getCompatibilityVersion(), storageDomainId, null, null)); } storageDomainDao.removeEntitesFromStorageDomain(storageDomainId); } return null; }); }</code><technical_language>Please return place</technical_language>

Target:
private void removeEntitiesFromStorageDomain(final List<VM> vmsForStorageDomain, final List<VmTemplate> vmTemplatesForStorageDomain, final List<DiskImage> disksForStorageDomain, final Guid storageDomainId) { if (!vmsForStorageDomain.isEmpty() || !vmTemplatesForStorageDomain.isEmpty() || !disksForStorageDomain.isEmpty()) { TransactionSupport.executeInNewTransaction(() -> { for (VM vm : vmsForStorageDomain) { removeEntityLeftOver(vm.getId(), vm.getName(), storageDomainId); unregisteredOVFDataDao.saveOVFData(new OvfEntityData( vm.getId(), vm.getName(), VmEntityType.VM, vm.getClusterArch(), vm.getCompatibilityVersion(), storageDomainId, null, null)); } for (VmTemplate vmTemplate : vmTemplatesForStorageDomain) { removeEntityLeftOver(vmTemplate.getId(), vmTemplate.getName(), storageDomainId); unregisteredOVFDataDao.saveOVFData(new OvfEntityData( vmTemplate.getId(), vmTemplate.getName(), VmEntityType.TEMPLATE, vmTemplate.getClusterArch(), clusterDao.get(vmTemplate.getClusterId()).getCompatibilityVersion(), storageDomainId, null, null)); } storageDomainDao.removeEntitesFromStorageDomain(storageDomainId); return null; } }); }
Source:
<code>public ContainerBuilder(Container origin) { if (origin == null) { throw new IllegalArgumentException("origin cannot be null."); } <START> this.id = origin.getId(); <END> this.name = origin.getName(); this.status = origin.getStatus(); this.description = origin.getDescription(); this.isPrivate = origin.getIsPrivate(); this.parentAccountId = origin.getParentAccountId(); this.version = CONTAINER_METADATA_VERSION_1; }</code><technical_language>question above. do handle multiple versions of Container passed in argument</technical_language>

Target:
public ContainerBuilder(Container origin) { if (origin == null) { throw new IllegalArgumentException("origin cannot be null."); } id = origin.getId(); name = origin.getName(); status = origin.getStatus(); description = origin.getDescription(); isPrivate = origin.isPrivate(); parentAccountId = origin.getParentAccountId(); }
Source:
<code>private DatasetResponseWithStatusCodeAndHeaders fetchOnlyOnce(final URI resource, final URI requesterWebID, final LinkedDataCacheEntry linkedDataCacheEntry, final HttpHeaders headers) { String cacheKey = makeCacheKey(resource, requesterWebID); CountDownLatch latch = new CountDownLatch(1); CountDownLatch preExistingLatch = countDownLatchMap.putIfAbsent(cacheKey, latch); try { if (preExistingLatch != null) { if (logger.isDebugEnabled()) { <START> logger.debug("resource " + cacheKey <END> + " is being fetched in another thread, we wait for its result and use it " + "if it turns out to be cacheable"); } try { preExistingLatch.await(); } catch (InterruptedException e) { logger.warn("interrupted while waiting for another thread to fetch '" + resource + "'"); } Element element = cache.get(cacheKey); if (element != null) { if (logger.isDebugEnabled()) { logger.debug("resource " + cacheKey + " turned out to be cacheable, using it"); } LinkedDataCacheEntry entry = (LinkedDataCacheEntry) element.getObjectValue(); return entry.recreateResponse(); } if (logger.isDebugEnabled()) { logger.debug("resource " + cacheKey + " did not turn out to be cacheable - fetching it, too"); } } return fetchAndCacheIfAppropriate(resource, requesterWebID, linkedDataCacheEntry, headers); } finally { countDownLatchMap.remove(cacheKey, latch); latch.countDown(); } }</code><technical_language>nitpick, if a parameterized query ( .. {}... cacheKey a parameter) avoid isDebugEnabled clause, logger framework concat/init log-string if debug mode is enabled</technical_language>

Target:
private DatasetResponseWithStatusCodeAndHeaders fetchOnlyOnce(final URI resource, final URI requesterWebID, final LinkedDataCacheEntry linkedDataCacheEntry, final HttpHeaders headers) { String cacheKey = makeCacheKey(resource, requesterWebID); CountDownLatch latch = new CountDownLatch(1); CountDownLatch preExistingLatch = countDownLatchMap.putIfAbsent(cacheKey, latch); try { if (preExistingLatch != null) { if (logger.isDebugEnabled()) { logger.debug("resource {}" + " is being fetched in another thread, we wait for its result and use it " + "if it turns out to be cacheable", cacheKey); } try { preExistingLatch.await(); } catch (InterruptedException e) { logger.warn("interrupted while waiting for another thread to fetch '" + resource + "'"); } Element element = cache.get(cacheKey); if (element != null) { if (logger.isDebugEnabled()) { logger.debug("resource turned out to be cacheable, using it", cacheKey); } LinkedDataCacheEntry entry = (LinkedDataCacheEntry) element.getObjectValue(); return entry.recreateResponse(); } if (logger.isDebugEnabled()) { logger.debug("resource did not turn out to be cacheable - fetching it, too", cacheKey); } } return fetchAndCacheIfAppropriate(resource, requesterWebID, linkedDataCacheEntry, headers); } finally { countDownLatchMap.remove(cacheKey, latch); latch.countDown(); } }
Source:
<code>public Optional<SmeltingResult> getResult(@Nonnull ItemStackSnapshot ingredient) { if (isValid(ingredient)) { return Optional.of(new SmeltingResult(this.exemplaryResult, this.experience)); <START> } else { <END> return Optional.empty(); } }</code><technical_language>Unnecessary else</technical_language>

Target:
public Optional<SmeltingResult> getResult(@Nonnull ItemStackSnapshot ingredient) { if (isValid(ingredient)) { return Optional.of(new SmeltingResult(this.exemplaryResult, this.experience)); } return Optional.empty(); }
Source:
<code><START> private ResourcePool tryFindResourcePool(Folder folder, String hostname) { <END> Iterable<ResourcePool> resourcePools = ImmutableSet.<ResourcePool>of(); try { ManagedEntity[] resourcePoolEntities = new InventoryNavigator(folder).searchManagedEntities("ResourcePool"); resourcePools = Iterables.transform(Arrays.asList(resourcePoolEntities), new Function<ManagedEntity, ResourcePool>() { public ResourcePool apply(ManagedEntity input) { return (ResourcePool) input; } }); Optional<ResourcePool> optionalResourcePool = Iterables.tryFind(resourcePools, VSpherePredicate.isResourcePoolOf(hostname)); return optionalResourcePool.orNull(); } catch (Exception e) { logger.error("Problem in finding a valid resource pool", e); } return null; }</code><technical_language>In general, "tryFind" methods return Optional. Consider changing return type</technical_language>

Target:
private Optional<ResourcePool> tryFindResourcePool(Folder folder, String hostname) { Iterable<ResourcePool> resourcePools = ImmutableSet.<ResourcePool>of(); try { ManagedEntity[] resourcePoolEntities = new InventoryNavigator(folder).searchManagedEntities("ResourcePool"); resourcePools = Iterables.transform(Arrays.asList(resourcePoolEntities), new Function<ManagedEntity, ResourcePool>() { public ResourcePool apply(ManagedEntity input) { return (ResourcePool) input; } }); Optional<ResourcePool> optionalResourcePool = Iterables.tryFind(resourcePools, VSpherePredicate.isResourcePoolOf(hostname)); return optionalResourcePool; } catch (Exception e) { logger.error("Problem in finding a valid resource pool", e); } return Optional.absent(); }
Source:
<code>private void mkAssignments() throws Exception { try { <START> mkAssignments(null); <END> } catch(Exception e) { this.mkAssignmentsErrors.mark(); throw e; } }</code><technical_language>Do want change mkAssignments(String scratchTopoId) count errors rebalance command well</technical_language>

Target:
private void mkAssignments() throws Exception { mkAssignments(null); }
Source:
<code>public void instantiationWithHttpRequestPopulatesCorrectly() throws IOException { HttpServletRequest mockRequest = mock(HttpServletRequest.class); String expectedPathInfo = "someUrlPath"; String expectedMethod = "GET"; <START> Enumeration<String> expectedHeaderNames = new Vector<String>(Arrays.asList("header1")).elements(); <END> String bodyContent = "bodyContent"; String expectedContentType = "contentType"; when(mockRequest.getPathInfo()).thenReturn(expectedPathInfo); when(mockRequest.getMethod()).thenReturn(expectedMethod); when(mockRequest.getQueryString()).thenReturn("hello=world"); when(mockRequest.getHeaderNames()).thenReturn(expectedHeaderNames); when(mockRequest.getHeader("header1")).thenReturn("thisIsHeader1"); when(mockRequest.getReader()).thenReturn(new BufferedReader(new StringReader(bodyContent))); when(mockRequest.getContentType()).thenReturn(expectedContentType); ClientDriverRequest clientDriverRequest = new ClientDriverRequest(mockRequest); assertThat((String) clientDriverRequest.getPath(), is(expectedPathInfo)); assertThat(clientDriverRequest.getMethod(), is(Method.GET)); assertThat(clientDriverRequest.getParams().size(), is(1)); assertThat((String) clientDriverRequest.getParams().get("hello").iterator().next(), is("world")); assertThat((String) clientDriverRequest.getHeaders().get("header1"), is("thisIsHeader1")); assertThat((String) clientDriverRequest.getBodyContentType(), is(expectedContentType)); }</code><technical_language>Collections.enumeration(Arrays.asList(...)) instead</technical_language>

Target:
public void instantiationWithHttpRequestPopulatesCorrectly() throws IOException { HttpServletRequest mockRequest = mock(HttpServletRequest.class); String expectedPathInfo = "someUrlPath"; String expectedMethod = "GET"; Enumeration<String> expectedHeaderNames = Collections.enumeration(Arrays.asList("header1")); String bodyContent = "bodyContent"; String expectedContentType = "contentType"; when(mockRequest.getPathInfo()).thenReturn(expectedPathInfo); when(mockRequest.getMethod()).thenReturn(expectedMethod); when(mockRequest.getParameterMap()).thenReturn(new HashMap<String, String[]>() {{ put("hello", new String[] { "world" });}}); when(mockRequest.getHeaderNames()).thenReturn(expectedHeaderNames); when(mockRequest.getHeader("header1")).thenReturn("thisIsHeader1"); when(mockRequest.getReader()).thenReturn(new BufferedReader(new StringReader(bodyContent))); when(mockRequest.getContentType()).thenReturn(expectedContentType); ClientDriverRequest clientDriverRequest = new ClientDriverRequest(mockRequest); assertThat((String) clientDriverRequest.getPath(), is(expectedPathInfo)); assertThat(clientDriverRequest.getMethod(), is(Method.GET)); assertThat(clientDriverRequest.getParams().size(), is(1)); assertThat((String) clientDriverRequest.getParams().get("hello").iterator().next(), is("world")); assertThat((String) clientDriverRequest.getHeaders().get("header1"), is("thisIsHeader1")); assertThat((String) clientDriverRequest.getBodyContentType(), is(expectedContentType)); }
Source:
<code>private void closeConnection(String deviceId) { DeviceConfig device = deviceConfigCache.get(deviceId); if (device == null) { <START> logger.error("Could not find device '{}'", deviceId); <END> return; } EpsonProjectorDevice remoteController = device.getConnection(); if (remoteController != null) { try { logger.debug("Closing connection to device '{}' ", deviceId); remoteController.disconnect(); } catch (EpsonProjectorException e) { logger.debug("Error occurred when closing connection to device '{}'", deviceId); } } }</code><technical_language>This a WARN instead of ERROR</technical_language>

Target:
private void closeConnection(String deviceId) { DeviceConfig device = deviceConfigCache.get(deviceId); if (device == null) { logger.warn("Could not find device '{}'", deviceId); return; } EpsonProjectorDevice remoteController = device.getConnection(); if (remoteController != null) { try { logger.debug("Closing connection to device '{}' ", deviceId); remoteController.disconnect(); } catch (EpsonProjectorException e) { logger.debug("Error occurred when closing connection to device '{}'", deviceId); } } }
Source:
<code>public static String formatFilesize(long filesize, int decimalPlaces) { int multipleCount = 0; long filesizeRemainder = 0; long filesizeValue = filesize; <START> while (filesizeValue > 1024 && multipleCount < filesizeSuffixes.length) { <END> filesizeRemainder = filesizeValue % 1024; filesizeValue /= 1024; multipleCount++; } StringBuilder filesizeBuilder = new StringBuilder(); filesizeBuilder.append(filesizeValue); if (filesizeRemainder > 0 && decimalPlaces > 0) { int decimalMultiplier = 1; for (int i = 0; i < decimalPlaces; i++) { decimalMultiplier *= 10; } filesizeRemainder = (filesizeRemainder * decimalMultiplier) / 1024; if (filesizeRemainder > 0) { filesizeBuilder.append(".").append(filesizeRemainder); } } filesizeBuilder.append(" "); if (multipleCount < filesizeSuffixes.length) { filesizeBuilder.append(filesizeSuffixes[multipleCount]); } else { filesizeBuilder.append(filesizeSuffixes[filesizeSuffixes.length - 1]); } return filesizeBuilder.toString(); }</code><technical_language>ONE_MB constant here</technical_language>

Target:
public static String formatFilesize(long filesize, int decimalPlaces) { int multipleCount = 0; long filesizeRemainder = 0; long filesizeValue = filesize; while (filesizeValue > UNIT_FACTOR && multipleCount < filesizeSuffixes.length) { filesizeRemainder = filesizeValue % UNIT_FACTOR; filesizeValue /= UNIT_FACTOR; multipleCount++; } StringBuilder filesizeBuilder = new StringBuilder(); filesizeBuilder.append(filesizeValue); if (filesizeRemainder > 0 && decimalPlaces > 0) { int decimalMultiplier = 1; for (int i = 0; i < decimalPlaces; i++) { decimalMultiplier *= 10; } filesizeRemainder = (filesizeRemainder * decimalMultiplier) / UNIT_FACTOR; if (filesizeRemainder > 0) { filesizeBuilder.append(".").append(filesizeRemainder); } } filesizeBuilder.append(" "); if (multipleCount < filesizeSuffixes.length) { filesizeBuilder.append(filesizeSuffixes[multipleCount]); } else { filesizeBuilder.append(filesizeSuffixes[filesizeSuffixes.length - 1]); } return filesizeBuilder.toString(); }