auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private synchronized void addEntryTodnsToUuidMap( String dnsName, String uuid) { Set<String> dnList = dnsToUuidMap.get(dnsName); if (dnList == null) { <START> dnList = new HashSet<>(); <END> dnsToUuidMap.put(dnsName, dnList); } dnList.add(uuid); }</code><technical_language>Do need concurrent HashSet here? dnsToUuidMap is thread safe if reader writer start HashSet</technical_language>

Target:
private synchronized void addEntryTodnsToUuidMap( String dnsName, String uuid) { Set<String> dnList = dnsToUuidMap.get(dnsName); if (dnList == null) { dnList = ConcurrentHashMap.newKeySet(); dnsToUuidMap.put(dnsName, dnList); } dnList.add(uuid); }
Source:
<code>public Candidate getCandidate() { double[] values = selectionOperator.buildNextGenes(); Object value = null; Exception e = null; try { value = parameterSpace.getValue(values); } catch (Exception e2) { <START> e = e2; <END> } return new Candidate(value, candidateCounter.getAndIncrement(), values, dataParameters, e); }</code><technical_language>log a warning here</technical_language>

Target:
public Candidate getCandidate() { double[] values = null; Object value = null; Exception e = null; try { values = selectionOperator.buildNextGenes(); value = parameterSpace.getValue(values); } catch (GeneticGenerationException e2) { log.warn("Error generating candidate", e2); e = e2; hasMoreCandidates = false; } catch (Exception e2) { log.warn("Error getting configuration for candidate", e2); e = e2; } return new Candidate(value, candidateCounter.getAndIncrement(), values, dataParameters, e); }
Source:
<code>public void onSettingsClick(MenuItem item) { <START> Toast.makeText(this, "Open settings", Toast.LENGTH_SHORT).show(); <END> showSettingsDialog(); }</code><technical_language>remove this Toast</technical_language>

Target:
public void onSettingsClick(MenuItem item) { showSettingsDialog(); }
Source:
<code>private void estimateCommandsMachineName( WorkspaceConfig workspaceConfig, Tool tool, List<HasMetadata> toolsObjects) { List<? extends Command> toolCommands = workspaceConfig .getCommands() .stream() .filter( c -> tool.getName() .equals(c.getAttributes().get(Constants.TOOL_NAME_COMMAND_ATTRIBUTE))) .collect(toList()); if (toolCommands.isEmpty()) { return; } List<PodData> podsData = new ArrayList<>(); toolsObjects .stream() .filter(hasMetadata -> hasMetadata instanceof Pod) .map(hasMetadata -> (Pod) hasMetadata) .forEach(p -> podsData.add(new PodData(p))); toolsObjects .stream() .filter(hasMetadata -> hasMetadata instanceof Deployment) .map(hasMetadata -> (Deployment) hasMetadata) .forEach(d -> podsData.add(new PodData(d))); PodData pod; <START> if (podsData.size() != 1 || (pod = podsData.get(0)).getSpec().getContainers().isEmpty()) { <END> return; } String machineName = Names.machineName(pod, pod.getSpec().getContainers().get(0)); toolCommands.forEach(c -> c.getAttributes().put(MACHINE_NAME_ATTRIBUTE, machineName)); }</code><technical_language>IMHO, inlined assignment simple decision logic unnecessarily hard parse eyes. simply: java if (podsData.size() != 1) { // pods - estimate name of ambiguity lack of information return; } PodData pod = podsData.get(0); if (pod.getSpec().getContainers().isEmpty()) { // containers base name return; } code is read more times is written</technical_language>

Target:
private void estimateCommandsMachineName( WorkspaceConfig workspaceConfig, Tool tool, List<HasMetadata> toolsObjects) { List<? extends Command> toolCommands = workspaceConfig .getCommands() .stream() .filter( c -> tool.getName() .equals(c.getAttributes().get(Constants.TOOL_NAME_COMMAND_ATTRIBUTE))) .collect(toList()); if (toolCommands.isEmpty()) { return; } List<PodData> podsData = new ArrayList<>(); toolsObjects .stream() .filter(hasMetadata -> hasMetadata instanceof Pod) .map(hasMetadata -> (Pod) hasMetadata) .forEach(p -> podsData.add(new PodData(p))); toolsObjects .stream() .filter(hasMetadata -> hasMetadata instanceof Deployment) .map(hasMetadata -> (Deployment) hasMetadata) .forEach(d -> podsData.add(new PodData(d))); if (podsData.size() != 1) { return; } PodData pod = podsData.get(0); if (pod.getSpec().getContainers().size() != 1) { return; } String machineName = Names.machineName(pod, pod.getSpec().getContainers().get(0)); toolCommands.forEach(c -> c.getAttributes().put(MACHINE_NAME_ATTRIBUTE, machineName)); }
Source:
<code><START> protected boolean deploymentNeverDisabled(List<String> previewListItems) { <END> return itemInListExistsLowerCase(previewListItems, "the deployment was never disabled"); }</code><technical_language>package private visibility? Protected visibility recommend subclassing of DeploymentsOperations. intention? Why</technical_language>

Target:
public boolean deploymentNeverDisabled(List<String> previewListItems) { return itemInListExistsLowerCase(previewListItems, "the deployment was never disabled"); }
Source:
<code>public void checkpoint(ManagementPlaneSyncRecord record) { init(); for (ManagementNodeSyncRecord node : record.getManagementNodes().values()) { <START> if (node.getNodeId() != null) { <END> persist(node); } } }</code><technical_language>reasonable. id null in future, filter based INITIALIZING state (or either, i.e. id==null triggers exclusion)</technical_language>

Target:
public void checkpoint(ManagementPlaneSyncRecord record) { init(); for (ManagementNodeSyncRecord node : record.getManagementNodes().values()) { if (!ManagementNodeState.INITIALIZING.equals(node.getStatus()) && node.getNodeId() != null) { persist(node); } } }
Source:
<code>public Response intercept(Chain chain) throws IOException { Request request = chain.request(); OpenSpan callState = Tracer.startSpan(request.method() + " " + request.url()); Request.Builder tracedRequest = request.newBuilder() .addHeader(TraceHttpHeaders.TRACE_ID, Tracer.getTraceId()) <START> .addHeader(TraceHttpHeaders.SPAN_ID, callState.getSpanId()); <END> if (callState.getParentSpanId().isPresent()) { tracedRequest.header(TraceHttpHeaders.PARENT_SPAN_ID, callState.getParentSpanId().get()); } try { return chain.proceed(tracedRequest.build()); } finally { Tracer.completeSpan(); } }</code><technical_language>sampling header</technical_language>

Target:
public Response intercept(Chain chain) throws IOException { Request request = chain.request(); OpenSpan span = Tracer.startSpan(request.method() + " " + request.url()); Request.Builder tracedRequest = request.newBuilder() .addHeader(TraceHttpHeaders.TRACE_ID, Tracer.getTraceId()) .addHeader(TraceHttpHeaders.SPAN_ID, span.getSpanId()) .addHeader(TraceHttpHeaders.IS_SAMPLED, Tracer.isTraceObservable() ? "1" : "0"); if (span.getParentSpanId().isPresent()) { tracedRequest.header(TraceHttpHeaders.PARENT_SPAN_ID, span.getParentSpanId().get()); } try { return chain.proceed(tracedRequest.build()); } finally { Tracer.completeSpan(); } }
Source:
<code>public int deduplicate(String crawlId, String batchId) throws Exception { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); long start = System.currentTimeMillis(); <START> LOG.info("DeduplicatorJob: starting at " + sdf.format(start)); <END> if (batchId.equals(Nutch.ALL_BATCH_ID_STR)) { LOG.info("DeduplicatorJob: deduplicating all"); } else { LOG.info("DeduplicatorJob: batchId: "+ batchId); } run(ToolUtil.toArgMap(Nutch.ARG_CRAWL, crawlId, Nutch.ARG_BATCH, batchId)); long finish = System.currentTimeMillis(); LOG.info("DeduplicatorJob: finished at " + sdf.format(finish) + ", time elapsed: " + TimingUtil.elapsedTime(start, finish)); return 0; }</code><technical_language>Please paramaterized logging</technical_language>

Target:
public int deduplicate(String crawlId, String batchId) throws Exception { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); long start = System.currentTimeMillis(); LOG.info("DeduplicatorJob: starting at {}", sdf.format(start)); if (batchId.equals(Nutch.ALL_BATCH_ID_STR)) { LOG.info("DeduplicatorJob: deduplicating all"); } else { LOG.info("DeduplicatorJob: batchId: {}", batchId); } run(ToolUtil.toArgMap(Nutch.ARG_CRAWL, crawlId, Nutch.ARG_BATCH, batchId)); long finish = System.currentTimeMillis(); LOG.info("DeduplicatorJob: finished at {}, time elapsed: {}", sdf.format(finish), TimingUtil.elapsedTime(start, finish)); return 0; }
Source:
<code>public static boolean isMoeFile(IResource resource) { if(resource instanceof IFile ) { <START> String fileExtension = resource.getFileExtension(); return fileExtension != null && resource.getFileExtension().equals(MODEL_OBJECT_ELEMENTFILE_EXTENSION); <END> } return false; }</code><technical_language>replace this new code MODEL_OBJECT_ELEMENTFILE_EXTENSION.equals(resource.getFileExtension())</technical_language>

Target:
public static boolean isMoeFile(IResource resource) { return resource instanceof IFile && MODEL_OBJECT_ELEMENTFILE_EXTENSION.equals(resource.getFileExtension()); }
Source:
<code>public void testCloseConnectionWrapperFor() throws NamingException, SQLException { expectedException.expect(SQLException.class); <START> expectedException.expectMessage("IJ031041: Connection handle has been closed and is unusable"); <END> DataSourceBean bean = (DataSourceBean)ctx.lookup("java:module/" + DataSourceBean.class.getSimpleName()); DataSource ds = bean.getDataSource(); Connection c = ds.getConnection(); c.close(); try { c.isWrapperFor(ResultSet.class); }catch (NullPointerException e){ Assert.fail("Wrong exception is raised. The exception should be Connection is not associated with a managed connection: ... See JBJCA-1389."); } }</code><technical_language>check for message id, fail if is e.g. German locale</technical_language>

Target:
public void testCloseConnectionWrapperFor() throws NamingException, SQLException { expectedException.expect(SQLException.class); expectedException.expectMessage("IJ031041"); DataSourceBean bean = (DataSourceBean)ctx.lookup("java:module/" + DataSourceBean.class.getSimpleName()); DataSource ds = bean.getDataSource(); Connection c = ds.getConnection(); c.close(); try { c.isWrapperFor(ResultSet.class); } catch (NullPointerException e) { Assert.fail("Wrong exception is raised. The exception should be Connection is not associated with a managed connection: ... See JBJCA-1389."); } }
Source:
<code>public void __renderPage() { mDeckListAdapter.buildDeckList(mDueTree, getCol()); try { int eta = mDeckListAdapter.getEta(); int due = mDeckListAdapter.getDue(); <START> Resources res = getResources(); <END> if (getCol().cardCount() != -1) { String time = "-"; if (eta != -1) { time = Utils.timeQuantity(AnkiDroidApp.getInstance(), eta*60); } if (getSupportActionBar() != null) { getSupportActionBar().setSubtitle(res.getQuantityString(R.plurals.deckpicker_title, due, due, time)); } } } catch (RuntimeException e) { Timber.e(e, "RuntimeException setting time remaining"); } long current = getCol().getDecks().current().optLong("id"); if (mFocusedDeck != current) { scrollDecklistToDeck(current); mFocusedDeck = current; } }</code><technical_language>I worry this work activity restarts, mDueTree null saved/restored in onSaveInstance/onCreate (which do is unbounded data Bundle for Activity save/restore finite size). I a null check for mDueTree if null forego optimization call updateDeckList return Related, conditions mDueTree *should* invalidated is not? analysis updateDeckList overwrite necessary, worth a triple check agree</technical_language>

Target:
public void __renderPage() { if (mDueTree == null) { updateDeckList(); return; } mDeckListAdapter.buildDeckList(mDueTree, getCol()); try { int eta = mDeckListAdapter.getEta(); int due = mDeckListAdapter.getDue(); Resources res = getResources(); if (getCol().cardCount() != -1) { String time = "-"; if (eta != -1) { time = Utils.timeQuantity(AnkiDroidApp.getInstance(), eta*60); } if (getSupportActionBar() != null) { getSupportActionBar().setSubtitle(res.getQuantityString(R.plurals.deckpicker_title, due, due, time)); } } } catch (RuntimeException e) { Timber.e(e, "RuntimeException setting time remaining"); } long current = getCol().getDecks().current().optLong("id"); if (mFocusedDeck != current) { scrollDecklistToDeck(current); mFocusedDeck = current; } }
Source:
<code>public ManagementAgent(@NonNull SingletonResource<CorfuRuntime> runtimeSingletonResource, @NonNull ServerContext serverContext, @NonNull ClusterStateContext clusterContext, @NonNull FailureDetector failureDetector, Layout managementLayout) { this.runtimeSingletonResource = runtimeSingletonResource; this.serverContext = serverContext; this.localMonitoringService = new LocalMonitoringService(serverContext, runtimeSingletonResource); if (managementLayout == null) { recovered = true; } serverContext.installSingleNodeLayoutIfAbsent(); serverContext.saveManagementLayout(serverContext.getCurrentLayout()); serverContext.saveManagementLayout(managementLayout); if (!recovered) { log.info("Attempting to recover. Layout before shutdown: {}", managementLayout); } this.remoteMonitoringService = new RemoteMonitoringService( serverContext, runtimeSingletonResource, clusterContext, failureDetector, localMonitoringService ); <START> <END> this.autoCommitService = new AutoCommitService(serverContext, runtimeSingletonResource); this.initializationTaskThread = new Thread(this::initializationTask, "initializationTaskThread"); this.initializationTaskThread.setUncaughtExceptionHandler( (thread, throwable) -> { log.error("Error in initialization task: {}", throwable); shutdown(); }); this.initializationTaskThread.start(); }</code><technical_language>I description of Management Agent class reflect runs auto-commit service</technical_language>

Target:
ManagementAgent(@NonNull SingletonResource<CorfuRuntime> runtimeSingletonResource, @NonNull ServerContext serverContext, @NonNull ClusterStateContext clusterContext, @NonNull FailureDetector failureDetector, Layout managementLayout) { this.runtimeSingletonResource = runtimeSingletonResource; this.serverContext = serverContext; this.localMonitoringService = new LocalMonitoringService(serverContext, runtimeSingletonResource); if (managementLayout == null) { recovered = true; } serverContext.installSingleNodeLayoutIfAbsent(); serverContext.saveManagementLayout(serverContext.getCurrentLayout()); serverContext.saveManagementLayout(managementLayout); if (!recovered) { log.info("Attempting to recover. Layout before shutdown: {}", managementLayout); } this.remoteMonitoringService = new RemoteMonitoringService( serverContext, runtimeSingletonResource, clusterContext, failureDetector, localMonitoringService ); this.autoCommitService = new AutoCommitService(serverContext, runtimeSingletonResource); this.initializationTaskThread = new Thread(this::initializationTask, "initializationTaskThread"); this.initializationTaskThread.setUncaughtExceptionHandler( (thread, throwable) -> { log.error("Error in initialization task: {}", throwable); shutdown(); }); this.initializationTaskThread.start(); }
Source:
<code>public boolean nextBoolean() throws IOException { requirePeek(); boolean value; try { <START> value = parser.getBooleanValue(); <END> } catch (JsonParseException e) { value = Boolean.parseBoolean(parser.getValueAsString()); } clearPeek(); return value; }</code><technical_language>parser.getCurrentToken() detect JSON type</technical_language>

Target:
public boolean nextBoolean() throws IOException { requirePeek(); boolean value = parser.getBooleanValue(); clearPeek(); return value; }
Source:
<code>private <T> void sendResultToOrigin(final LongKeyOperation<T> operation) { try (final TraceScope traceScope = Trace.startSpan("SEND_REMOTE_RESULT")) { final String dataType = operation.getDataType(); final Codec codec = serializer.getCodec(dataType); final Optional<String> origEvalId = operation.getOrigEvalId(); final Map<Long, T> outputData = operation.getOutputData(); final List<UnitIdPair> dataKVPairList; if (operation.getOperationType() == DataOpType.GET || operation.getOperationType() == DataOpType.REMOVE) { <START> dataKVPairList = new LinkedList<>(); <END> for (final Map.Entry<Long, T> dataKVPair : outputData.entrySet()) { final ByteBuffer encodedData = ByteBuffer.wrap(codec.encode(dataKVPair.getValue())); dataKVPairList.add(new UnitIdPair(encodedData, dataKVPair.getKey())); } } else { dataKVPairList = Collections.EMPTY_LIST; } msgSender.get().sendRemoteOpResultMsg(origEvalId.get(), dataKVPairList, operation.getFailedRanges(), operation.getOperationId(), TraceInfo.fromSpan(traceScope.getSpan())); } }</code><technical_language>size set outputData.size()</technical_language>

Target:
private <T> void sendResultToOrigin(final LongKeyOperation<T> operation) { try (final TraceScope traceScope = Trace.startSpan("SEND_REMOTE_RESULT")) { final String dataType = operation.getDataType(); final Codec codec = serializer.getCodec(dataType); final Optional<String> origEvalId = operation.getOrigEvalId(); final Map<Long, T> outputData = operation.getOutputData(); final List<UnitIdPair> dataKVPairList; if (operation.getOperationType() == DataOpType.GET || operation.getOperationType() == DataOpType.REMOVE) { dataKVPairList = new ArrayList<>(outputData.size()); for (final Map.Entry<Long, T> dataKVPair : outputData.entrySet()) { final ByteBuffer encodedData = ByteBuffer.wrap(codec.encode(dataKVPair.getValue())); dataKVPairList.add(new UnitIdPair(encodedData, dataKVPair.getKey())); } } else { dataKVPairList = Collections.EMPTY_LIST; } msgSender.get().sendRemoteOpResultMsg(origEvalId.get(), dataKVPairList, operation.getFailedRanges(), operation.getOperationId(), TraceInfo.fromSpan(traceScope.getSpan())); } }
Source:
<code>public void onResponseReceived(Request req, Response res) { int status = res.getStatusCode(); if (status == Response.SC_NO_CONTENT) { cb.onSuccess(null); if (!background) { RpcStatus.INSTANCE.onRpcComplete(); } } else if (200 <= status && status < 300) { T data; if (isTextBody(res)) { data = NativeString.wrap(res.getText()).cast(); <START> res.getText(); <END> } else if (isJsonBody(res)) { try { data = RestApi.<T>cast(parseJson(res)); } catch (JSONException e) { if (!background) { RpcStatus.INSTANCE.onRpcComplete(); } cb.onFailure(new StatusCodeException(SC_BAD_RESPONSE, "Invalid JSON: " + e.getMessage())); return; } } else { if (!background) { RpcStatus.INSTANCE.onRpcComplete(); } cb.onFailure(new StatusCodeException(SC_BAD_RESPONSE, "Expected " + JSON_TYPE + " or " + TEXT_TYPE + "; received Content-Type: " + res.getHeader("Content-Type"))); return; } cb.onSuccess(data); if (!background) { RpcStatus.INSTANCE.onRpcComplete(); } } else { String msg; if (isTextBody(res)) { msg = res.getText().trim(); } else if (isJsonBody(res)) { JSONValue v; try { v = parseJson(res); } catch (JSONException e) { v = null; } if (v != null && v.isString() != null) { msg = v.isString().stringValue(); } else { msg = trimJsonMagic(res.getText()).trim(); } } else { msg = res.getStatusText(); } if (!background) { RpcStatus.INSTANCE.onRpcComplete(); } cb.onFailure(new StatusCodeException(status, msg)); } }</code><technical_language>Bad merge? This get sense own</technical_language>

Target:
public void onResponseReceived(Request req, Response res) { int status = res.getStatusCode(); if (status == Response.SC_NO_CONTENT) { cb.onSuccess(null); if (!background) { RpcStatus.INSTANCE.onRpcComplete(); } } else if (200 <= status && status < 300) { T data; if (isTextBody(res)) { data = NativeString.wrap(res.getText()).cast(); } else if (isJsonBody(res)) { try { data = RestApi.<T>cast(parseJson(res)); } catch (JSONException e) { if (!background) { RpcStatus.INSTANCE.onRpcComplete(); } cb.onFailure(new StatusCodeException(SC_BAD_RESPONSE, "Invalid JSON: " + e.getMessage())); return; } } else { if (!background) { RpcStatus.INSTANCE.onRpcComplete(); } cb.onFailure(new StatusCodeException(SC_BAD_RESPONSE, "Expected " + JSON_TYPE + " or " + TEXT_TYPE + "; received Content-Type: " + res.getHeader("Content-Type"))); return; } cb.onSuccess(data); if (!background) { RpcStatus.INSTANCE.onRpcComplete(); } } else { String msg; if (isTextBody(res)) { msg = res.getText().trim(); } else if (isJsonBody(res)) { JSONValue v; try { v = parseJson(res); } catch (JSONException e) { v = null; } if (v != null && v.isString() != null) { msg = v.isString().stringValue(); } else { msg = trimJsonMagic(res.getText()).trim(); } } else { msg = res.getStatusText(); } if (!background) { RpcStatus.INSTANCE.onRpcComplete(); } cb.onFailure(new StatusCodeException(status, msg)); } }
Source:
<code>public void testDBConnectionTimeMetrics() { <START> metrics.setDBConnectionTime(14); <END> assertEquals(14, testUtil.getGaugeValue("dbConnectionTime")); }</code><technical_language>apply saveaction</technical_language>

Target:
public void testDBConnectionTimeMetrics() { this.metrics.setDBConnectionTime(14); assertEquals(14, this.testUtil.getGaugeValue("dbConnectionTime")); }
Source:
<code>public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { super.write(ctx, msg, promise); final NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler); <START> final boolean isMsg = msg instanceof Request; <END> promise.addListener(future -> { if (future.isSuccess()) { try { handler.sent(channel, msg); } finally { NettyChannel.removeChannelIfDisconnected(ctx.channel()); } return; } Throwable t = future.cause(); if (t != null && isMsg) { Request request = (Request) msg; Response response = new Response(request.getId(), request.getVersion()); response.setStatus(Response.BAD_REQUEST); response.setErrorMessage(StringUtils.toString(t)); handler.received(channel, response); } }); }</code><technical_language>name 'isRequest'</technical_language>

Target:
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { super.write(ctx, msg, promise); final NettyChannel channel = NettyChannel.getOrAddChannel(ctx.channel(), url, handler); final boolean isRequest = msg instanceof Request; promise.addListener(future -> { try { if (future.isSuccess()) { handler.sent(channel, msg); return; } Throwable t = future.cause(); if (t != null && isRequest) { Request request = (Request) msg; Response response = buildErrorResponse(request, t); handler.received(channel, response); } } finally { NettyChannel.removeChannelIfDisconnected(ctx.channel()); } }); }
Source:
<code>public void onMinecartPass(EntityMinecart cart) { if (powered && cart.canBeRidden() && cart.riddenByEntity == null && cart.getEntityData().getInteger("MountPrevention") <= 0) { int a = area; double x = getPos().getX(); double y = getPos().getY(); double z = getPos().getZ(); <START> AxisAlignedBB box = AxisAlignedBB.fromBounds(x, y, z, x + 1, y + 1, z + 1); <END> box = box.expand(a, a, a); List<EntityLivingBase> entities = getWorld().getEntitiesWithinAABB(EntityLivingBase.class, box); if (entities.size() > 0) { EntityLivingBase entity = entities.get(MiscTools.RANDOM.nextInt(entities.size())); if (entity instanceof EntityPlayer) { EntityPlayer player = (EntityPlayer) entity; if (player.isSneaking()) { return; } ItemStack current = player.getCurrentEquippedItem(); if (current != null && current.getItem() instanceof IToolCrowbar) { return; } } else if (excludedEntities.contains(entity.getClass())) { return; } else if (entity instanceof EntitySlime) { EntitySlime slime = (EntitySlime) entity; if (slime.getSlimeSize() >= 100) return; } if (entity.ridingEntity == null) { EffectManager.instance.teleportEffect(entity, cart.posX, cart.posY, cart.posZ); entity.mountEntity(cart); } } } }</code><technical_language>Todo: Replace this crap a AABBFactory</technical_language>

Target:
public void onMinecartPass(EntityMinecart cart) { if (powered && cart.canBeRidden() && cart.riddenByEntity == null && cart.getEntityData().getInteger("MountPrevention") <= 0) { int a = area; AxisAlignedBB box = AABBFactory.make().createBoxForTileAt(getPos()).build(); box = box.expand(a, a, a); List<EntityLivingBase> entities = getWorld().getEntitiesWithinAABB(EntityLivingBase.class, box); if (entities.size() > 0) { EntityLivingBase entity = entities.get(MiscTools.RANDOM.nextInt(entities.size())); if (entity instanceof EntityPlayer) { EntityPlayer player = (EntityPlayer) entity; if (player.isSneaking()) { return; } ItemStack current = player.getCurrentEquippedItem(); if (current != null && current.getItem() instanceof IToolCrowbar) { return; } } else if (excludedEntities.contains(entity.getClass())) { return; } else if (entity instanceof EntitySlime) { EntitySlime slime = (EntitySlime) entity; if (slime.getSlimeSize() >= 100) return; } if (entity.ridingEntity == null) { EffectManager.instance.teleportEffect(entity, cart.posX, cart.posY, cart.posZ); entity.mountEntity(cart); } } } }
Source:
<code>public long transferTo(final long count, final ByteBuffer throughBuffer, final StreamSinkChannel target) throws IOException { long cnt; <START> final ByteBuffer src; <END> try { src = pooledBuffer.getResource(); final int pos = src.position(); final int rem = src.remaining(); if (rem > count) try { src.limit(pos + (int) count); int res = target.write(src); if(res == 0) { throughBuffer.clear(); Buffers.copy(throughBuffer, src); throughBuffer.flip(); } return res; } finally { src.limit(pos + rem); } else { cnt = target.write(src); if (cnt == rem) { current = next; pooledBuffer.free(); } else { if (cnt == 0) { throughBuffer.clear(); Buffers.copy(throughBuffer, src); throughBuffer.flip(); } return cnt; } } } catch (IllegalStateException ignored) { current = next; cnt = 0L; } final long res = next.transferTo(count - cnt, throughBuffer, target); return res > 0L ? cnt + res : cnt > 0L ? cnt : res; }</code><technical_language>buffer is cleared cleared filled exit path</technical_language>

Target:
public long transferTo(final long count, final ByteBuffer throughBuffer, final StreamSinkChannel target) throws IOException { long cnt; final ByteBuffer src; try { src = pooledBuffer.getResource(); final int pos = src.position(); final int rem = src.remaining(); if (rem > count) try { src.limit(pos + (int) count); int res = target.write(src); if(res == 0) { throughBuffer.clear(); Buffers.copy(throughBuffer, src); throughBuffer.flip(); } else { throughBuffer.clear(); throughBuffer.flip(); } return res; } finally { src.limit(pos + rem); } else { cnt = target.write(src); if (cnt == rem) { current = next; pooledBuffer.free(); } else { if (cnt == 0) { throughBuffer.clear(); Buffers.copy(throughBuffer, src); throughBuffer.flip(); } else { throughBuffer.clear(); throughBuffer.flip(); } return cnt; } } } catch (IllegalStateException ignored) { current = next; cnt = 0L; } final long res = next.transferTo(count - cnt, throughBuffer, target); return res > 0L ? cnt + res : cnt > 0L ? cnt : res; }
Source:
<code>public VmDevice addSoundDevice(VmBase vmBase, Supplier<Cluster> clusterSupplier) { ChipsetType chipset = EmulatedMachineUtils.getEffectiveChipset(vmBase, clusterSupplier); <START> if (vmBase instanceof VmTemplate) { return addSoundDevice(vmBase.getId(), vmBase.getOsId(), CompatibilityVersionUtils.getEffective((VmBase) null, clusterSupplier), chipset); } return addSoundDevice(vmBase.getId(), vmBase.getOsId(), clusterUtils.getCompatibilityVersion(vmBase), chipset); <END> }</code><technical_language>compute compatibility version differently a single call addSoundDevice</technical_language>

Target:
public VmDevice addSoundDevice(VmBase vmBase, Supplier<Cluster> clusterSupplier) { ChipsetType chipset = EmulatedMachineUtils.getEffectiveChipset(vmBase, clusterSupplier); Version compatibilityVersion = vmBase instanceof VmTemplate ? CompatibilityVersionUtils.getEffective((VmBase) null, clusterSupplier) : clusterUtils.getCompatibilityVersion(vmBase); return addSoundDevice(vmBase.getId(), vmBase.getOsId(), compatibilityVersion, chipset); }
Source:
<code><START> public static ConsoleProfileFinished fromJson(JsonInput input) { <END> String id = input.nextString(); Location location = null; Profile profile = null; String title = null; while (input.hasNext()) { switch (input.nextName()) { case "location": location = Location.fronJson(input); break; case "profile": profile = Profile.fromJson(input); break; case "title": title = input.nextString(); break; default: input.skipValue(); break; } } return new ConsoleProfileFinished(id, location, profile, title); }</code><technical_language>fromJson private work expected</technical_language>

Target:
private static ConsoleProfileFinished fromJson(JsonInput input) { String id = input.nextString(); Location location = null; Profile profile = null; String title = null; while (input.hasNext()) { switch (input.nextName()) { case "location": location = Location.fromJson(input); break; case "profile": profile = Profile.fromJson(input); break; case "title": title = input.nextString(); break; default: input.skipValue(); break; } } return new ConsoleProfileFinished(id, location, profile, title); }
Source:
<code>public Result<Void> deleteStorage(final String id) { try { transactionTemplate.execute(action -> { storageDbRepository.deleteStorage(id); return null; }); <START> } catch (final NoStorageException e) { <END> return Result.notFound("No storage with ID " + id); } catch (final StorageIsUsedException e) { return Result.forbidden("Storage " + id + " is in use"); } catch (final RepositoryProblemException e) { LOG.error("DB error occurred when deleting storage", e); return Result.problem(Problem.valueOf(INTERNAL_SERVER_ERROR, e.getMessage())); } catch (final TransactionException e) { LOG.error("Error with transaction handling when deleting storage", e); return Result.problem(Problem.valueOf(INTERNAL_SERVER_ERROR, "Transaction error occurred when deleting storage")); } return Result.ok(); }</code><technical_language>Do continue exceptions refactoring started in repository level throw exceptions controller level catching exception handling mechanism</technical_language>

Target:
public Result<Void> deleteStorage(final String id) { try { storageDbRepository.deleteStorage(id); } catch (final NoStorageException e) { return Result.notFound("No storage with ID " + id); } catch (final StorageIsUsedException e) { return Result.forbidden("Storage " + id + " is in use"); } catch (final RepositoryProblemException e) { LOG.error("DB error occurred when deleting storage", e); return Result.problem(Problem.valueOf(INTERNAL_SERVER_ERROR, e.getMessage())); } catch (final TransactionException e) { LOG.error("Error with transaction handling when deleting storage", e); return Result.problem(Problem.valueOf(INTERNAL_SERVER_ERROR, "Transaction error occurred when deleting storage")); } return Result.ok(); }
Source:
<code>protected File mergeQueryableIndex( final List<QueryableIndex> indexes, final AggregatorFactory[] aggs, final File file, ProgressIndicator progressIndicator ) throws IOException { if (config.isBuildV9Directly()) { return HadoopDruidIndexerConfig.INDEX_MERGER_V9.mergeQueryableIndex( <START> indexes, config.getSchema().getDataSchema().isRollup(), aggs, file, config.getIndexSpec(), progressIndicator <END> ); } else { return HadoopDruidIndexerConfig.INDEX_MERGER.mergeQueryableIndex( indexes, config.getSchema().getDataSchema().isRollup(), aggs, file, config.getIndexSpec(), progressIndicator ); } }</code><technical_language>rollup a part of indexSpec</technical_language>

Target:
protected File mergeQueryableIndex( final List<QueryableIndex> indexes, final AggregatorFactory[] aggs, final File file, ProgressIndicator progressIndicator ) throws IOException { boolean rollup = config.getSchema().getDataSchema().getGranularitySpec().isRollup(); if (config.isBuildV9Directly()) { return HadoopDruidIndexerConfig.INDEX_MERGER_V9.mergeQueryableIndex( indexes, rollup, aggs, file, config.getIndexSpec(), progressIndicator ); } else { return HadoopDruidIndexerConfig.INDEX_MERGER.mergeQueryableIndex( indexes, rollup, aggs, file, config.getIndexSpec(), progressIndicator ); } }
Source:
<code>public CreateNewWikiPage selectCategory(int categoryId) { if (wikiCategoryList.isEmpty()) { throw new WebDriverException("No categories to choose from"); } if (wikiCategoryList.size() < categoryId + 1) { <START> throw new WebDriverException("Cannot find a categpory with this index"); <END> } scrollTo(wikiCategoryDropdown); wait.forElementClickable(wikiCategoryDropdown); WebElement selectedCategory; try { selectedCategory = wikiCategoryList.get(categoryId); } catch (ArrayIndexOutOfBoundsException e) { Log.log("selectCategory", "There is no category with index " + categoryId, false); throw new WebDriverException("There is no category with index " + categoryId, e); } hover(wikiCategoryDropdown); wait.forElementClickable(selectedCategory); selectedCategory.click(); Log.log("selectCategory", "selected " + selectedCategory.getText() + " category", true, driver); return this; }</code><technical_language>Typo</technical_language>

Target:
public CreateNewWikiPage selectCategory(int categoryId) { if (wikiCategoryList.isEmpty()) { throw new WebDriverException("No categories to choose from"); } if (wikiCategoryList.size() < categoryId + 1) { throw new WebDriverException("Cannot find a category with this index"); } scrollTo(wikiCategoryDropdown); wait.forElementClickable(wikiCategoryDropdown); WebElement selectedCategory; try { selectedCategory = wikiCategoryList.get(categoryId); } catch (ArrayIndexOutOfBoundsException e) { Log.log("selectCategory", "There is no category with index " + categoryId, false); throw new WebDriverException("There is no category with index " + categoryId, e); } hover(wikiCategoryDropdown); wait.forElementClickable(selectedCategory); selectedCategory.click(); Log.log("selectCategory", "selected " + selectedCategory.getText() + " category", true, driver); return this; }
Source:
<code>public void createFHIRCondition_shouldReturnCreatedFHIRCondition() { Condition condition = new Condition(); String uuid = "75f5b373-5065-11de-80cb-001e378eb67f"; IdType id = new IdType(); id.setValue(uuid); condition.setId(id); <START> Patient patientRef = Context.getPatientService().getPatient(2); <END> Reference patient = FHIRUtils.buildPatientOrPersonResourceReference(patientRef); condition.setSubject(patient); condition.setClinicalStatus(Condition.ConditionClinicalStatus.ACTIVE); condition.setCode(new CodeableConcept().addCoding( new Coding().setCode("999").setDisplay("NO").setSystem(FHIRConstants.OPENMRS_URI)).setText("NO")); Condition resCondition = getService().createFHIRCondition(condition); assertNotNull(resCondition); assertEquals(resCondition.getId(), id.getValue()); assertEquals(resCondition.getSubject().getReference(), patient.getReference()); assertEquals(resCondition.getCode().getCoding().get(0).getDisplay(), "NO"); }</code><technical_language>a naming conventions for constants? <LINK_0></technical_language>

Target:
public void createFHIRCondition_shouldReturnCreatedFHIRCondition() { Condition condition = new Condition(); IdType id = new IdType(); id.setValue(CONDITION_UUID); condition.setId(id); Patient patientRef = Context.getPatientService().getPatient(2); Reference patient = FHIRUtils.buildPatientOrPersonResourceReference(patientRef); condition.setSubject(patient); condition.setClinicalStatus(Condition.ConditionClinicalStatus.ACTIVE); condition.setCode(new CodeableConcept().addCoding( new Coding().setCode("999").setDisplay("NO").setSystem(FHIRConstants.OPENMRS_URI)).setText("NO")); Condition resCondition = getService().createFHIRCondition(condition); assertNotNull(resCondition); assertEquals(resCondition.getId(), id.getValue()); assertEquals(resCondition.getSubject().getReference(), patient.getReference()); assertEquals(resCondition.getCode().getCoding().get(0).getDisplay(), "NO"); }
Source:
<code>public ByteBuffer getAndRelease() { <START> return buffer; <END> }</code><technical_language>if this is supposed "release" buffer, buffer field set null</technical_language>

Target:
public ByteBuffer getAndRelease() { try { return buffer; } finally { buffer = null; } }
Source:
<code>public V get(final K key) throws CacheLoaderException { final Function<K, V> mappingFunction = memoize( new Function<K, V>() { @Override public V apply(final K k) { V loaded = null; try { if (cacheLoader != null) { loaded = cacheLoader.load(k); } } catch (RuntimeException e) { throw new CacheLoaderException(e); } return loaded; } }); try { final Store.ValueHolder<V> valueHolder = store.computeIfAbsent(key, mappingFunction); return valueHolder == null ? null : valueHolder.value(); } catch (CacheAccessException e) { try { store.remove(key); resilienceStrategy.recoveredFrom(key, e); } catch (CacheAccessException e1) { resilienceStrategy.possiblyInconsistent(key, e1, e); } <START> return mappingFunction.apply(key); <END> } }</code><technical_language>Is this final attempt load value? want do this inconsistent condition is detected above? missing some context..</technical_language>

Target:
public V get(final K key) throws CacheLoaderException { checkNonNull(key); final Function<K, V> mappingFunction = memoize( new Function<K, V>() { @Override public V apply(final K k) { V loaded = null; try { if (cacheLoader != null) { loaded = cacheLoader.load(k); } } catch (RuntimeException e) { throw new CacheLoaderException(e); } return loaded; } }); try { final Store.ValueHolder<V> valueHolder = store.computeIfAbsent(key, mappingFunction); return valueHolder == null ? null : valueHolder.value(); } catch (CacheAccessException e) { try { store.remove(key); resilienceStrategy.recoveredFrom(key, e); } catch (CacheAccessException e1) { resilienceStrategy.possiblyInconsistent(key, e1, e); } return mappingFunction.apply(key); } }
Source:
<code>public void addContents(@NonNull Container container, FileListCap fileListCap) { synchronized (fileListCap) { File[] files = Preconditions.checkNotNull(fileListCap.getFolder().listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith(".txt"); } })); <START> for (File f : Util.fixNull(Arrays.asList(files))) { <END> container.add(new FileContent(fileListCap.getFolder().getName() + "/" + f.getName(), f, MAX_FILE_SIZE)); } } }</code><technical_language>call Util.fixNull is bogus here. null return of listFiles, _element_ of return value</technical_language>

Target:
public void addContents(@NonNull Container container, FileListCap fileListCap) { synchronized (fileListCap) { final Collection<File> files = FileUtils.listFiles( fileListCap.getFolder(), new String[] {"txt"}, false); for (File f : files) { container.add(new FileContent(fileListCap.getFolder().getName() + "/" + f.getName(), f, MAX_FILE_SIZE)); } } }
Source:
<code>public static String getPluginVersion() { <START> final String pluginVersion = ComponentAccessor.getPluginAccessor() <END> .getPlugin("org.everit.jira.timetracker.plugin") .getPluginInformation().getVersion(); return pluginVersion; }</code><technical_language>Remove of unnecessary final modifier local variables of modified classes</technical_language>

Target:
public static String getPluginVersion() { String pluginVersion = ComponentAccessor.getPluginAccessor() .getPlugin("org.everit.jira.timetracker.plugin") .getPluginInformation().getVersion(); return pluginVersion; }
Source:
<code>public Operation resume(RunContext run) throws WorldEditException { while (!blocks.isEmpty()) { BlockVector3 current = blocks.iterator().next(); if (!blocks.contains(current)) { continue; } final Deque<BlockVector3> walked = new LinkedList<>(); while (true) { walked.addFirst(current); assert (blockTypes.containsKey(current)); final BlockStateHolder blockStateHolder = blockTypes.get(current); if (BlockCategories.DOORS.contains(blockStateHolder.getBlockType())) { Property<Object> halfProperty = blockStateHolder.getBlockType().getProperty("half"); if (blockStateHolder.getState(halfProperty).equals("lower")) { BlockVector3 upperBlock = current.add(0, 1, 0); if (blocks.contains(upperBlock) && !walked.contains(upperBlock)) { walked.addFirst(upperBlock); } } } else if (BlockCategories.RAILS.contains(blockStateHolder.getBlockType())) { BlockVector3 lowerBlock = current.add(0, -1, 0); if (blocks.contains(lowerBlock) && !walked.contains(lowerBlock)) { walked.addFirst(lowerBlock); } } if (!blockStateHolder.getBlockType().getMaterial().isFragileWhenPushed()) { break; } if (walked.contains(current)) { break; } } for (BlockVector3 pt : walked) { extent.setBlock(pt, blockTypes.get(pt)); blocks.remove(pt); } } <START> if (blocks.isEmpty()) { <END> for (LocatedBlockList stage : stages) { stage.clear(); } return null; } return this; }</code><technical_language>Is this in preparation for multiple-tick operations? I this false, break for outer while loop above</technical_language>

Target:
public Operation resume(RunContext run) throws WorldEditException { while (!blocks.isEmpty()) { BlockVector3 current = blocks.iterator().next(); final Deque<BlockVector3> walked = new LinkedList<>(); while (true) { walked.addFirst(current); assert (blockTypes.containsKey(current)); final BlockStateHolder blockStateHolder = blockTypes.get(current); if (BlockCategories.DOORS.contains(blockStateHolder.getBlockType())) { Property<Object> halfProperty = blockStateHolder.getBlockType().getProperty("half"); if (blockStateHolder.getState(halfProperty).equals("lower")) { BlockVector3 upperBlock = current.add(0, 1, 0); if (blocks.contains(upperBlock) && !walked.contains(upperBlock)) { walked.addFirst(upperBlock); } } } else if (BlockCategories.RAILS.contains(blockStateHolder.getBlockType())) { BlockVector3 lowerBlock = current.add(0, -1, 0); if (blocks.contains(lowerBlock) && !walked.contains(lowerBlock)) { walked.addFirst(lowerBlock); } } if (!blockStateHolder.getBlockType().getMaterial().isFragileWhenPushed()) { break; } if (walked.contains(current)) { break; } } for (BlockVector3 pt : walked) { extent.setBlock(pt, blockTypes.get(pt)); blocks.remove(pt); } } for (LocatedBlockList stage : stages.values()) { stage.clear(); } return null; }
Source:
<code>public SimpleTextFormatter get(int i) { <START> return partitions[i]; <END> }</code><technical_language>this</technical_language>

Target:
public SimpleTextFormatter get(int i) { return this.partitions[i]; }
Source:
<code>protected boolean executeAnalysis(final IProgressMonitor monitor) { final ITmfStateProvider htInput = createStateProvider(); if (htInput == null) { return false; } try { StateSystemBackend backend = getBackend(); switch (backend) { case FULL: case PARTIAL: String directory = TmfTraceManager.getSupplementaryFileDir(getTrace()); <START> final File htFile = new File(directory + getSsFileName()); <END> if (backend.equals(StateSystemBackend.FULL)) { fStateSystem = TmfStateSystemFactory.newFullHistory(htFile, htInput, true); } else { fStateSystem = TmfStateSystemFactory.newPartialHistory(htFile, htInput, true); } break; case INMEM: fStateSystem = TmfStateSystemFactory.newInMemHistory(htInput, true); break; case NULL: fStateSystem = TmfStateSystemFactory.newNullHistory(htInput); break; default: break; } } catch (TmfTraceException e) { return false; } return true; }</code><technical_language>repeat lines in case, remove if below, easier understand flow</technical_language>

Target:
protected boolean executeAnalysis(final IProgressMonitor monitor) { final ITmfStateProvider htInput = createStateProvider(); try { StateSystemBackendType backend = getBackendType(); String directory; switch (backend) { case FULL: directory = TmfTraceManager.getSupplementaryFileDir(getTrace()); final File htFile = new File(directory + getSsFileName()); fStateSystem = TmfStateSystemFactory.newFullHistory(htFile, htInput, true); break; case PARTIAL: directory = TmfTraceManager.getSupplementaryFileDir(getTrace()); final File htPartialFile = new File(directory + getSsFileName()); fStateSystem = TmfStateSystemFactory.newPartialHistory(htPartialFile, htInput, true); break; case INMEM: fStateSystem = TmfStateSystemFactory.newInMemHistory(htInput, true); break; case NULL: fStateSystem = TmfStateSystemFactory.newNullHistory(htInput); break; default: break; } } catch (TmfTraceException e) { return false; } return true; }
Source:
<code>private void handleGetAuthorizationCodeResponse(Intent intent) { AuthorizationResponse authorizationResponse = AuthorizationResponse.fromIntent(intent); AuthorizationException authorizationException = AuthorizationException.fromIntent(intent); if (authorizationResponse != null && authorizationResponse.authorizationCode != null) { exchangeAuthorizationCodeForTokens(authorizationResponse); } else if (authorizationException != null) { updateOAuthStatusIconAndText(authorizationException); showAuthStatus(); <START> Timber.d("OAuth request to get authorization code failed: %s", authorizationException.error); <END> } }</code><technical_language>Timber.e log exceptions</technical_language>

Target:
private void handleGetAuthorizationCodeResponse(Intent intent) { AuthorizationResponse authorizationResponse = AuthorizationResponse.fromIntent(intent); AuthorizationException authorizationException = AuthorizationException.fromIntent(intent); if (authorizationResponse != null && authorizationResponse.authorizationCode != null) { exchangeAuthorizationCodeForTokens(authorizationResponse); } else if (authorizationException != null) { updateOAuthStatusIconAndText(authorizationException); showAuthStatus(); Timber.e(authorizationException, "OAuth request to get authorization code failed"); } }
Source:
<code>public void setSocketAddresses(List<InetSocketAddress> addresses) { <START> List<PhysicalAddress> list = new ArrayList<>(); <END> for (InetSocketAddress address : addresses) { IpAddress ipAddress = new IpAddress(address.getAddress(), address.getPort()); list.add(ipAddress); } this.setInitialHosts(list); }</code><technical_language>ArrayList constructed fixed capacity</technical_language>

Target:
public void setSocketAddresses(List<InetSocketAddress> addresses) { List<PhysicalAddress> list = new ArrayList<>(addresses.size()); for (InetSocketAddress address : addresses) { IpAddress ipAddress = new IpAddress(address.getAddress(), address.getPort()); list.add(ipAddress); } this.setInitialHosts(list); }
Source:
<code>static MethodMatcher levelTestMatcher(String typeDefinition, String level) { return MethodMatcher.create() .typeDefinition(typeDefinition) <START> .name(String.format("is%c%sEnabled", level.charAt(0), level.toLowerCase(Locale.ROOT).substring(2))) <END> .withoutParameter(); }</code><technical_language>substring(2) ? INFO, get isIfoEnabled..</technical_language>

Target:
private static MethodMatcher levelTestMatcher(String typeDefinition, String level) { return MethodMatcher.create() .typeDefinition(typeDefinition) .name(String.format("is%c%sEnabled", level.charAt(0), level.toLowerCase(Locale.ROOT).substring(1))) .withoutParameter(); }
Source:
<code>public void test() { connect(); <START> sleep(600); <END> Assert.assertEquals("false", getZKLog()); }</code><technical_language>waitResponse()</technical_language>

Target:
public void test() { connect(); waitResponse(); Assert.assertEquals("false", getZKLog()); }