auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testGetIntentContainsSkipCacheAndClaimsForBrokerActivity() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); sThreadExecutor.execute(new Runnable() { @Override public void run() { final String claimsChallenge = "testClaims"; final AuthenticationRequest authRequest = createAuthenticationRequest("<LINK_0>", "resource", "client", "redirect", "loginhint", PromptBehavior.Auto, "", UUID.randomUUID(), false); authRequest.setClaimsChallenge(claimsChallenge); final Context context = getMockContext(); final BrokerProxy brokerProxy = new BrokerProxy(context); final BrokerEvent brokerEvent = new BrokerEvent(EventStrings.BROKER_REQUEST_SILENT); Telemetry.getInstance().flush("1234"); brokerEvent.setRequestId("1234"); Telemetry.getInstance().startEvent(brokerEvent.getTelemetryRequestId(), EventStrings.BROKER_REQUEST_INTERACTIVE); try { final Intent intent = brokerProxy.getIntentForBrokerActivity(authRequest, brokerEvent); assertTrue(Boolean.toString(true).equals(intent.getStringExtra(AuthenticationConstants.Broker.BROKER_SKIP_CACHE))); assertTrue(claimsChallenge.equals(intent.getStringExtra(AuthenticationConstants.Broker.ACCOUNT_CLAIMS))); } catch (final AuthenticationException exc) { <START> fail("Exception ia not expected."); <END> } verifyBrokerEventList(brokerEvent); latch.countDown(); } }); latch.await(); }</code><technical_language>nit: spelling of is</technical_language>

Target:
public void testGetIntentContainsSkipCacheAndClaimsForBrokerActivity() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); sThreadExecutor.execute(new Runnable() { @Override public void run() { final String claimsChallenge = "testClaims"; final AuthenticationRequest authRequest = createAuthenticationRequest("<LINK_0>", "resource", "client", "redirect", "loginhint", PromptBehavior.Auto, "", UUID.randomUUID(), false); authRequest.setClaimsChallenge(claimsChallenge); final Context context = getMockContext(); final BrokerProxy brokerProxy = new BrokerProxy(context); final BrokerEvent brokerEvent = new BrokerEvent(EventStrings.BROKER_REQUEST_SILENT); Telemetry.getInstance().flush("1234"); brokerEvent.setRequestId("1234"); Telemetry.getInstance().startEvent(brokerEvent.getTelemetryRequestId(), EventStrings.BROKER_REQUEST_INTERACTIVE); try { final Intent intent = brokerProxy.getIntentForBrokerActivity(authRequest, brokerEvent); assertTrue(Boolean.toString(true).equals(intent.getStringExtra(AuthenticationConstants.Broker.BROKER_SKIP_CACHE))); assertTrue(claimsChallenge.equals(intent.getStringExtra(AuthenticationConstants.Broker.ACCOUNT_CLAIMS))); } catch (final AuthenticationException exc) { fail("Exception is not expected."); } verifyBrokerEventList(brokerEvent); latch.countDown(); } }); latch.await(); }
Source:
<code>return (Response) reply; } }; <START> public static Supplier<String> DEFAULT_CORRELATION_ID_GENERATOR = new IncrementingCorrelationIdGenerator(""); <END> private final Function<Object, Response> _replyHandler; private final Map<String, BlockingCell<Object>> _continuationMap = new HashMap<String, BlockingCell<Object>>(); private final Supplier<String> _correlationIdGenerator; private DefaultConsumer _consumer; public RpcClient(RpcClientParams params) throws IOException { _channel = params.getChannel(); _exchange = params.getExchange(); _routingKey = params.getRoutingKey(); _replyTo = params.getReplyTo(); if (params.getTimeout() < NO_TIMEOUT) { throw new IllegalArgumentException("Timeout argument must be NO_TIMEOUT(-1) or non-negative."); } _timeout = params.getTimeout(); _useMandatory = params.shouldUseMandatory(); _replyHandler = params.getReplyHandler(); _correlationIdGenerator = params.getCorrelationIdGenerator(); _consumer = setupConsumer(); if (_useMandatory) { this._channel.addReturnListener(returnMessage -> { synchronized (_continuationMap) { String replyId = returnMessage.getProperties().getCorrelationId(); BlockingCell<Object> blocker = _continuationMap.remove(replyId); if (blocker == null) { LOGGER.warn("No outstanding request for correlation ID {}", replyId); } else { blocker.set(new UnroutableRpcRequestException(returnMessage)); } } }); } }</code><technical_language>As-is this static instance more RpcClient instance. In case Supplier#get invoked concurrently, synchronized (_continuationMap) block ensures exclusive access for doCall invocations client. This is a problem as-is IncrementingCorrelationIdGenerator is thread-safe. option replace int _correlationId AtomicInteger (or more appropriately, AtomicLong.)</technical_language>

Target:
return (Response) reply; } }; private final Function<Object, Response> _replyHandler; private final Map<String, BlockingCell<Object>> _continuationMap = new HashMap<String, BlockingCell<Object>>(); private final Supplier<String> _correlationIdGenerator; private DefaultConsumer _consumer; public RpcClient(RpcClientParams params) throws IOException { _channel = params.getChannel(); _exchange = params.getExchange(); _routingKey = params.getRoutingKey(); _replyTo = params.getReplyTo(); if (params.getTimeout() < NO_TIMEOUT) { throw new IllegalArgumentException("Timeout argument must be NO_TIMEOUT(-1) or non-negative."); } _timeout = params.getTimeout(); _useMandatory = params.shouldUseMandatory(); _replyHandler = params.getReplyHandler(); _correlationIdGenerator = params.getCorrelationIdGenerator(); _consumer = setupConsumer(); if (_useMandatory) { this._channel.addReturnListener(returnMessage -> { synchronized (_continuationMap) { String replyId = returnMessage.getProperties().getCorrelationId(); BlockingCell<Object> blocker = _continuationMap.remove(replyId); if (blocker == null) { LOGGER.warn("No outstanding request for correlation ID {}", replyId); } else { blocker.set(new UnroutableRpcRequestException(returnMessage)); } } }); } }
Source:
<code>public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) { long totalHits = response.getHits().getTotalHits(); float maxScore = response.getHits().getMaxScore(); List<T> results = new ArrayList<>(); for (SearchHit hit : response.getHits()) { if (hit != null) { <START> T result = mapSearchHit(hit, clazz); <END> setPersistentEntityId(result, hit.getId(), clazz); setPersistentEntityVersion(result, hit.getVersion(), clazz); setPersistentEntityScore(result, hit.getScore(), clazz); populateScriptFields(result, hit); results.add(result); } } return new AggregatedPageImpl<T>(results, pageable, totalHits, response.getAggregations(), response.getScrollId(), maxScore); }</code><technical_language>mapSearchHit returns @Nullable I a check here</technical_language>

Target:
public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) { long totalHits = SearchHitsUtil.getTotalCount(response.getHits()); float maxScore = response.getHits().getMaxScore(); List<T> results = new ArrayList<>(); for (SearchHit hit : response.getHits()) { if (hit != null) { T result = mapSearchHit(hit, clazz); setPersistentEntityId(result, hit.getId(), clazz); setPersistentEntityVersion(result, hit.getVersion(), clazz); setPersistentEntityScore(result, hit.getScore(), clazz); populateScriptFields(result, hit); results.add(result); } } return new AggregatedPageImpl<T>(results, pageable, totalHits, response.getAggregations(), response.getScrollId(), maxScore); }
Source:
<code>public Coin parse(String str) throws NumberFormatException { checkArgument(str.length() > 0); char first = str.charAt(0); if (first == negativeSign || first == positiveSign) str = str.substring(1); String numbers; String decimals; int decimalMarkIndex = str.indexOf(decimalMark); if (decimalMarkIndex != -1) { numbers = str.substring(0, decimalMarkIndex); <START> decimals = (str + "00000000").substring(decimalMarkIndex + 1); <END> if (decimals.indexOf(decimalMark) != -1) throw new NumberFormatException("more than one decimal mark"); } else { numbers = str; decimals = "00000000"; } String satoshis = numbers + decimals.substring(0, 8 - shift); for (char c : satoshis.toCharArray()) if (!Character.isDigit(c)) throw new NumberFormatException("illegal character: " + c); Coin coin = Coin.valueOf(Long.parseLong(satoshis)); if (first == negativeSign) coin = coin.negate(); return coin; }</code><technical_language>I if this sort of generalised a bit for alt coins, assumption of 8 decimal places hard coded</technical_language>

Target:
public Coin parse(String str) throws NumberFormatException { checkState(DECIMALS_PADDING.length() >= Coin.NUM_COIN_DECIMALS); if (str.isEmpty()) throw new NumberFormatException("empty string"); char first = str.charAt(0); if (first == negativeSign || first == positiveSign) str = str.substring(1); String numbers; String decimals; int decimalMarkIndex = str.indexOf(decimalMark); if (decimalMarkIndex != -1) { numbers = str.substring(0, decimalMarkIndex); decimals = (str + DECIMALS_PADDING).substring(decimalMarkIndex + 1); if (decimals.indexOf(decimalMark) != -1) throw new NumberFormatException("more than one decimal mark"); } else { numbers = str; decimals = DECIMALS_PADDING; } String satoshis = numbers + decimals.substring(0, Coin.NUM_COIN_DECIMALS - shift); for (char c : satoshis.toCharArray()) if (!Character.isDigit(c)) throw new NumberFormatException("illegal character: " + c); Coin coin = Coin.valueOf(Long.parseLong(satoshis)); if (first == negativeSign) coin = coin.negate(); return coin; }
Source:
<code>public void cleaningCompensationDataAfterSuccess() { log.debug("Command successfully executed, releasing macs: {}" + macsToReleaseOnCommit); <START> macsToReleaseOnCommit.forEach(macPool::freeMac); this.macsToReleaseOnCommit.clear(); <END> }</code><technical_language>this unrelated this patch</technical_language>

Target:
public void cleaningCompensationDataAfterSuccess() { log.debug("Command successfully executed, releasing macs: {}" + macsToReleaseOnCommit); macsToReleaseOnCommit.forEach(macPool::freeMac); }
Source:
<code>private void mapProject(final IProject source, final IProjectDescription description, final IProgressMonitor monitor, IPath gitDir) throws CoreException, TeamException { IProject destination = source.getWorkspace().getRoot() .getProject(description.getName()); RepositoryMapping repositoryMapping = RepositoryMapping.create(destination, gitDir.toFile()); <START> SubMonitor subMonitor = SubMonitor.convert(monitor, 50); <END> if (repositoryMapping != null) { GitProjectData projectData = new GitProjectData(destination); projectData.setRepositoryMappings(Arrays.asList(repositoryMapping)); projectData.store(); GitProjectData.add(destination, projectData); RepositoryProvider.map(destination, GitProvider.class.getName()); destination.refreshLocal(IResource.DEPTH_INFINITE, subMonitor.newChild(50)); } }</code><technical_language>Actually, this correct. Please convert SubMonitor in callers, pass monitor here. A SubMonitor consumes monitor. In this case work (sort of) mapProject() is called moveProject(), proper</technical_language>

Target:
private void mapProject(final IProject source, final IProjectDescription description, final IProgressMonitor monitor, IPath gitDir) throws CoreException, TeamException { IProject destination = source.getWorkspace().getRoot() .getProject(description.getName()); RepositoryMapping repositoryMapping = RepositoryMapping.create(destination, gitDir.toFile()); if (repositoryMapping != null) { GitProjectData projectData = new GitProjectData(destination); projectData.setRepositoryMappings(Arrays.asList(repositoryMapping)); projectData.store(); GitProjectData.add(destination, projectData); RepositoryProvider.map(destination, GitProvider.class.getName()); destination.refreshLocal(IResource.DEPTH_INFINITE, monitor); } }
Source:
<code><START> private AttributeMapping(String searchDn, boolean recursiveSearch, String filter, String ldapName, String name, String rdn, int recursiveDepth) { <END> this.searchDn = searchDn; this.recursiveSearch = recursiveSearch; this.filter = filter; this.ldapName = ldapName; this.name = name; this.rdn = rdn; this.recursiveDepth = recursiveDepth; }</code><technical_language>This package-private referenced a nested class; if private, javac generate a "bridge" constructor method is package-private. a mistake package-private referenced type, if access is technically allowed JLS</technical_language>

Target:
AttributeMapping(String searchDn, boolean recursiveSearch, String filter, String ldapName, String name, String rdn, int recursiveDepth) { this.searchDn = searchDn; this.recursiveSearch = recursiveSearch; this.filter = filter; this.ldapName = ldapName; this.name = name; this.rdn = rdn; this.recursiveDepth = recursiveDepth; }
Source:
<code>public void createControl(Composite parent) { Composite composite= new Composite(parent, SWT.NONE); GridLayout gd= new GridLayout(); gd.numColumns= 2; composite.setLayout(gd); Label label= new Label(composite, SWT.LEFT); label.setText(fNameLabel); label.setLayoutData(new GridData()); fTextControl= new Text(composite, SWT.SINGLE | SWT.BORDER); fTextControl.setText(fProjectName); fTextControl.setSelection(fProjectName.length()); fTextControl.addModifyListener(new ModifyListener() { <START> @Override public void modifyText(ModifyEvent e) { if (!fTextControl.isDisposed()) { validateText(fTextControl.getText()); } } <END> }); fTextControl.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); fTextControl.setFocus(); setControl(composite); Dialog.applyDialogFont(composite); validateText(fProjectName); }</code><technical_language>lambda, if it</technical_language>

Target:
public void createControl(Composite parent) { Composite composite= new Composite(parent, SWT.NONE); GridLayout gd= new GridLayout(); gd.numColumns= 2; composite.setLayout(gd); Label label= new Label(composite, SWT.LEFT); label.setText(fNameLabel); label.setLayoutData(new GridData()); fTextControl= new Text(composite, SWT.SINGLE | SWT.BORDER); fTextControl.setText(fProjectName); fTextControl.setSelection(fProjectName.length()); fTextControl.addModifyListener(e -> { if (!fTextControl.isDisposed()) { validateText(fTextControl.getText()); } }); fTextControl.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); fTextControl.setFocus(); setControl(composite); Dialog.applyDialogFont(composite); validateText(fProjectName); }
Source:
<code>private void addAuthorizationForUser(String userName, String resourceId, String action, short allow, boolean updateCache) throws UserStoreException { authorizationCache.clearCacheByTenant(this.tenantId); Connection dbConnection = null; PreparedStatement prepStmt = null; try { dbConnection = getDBConnection(); int permissionId = this.getPermissionId(dbConnection, resourceId, action); if (permissionId == -1) { this.addPermissionId(dbConnection, resourceId, action); permissionId = this.getPermissionId(dbConnection, resourceId, action); } DatabaseUtil.updateDatabase(dbConnection, DBConstants.DELETE_USER_PERMISSION_SQL, userName, resourceId, action, tenantId, tenantId); DatabaseUtil.updateDatabase(dbConnection, DBConstants.ADD_USER_PERMISSION_SQL, permissionId, userName, allow, tenantId); if(updateCache){ if (allow == UserCoreConstants.ALLOW) { permissionTree.authorizeUserInTree(userName, resourceId, action, true); } else { permissionTree.denyUserInTree(userName, resourceId, action, true); authorizationCache.clearCacheEntry(cacheIdentifier, tenantId, userName, resourceId, action); } } dbConnection.commit(); } catch (Exception e) { try { if (dbConnection != null) { dbConnection.rollback(); } } catch (SQLException e1) { <START> throw new UserStoreException("Error in connection rollback " + e1.getMessage(), e1); <END> } log.error("Error! " + e.getMessage(), e); throw new UserStoreException("Error! " + e.getMessage(), e); } finally { DatabaseUtil.closeAllConnections(dbConnection, prepStmt); } }</code><technical_language>need append e1.getMessage(), is logged e1</technical_language>

Target:
private void addAuthorizationForUser(String userName, String resourceId, String action, short allow, boolean updateCache) throws UserStoreException { authorizationCache.clearCacheByTenant(this.tenantId); Connection dbConnection = null; PreparedStatement prepStmt = null; try { dbConnection = getDBConnection(); int permissionId = this.getPermissionId(dbConnection, resourceId, action); if (permissionId == -1) { this.addPermissionId(dbConnection, resourceId, action); permissionId = this.getPermissionId(dbConnection, resourceId, action); } DatabaseUtil.updateDatabase(dbConnection, DBConstants.DELETE_USER_PERMISSION_SQL, userName, resourceId, action, tenantId, tenantId); DatabaseUtil.updateDatabase(dbConnection, DBConstants.ADD_USER_PERMISSION_SQL, permissionId, userName, allow, tenantId); if(updateCache){ if (allow == UserCoreConstants.ALLOW) { permissionTree.authorizeUserInTree(userName, resourceId, action, true); } else { permissionTree.denyUserInTree(userName, resourceId, action, true); authorizationCache.clearCacheEntry(cacheIdentifier, tenantId, userName, resourceId, action); } } dbConnection.commit(); } catch (Exception e) { try { if (dbConnection != null) { dbConnection.rollback(); } } catch (SQLException e1) { throw new UserStoreException("Error in connection rollback ", e1); } log.error("Error! " + e.getMessage(), e); throw new UserStoreException("Error! " + e.getMessage(), e); } finally { DatabaseUtil.closeAllConnections(dbConnection, prepStmt); } }
Source:
<code>public Block copyPositions(int[] positions, int offset, int length) { <START> checkValidPositionsArray(positions, offset, length); <END> int finalLength = stream(positions, offset, offset + length) .map(this::getSliceLength) .sum(); SliceOutput newSlice = Slices.allocate(finalLength).getOutput(); int[] newOffsets = new int[length + 1]; boolean[] newValueIsNull = new boolean[length]; for (int i = 0; i < length; i++) { int position = positions[offset + i]; if (isEntryNull(position)) { newValueIsNull[i] = true; } else { newSlice.appendBytes(slice.getBytes(getPositionOffset(position), getSliceLength(position))); } newOffsets[i + 1] = newSlice.size(); } return new VariableWidthBlock(length, newSlice.slice(), newOffsets, newValueIsNull); }</code><technical_language>missing checkValidPosition(positionCount, position); below</technical_language>

Target:
public Block copyPositions(int[] positions, int offset, int length) { checkArrayRange(positions, offset, length); int finalLength = stream(positions, offset, offset + length) .map(this::getSliceLength) .sum(); SliceOutput newSlice = Slices.allocate(finalLength).getOutput(); int[] newOffsets = new int[length + 1]; boolean[] newValueIsNull = new boolean[length]; for (int i = 0; i < length; i++) { int position = positions[offset + i]; if (isEntryNull(position)) { newValueIsNull[i] = true; } else { newSlice.appendBytes(slice.getBytes(getPositionOffset(position), getSliceLength(position))); } newOffsets[i + 1] = newSlice.size(); } return new VariableWidthBlock(length, newSlice.slice(), newOffsets, newValueIsNull); }
Source:
<code>public static void onBlockBreak(PlayerInteractEvent.LeftClickBlock event) { if(!event.getEntity().world.isRemote && getData(event.getPlayer()) != null) { EditData data = getData(event.getPlayer()); if(!MinestuckConfig.gristRefund.get()) { GristHelper.notifyEditPlayer(event.getWorld().getServer(), data.connection.getClientIdentifier(), new GristSet(GristTypes.BUILD, 1), false); <START> GristHelper.decrease(event.getWorld(), data.connection.getClientIdentifier(), new GristSet(GristTypes.BUILD,1)); <END> } else { BlockState block = event.getWorld().getBlockState(event.getPos()); ItemStack stack = block.getBlock().getPickBlock(block, null, event.getWorld(), event.getPos(), event.getPlayer()); GristSet set = GristCostRecipe.findCostForItem(stack, null, false, event.getWorld()); if(set != null && !set.isEmpty()) GristHelper.increase(event.getWorld(), data.connection.getClientIdentifier(), set); GristHelper.notifyEditPlayer(event.getWorld().getServer(), data.connection.getClientIdentifier(), new GristSet(GristTypes.BUILD, 1), true); } } }</code><technical_language>suggest calling decrease notify</technical_language>

Target:
public static void onBlockBreak(PlayerInteractEvent.LeftClickBlock event) { if(!event.getEntity().world.isRemote && getData(event.getPlayer()) != null) { EditData data = getData(event.getPlayer()); if(!MinestuckConfig.gristRefund.get()) { GristHelper.decrease(event.getWorld(), data.connection.getClientIdentifier(), new GristSet(GristTypes.BUILD,1)); GristHelper.notifyEditPlayer(event.getWorld().getServer(), data.connection.getClientIdentifier(), new GristSet(GristTypes.BUILD, 1), false); } else { BlockState block = event.getWorld().getBlockState(event.getPos()); ItemStack stack = block.getBlock().getPickBlock(block, null, event.getWorld(), event.getPos(), event.getPlayer()); GristSet set = GristCostRecipe.findCostForItem(stack, null, false, event.getWorld()); if(set != null && !set.isEmpty()) GristHelper.increase(event.getWorld(), data.connection.getClientIdentifier(), set); GristHelper.notifyEditPlayer(event.getWorld().getServer(), data.connection.getClientIdentifier(), new GristSet(GristTypes.BUILD, 1), true); } } }
Source:
<code>public void start(StartAction action) throws DebuggerException { try { for (Breakpoint breakpoint : action.getBreakpoints()) { Location location = breakpoint.getLocation(); library.setBreakpoint(location.getTarget(), location.getLineNumber()); <START> debuggerCallback.onEvent(new BreakpointActivatedEventImpl(breakpoint)); <END> pendingBreakpoints.add(location); } debuggerCallback.onEvent(new SuspendEventImpl(library.backtrace())); checkActivatedBreakpoints(); } catch (NodeJsDebuggerTerminatedException e) { disconnect(); throw e; } catch (NodeJsDebuggerException e) { throw new DebuggerException("Start error. " + e.getMessage(), e); } }</code><technical_language>send BreakpointActivatedEventImpl immediately delegate this checkActivatedBreakpoints method</technical_language>

Target:
public void start(StartAction action) throws DebuggerException { try { for (Breakpoint breakpoint : action.getBreakpoints()) { Location location = breakpoint.getLocation(); library.setBreakpoint(location.getTarget(), location.getLineNumber()); debuggerCallback.onEvent(new BreakpointActivatedEventImpl(breakpoint)); } debuggerCallback.onEvent(new SuspendEventImpl(library.backtrace())); } catch (NodeJsDebuggerTerminatedException e) { disconnect(); throw e; } catch (NodeJsDebuggerException e) { throw new DebuggerException("Start error. " + e.getMessage(), e); } }
Source:
<code>public void setupOpticalDuplicateFinder() { <START> this.opticalDuplicateFinder = new OpticalDuplicateFinder(READ_NAME_REGEX, OPTICAL_DUPLICATE_PIXEL_DISTANCE, LOG); <END> opticalDuplicateFinder.setMaxDuplicateSetSize(MAX_OPTICAL_DUPLICATE_SET_SIZE); }</code><technical_language>this is of this constructor in picard source. this new setting added another argument constructor, instead of a setter</technical_language>

Target:
public void setupOpticalDuplicateFinder() { this.opticalDuplicateFinder = new OpticalDuplicateFinder(READ_NAME_REGEX, OPTICAL_DUPLICATE_PIXEL_DISTANCE, MAX_OPTICAL_DUPLICATE_SET_SIZE, LOG); }
Source:
<code>private void visitClass( PersistenceUnitModel persistenceUnit, NodeList nodes ) { <START> List<PersistableDataObject> persistableDataObjectList = new ArrayList<PersistableDataObject>(); <END> parseSimpleTextElementList(nodes).forEach(node -> { persistableDataObjectList.add(new PersistableDataObject(node)); }); persistenceUnit.setClasses(persistableDataObjectList); }</code><technical_language>a functional style parseSimpleTextElementList(nodes).stream.map.collect(toList)</technical_language>

Target:
private void visitClass(PersistenceUnitModel persistenceUnit, NodeList nodes) { persistenceUnit.setClasses(parseSimpleTextElementList(nodes).stream().map(p -> new PersistableDataObject(p)).collect(Collectors.toList())); }
Source:
<code>public Map<String, Ref> filter(Map<String, Ref> refs) { final Set<Change.Id> visibleChanges = visibleChanges(); final Map<String, Ref> result = new HashMap<String, Ref>(); final List<Ref> deferredTags = new ArrayList<Ref>(); for (Ref ref : refs.values()) { if (PatchSet.isRef(ref.getName())) { if (visibleChanges.contains(Change.Id.fromRef(ref.getName()))) { result.put(ref.getName(), ref); } } else if (isTag(ref)) { deferredTags.add(ref); } else if (projectCtl.controlForRef(ref.getLeaf().getName()).isVisible()) { result.put(ref.getName(), ref); } } if (!deferredTags.isEmpty() && !result.isEmpty()) { Map<Ref, List<Ref>> reachableTags = tagCache.get(db); <START> for (Ref tag : reachableTags.keySet()) { <END> for (Ref ref : reachableTags.get(tag)) { if (projectCtl.controlForRef(ref.getName()).isVisible()) { result.put(tag.getName(), tag); break; } } } } return result; }</code><technical_language>Instead of this loop I deferredTags above: for (Ref tag : deferredTags) { List<Ref> reachableFrom = reachableTags.get(tag.getObjectId()); if (reachableFrom == null && !updated) { // reachableTag data is stale. Try update once. reachableTags = tagCache.update(gitRepo); reachableFrom = reachableTags.get(tag.getObjectId()); } if (reachableFrom == null) { continue; } for (Ref ref : reachableFrom) { This if a tag deleted cache built advertise client. slightly faster current code, iterating ArrayList is faster a HashMap. removes of cache eviction code ReceiveCommits. Performing update cache a new tag is discovered allows server react new tags correctly, matter put repository</technical_language>

Target:
public Map<String, Ref> filter(Map<String, Ref> refs) { try { return doFilter(refs); } finally { if (rw != null) { rw.release(); rw = null; } } }
Source:
<code>protected void onHandleIntent(Intent intent) { try { boolean unkownIntentContent = true; ArrayList<String> eventsExtras = intent.getExtras().getStringArrayList(EXTRA_EVENTS); if (eventsExtras != null) { unkownIntentContent = false; handleSendEvents(eventsExtras); <START> } <END> if (unkownIntentContent) { SwrveLogger.e(LOG_TAG, "SwrveWakefulService: Unknown intent received."); } } catch (Exception ex) { SwrveLogger.e(LOG_TAG, "SwrveWakefulService exception:", ex); } finally { SwrveWakefulReceiver.completeWakefulIntent(intent); } }</code><technical_language>add else block prints error, remove boolean unkownIntentContent</technical_language>

Target:
protected void onHandleIntent(Intent intent) { try { ArrayList<String> eventsExtras = intent.getExtras().getStringArrayList(EXTRA_EVENTS); if (eventsExtras != null && eventsExtras.size() > 0) { handleSendEvents(eventsExtras); } else { SwrveLogger.e(LOG_TAG, "SwrveWakefulService: Unknown intent received."); } } catch (Exception ex) { SwrveLogger.e(LOG_TAG, "SwrveWakefulService exception:", ex); } finally { SwrveWakefulReceiver.completeWakefulIntent(intent); } }
Source:
<code>private static boolean isPositionBefore(final ContentPosition position, final Box box) { <START> return position.getOffset() < box.getStartOffset(); <END> }</code><technical_language>Please ContentPosition.isBefore</technical_language>

Target:
private static boolean isPositionBefore(final ContentPosition position, final Box box) { return position.isBefore(new ContentPosition(box.getNode(), box.getStartOffset())); }
Source:
<code>public void testNonOwnerConnectionClosed_whenHeartbeatStopped() throws InterruptedException { hazelcastFactory.newHazelcastInstance(); HazelcastInstance client = hazelcastFactory.newHazelcastClient(getClientConfig()); HazelcastInstance instance = hazelcastFactory.newHazelcastInstance(); HazelcastClientInstanceImpl clientImpl = getHazelcastClientInstanceImpl(client); final ClientConnectionManager connectionManager = clientImpl.getConnectionManager(); assertTrueEventually(new AssertTask() { @Override public void run() throws Exception { assertEquals(2, connectionManager.getActiveConnections().size()); } }); final CountDownLatch countDownLatch = new CountDownLatch(1); connectionManager.addConnectionListener(new ConnectionListener() { @Override public void connectionAdded(Connection connection) { } @Override public void connectionRemoved(Connection connection) { <START> countDownLatch.countDown(); <END> } }); blockMessagesFromInstance(instance, client); assertOpenEventually(countDownLatch); }</code><technical_language>I check this is non-owner connection, you</technical_language>

Target:
public void testNonOwnerConnectionClosed_whenHeartbeatStopped() { hazelcastFactory.newHazelcastInstance(); final HazelcastInstance client = hazelcastFactory.newHazelcastClient(getClientConfig()); HazelcastInstance instance = hazelcastFactory.newHazelcastInstance(); HazelcastClientInstanceImpl clientImpl = getHazelcastClientInstanceImpl(client); final ClientConnectionManager connectionManager = clientImpl.getConnectionManager(); assertTrueEventually(new AssertTask() { @Override public void run() throws Exception { assertEquals(2, connectionManager.getActiveConnections().size()); } }); final CountDownLatch countDownLatch = new CountDownLatch(1); connectionManager.addConnectionListener(new ConnectionListener() { @Override public void connectionAdded(Connection connection) { } @Override public void connectionRemoved(Connection connection) { ClientConnection clientConnection = (ClientConnection) connection; if (!clientConnection.isAuthenticatedAsOwner()) { countDownLatch.countDown(); } } }); blockMessagesFromInstance(instance, client); assertOpenEventually(countDownLatch); }
Source:
<code>public <T> T getAdapter(Object adaptableObject, Class<T> adapterType) { if (adapterType.equals(ICSourceNotFoundDescription.class) && adaptableObject instanceof IFrameDMContext) { final IFrameDMContext frameDMC = (IFrameDMContext) adaptableObject; return (T) new ICSourceNotFoundDescription() { @Override public String getDescription() { <START> ICSourceNotFoundDescription frameDescription = createQuery(); if(frameDescription != null) return frameDescription.getDescription(); return frameDMC.toString(); <END> } @Override public boolean isAddress() { ICSourceNotFoundDescription frameDescription = createQuery(); if(frameDescription != null) return frameDescription.isAddress(); return false; } private ICSourceNotFoundDescription createQuery() { Query<IStack.IFrameDMData> query = new Query<IStack.IFrameDMData>() { @Override protected void execute(DataRequestMonitor<IStack.IFrameDMData> rm) { DsfServicesTracker tracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), frameDMC.getSessionId()); IStack stack = tracker.getService(IStack.class); if (stack != null) { stack.getFrameData(frameDMC, rm); } else { rm.setData(null); rm.done(); } tracker.dispose(); } }; DsfSession session = DsfSession.getSession(frameDMC.getSessionId()); if (session != null && session.getExecutor() != null) { session.getExecutor().execute(query); try { IFrameDMData dmData = query.get(); return getFrameDescription(dmData); } catch (Exception e) { return null; } } return null; } }; } return null; }</code><technical_language>suggestion this becomes: return createQuery().getDescription();</technical_language>

Target:
public <T> T getAdapter(Object adaptableObject, Class<T> adapterType) { if (adapterType.equals(ICSourceNotFoundDescription.class) && adaptableObject instanceof IFrameDMContext) { final IFrameDMContext frameDMC = (IFrameDMContext) adaptableObject; return (T) new ICSourceNotFoundDescription() { @Override public String getDescription() { return createQuery().getDescription(); } @Override public boolean isAddressOnly() { return createQuery().isAddressOnly(); } private ICSourceNotFoundDescription createQuery() { Query<IStack.IFrameDMData> query = new Query<IStack.IFrameDMData>() { @Override protected void execute(DataRequestMonitor<IStack.IFrameDMData> rm) { DsfServicesTracker tracker = new DsfServicesTracker(DsfUIPlugin.getBundleContext(), frameDMC.getSessionId()); IStack stack = tracker.getService(IStack.class); if (stack != null) { stack.getFrameData(frameDMC, rm); } else { rm.setData(null); rm.done(); } tracker.dispose(); } }; DsfSession session = DsfSession.getSession(frameDMC.getSessionId()); if (session != null && session.getExecutor() != null) { session.getExecutor().execute(query); try { IFrameDMData dmData = query.get(); return getFrameDescription(dmData); } catch (Exception e) { } } return new ICSourceNotFoundDescription() { @Override public String getDescription() { return frameDMC.toString(); } }; } }; } return null; }
Source:
<code>public void shutdown() { if (config.getTelemetryConfig().isTelemetryEnabled()) { Optional<Metric> optional = metrics.getMetric(BlockDestroyedMetric.class); if (optional.isPresent()) { Metric blockDestroyedMetric = optional.get(); Unstructured unstructuredBlockDestroyed = blockDestroyedMetric.getUnstructuredMetric(); TelemetryUtils.trackMetric(emitter, trackerNamespace, unstructuredBlockDestroyed, blockDestroyedMetric, bindingMap); } optional = metrics.getMetric(BlockPlacedMetric.class); if (optional.isPresent()) { Metric blockPlacedMetric = optional.get(); Unstructured unstructuredBlockPlaced = blockPlacedMetric.getUnstructuredMetric(); TelemetryUtils.trackMetric(emitter, trackerNamespace, unstructuredBlockPlaced, blockPlacedMetric, bindingMap); } optional = metrics.getMetric(GameConfigurationMetric.class); if (optional.isPresent()) { Metric gameConfigurationMetric = optional.get(); Unstructured unstructuredGameConfiguration = gameConfigurationMetric.getUnstructuredMetric(); TelemetryUtils.trackMetric(emitter, trackerNamespace, unstructuredGameConfiguration, gameConfigurationMetric, bindingMap); } optional = metrics.getMetric(GamePlayMetric.class); if (optional.isPresent()) { Metric gamePlayMetric = optional.get(); Unstructured unstructuredGamePlay = gamePlayMetric.getUnstructuredMetric(); TelemetryUtils.trackMetric(emitter, trackerNamespace, unstructuredGamePlay, gamePlayMetric, bindingMap); } optional = metrics.getMetric(MonsterKilledMetric.class); if (optional.isPresent()) { Metric monsterKilledMetric = optional.get(); Unstructured unstructuredMonsterKilled = monsterKilledMetric.getUnstructuredMetric(); TelemetryUtils.trackMetric(emitter, trackerNamespace, unstructuredMonsterKilled, monsterKilledMetric, bindingMap); <START> } <END> } }</code><technical_language>I a pattern a lot of copy-paste code ;)</technical_language>

Target:
public void shutdown() { if (config.getTelemetryConfig().isTelemetryEnabled()) { TelemetryUtils.fetchMetricAndSend(metrics, BlockPlacedMetric.class, emitter, trackerNamespace, bindingMap); TelemetryUtils.fetchMetricAndSend(metrics, BlockDestroyedMetric.class, emitter, trackerNamespace, bindingMap); TelemetryUtils.fetchMetricAndSend(metrics, GameConfigurationMetric.class, emitter, trackerNamespace, bindingMap); TelemetryUtils.fetchMetricAndSend(metrics, MonsterKilledMetric.class, emitter, trackerNamespace, bindingMap); TelemetryUtils.fetchMetricAndSend(metrics, GamePlayMetric.class, emitter, trackerNamespace, bindingMap); } }
Source:
<code>private String getUnsatisfiedDependenciesAdditionalInfo(InjectionPoint ij, BeanManagerImpl beanManager) { <START> Set<Bean<?>> beansMatchedByType = beanManager.getBeans(ij.getType()); <END> if (beansMatchedByType.isEmpty()) { Class<?> rawType = Reflections.getRawType(ij.getType()); if (rawType != null) { String missingDependency = beanManager.getMissingDependencyForClass(rawType.getName()); if (missingDependency != null) { return loggerFactory().getMessageConveyor().getMessage( UNSATISFIED_DEPENDENCY_BECAUSE_CLASS_IGNORED, rawType.getName(), missingDependency); } } } else { return loggerFactory().getMessageConveyor().getMessage( UNSATISFIED_DEPENDENCY_BECAUSE_QUALIFIERS_DONT_MATCH, WeldCollections.toMultiRowString(beansMatchedByType)); } return ""; }</code><technical_language>this change Weld suggest a bean matched type if injection point requires specific Qualifier a bean exists type qualifiers. If change getBeans() call add AnyLiteral Weld suggest other combinations injection point qualifiers a bean a qualifier</technical_language>

Target:
private String getUnsatisfiedDependenciesAdditionalInfo(InjectionPoint ij, BeanManagerImpl beanManager) { Set<Bean<?>> beansMatchedByType = beanManager.getBeans(ij.getType(), AnyLiteral.INSTANCE); if (beansMatchedByType.isEmpty()) { Class<?> rawType = Reflections.getRawType(ij.getType()); if (rawType != null) { MissingDependenciesRegistry missingDependenciesRegistry = beanManager.getServices().get(MissingDependenciesRegistry.class); String missingDependency = missingDependenciesRegistry.getMissingDependencyForClass(rawType.getName()); if (missingDependency != null) { return loggerFactory().getMessageConveyor().getMessage( UNSATISFIED_DEPENDENCY_BECAUSE_CLASS_IGNORED, rawType.getName(), missingDependency); } } } else { return loggerFactory().getMessageConveyor().getMessage( UNSATISFIED_DEPENDENCY_BECAUSE_QUALIFIERS_DONT_MATCH, WeldCollections.toMultiRowString(beansMatchedByType)); } return ""; }
Source:
<code>void register() { <START> register(repliedAddress, true, Promise.promise()); <END> }</code><technical_language>pass null allow downstream EventBusImpl#addRegistration passed null, avoid creating a Promise is needed</technical_language>

Target:
void register() { register(repliedAddress, true, null); }
Source:
<code>public TripScheduleImpl ( TripTimes originalTripTimes, TripPattern originalTripPattern, int[] arrivals, int[] departures, int timeShift ) { final int numStops = originalTripTimes.getNumStops(); if (originalTripPattern.getStops().size() != numStops) { LOG.error("TripPattern is not the same size as the TripTimes. This indicates a bug."); } if (arrivals.length != numStops) { LOG.error("Arrivals arrays is not the same size as the TripTimes. This indicates a bug."); } if (departures.length != numStops) { LOG.error("Departures arrays is not the same size as the TripTimes. This indicates a bug."); <START> } <END> this.originalTripTimes = originalTripTimes; this.originalTripPattern = originalTripPattern; this.arrivals = arrivals; this.departures = departures; this.timeShift = timeShift; }</code><technical_language>I this sanity checks, I prefer throw exceptions instead - I find a good reason to, of any. importing data try nice fix poor data, allways able trust correctness of internal model; fail early</technical_language>

Target:
public TripScheduleImpl ( TripTimes originalTripTimes, TripPattern originalTripPattern, int[] arrivals, int[] departures, int timeShift ) { final int numStops = originalTripTimes.getNumStops(); if (originalTripPattern.getStops().size() != numStops) { throw new IllegalStateException( "TripPattern is not the same size as the TripTimes. This indicates a bug." ); } if (arrivals.length != numStops) { throw new IllegalStateException( "Arrivals arrays is not the same size as the TripTimes. This indicates a bug." ); } if (departures.length != numStops) { throw new IllegalStateException( "Departures arrays is not the same size as the TripTimes. This indicates a bug." ); } this.originalTripTimes = originalTripTimes; this.originalTripPattern = originalTripPattern; this.arrivals = arrivals; this.departures = departures; this.timeShift = timeShift; }
Source:
<code>public PatientData<Integer> readJSON(JSONObject json) { if (json == null || json.length() == 0) { return null; } JSONObject data = json.optJSONObject(getJsonPropertyName()); if (data == null || data.length() == 0) { return null; } Map<String, Integer> result = new LinkedHashMap<>(); for (String property : getProperties()) { if (data.has(property)) { int age = data.getInt(property); if (age == 0) { <START> result.put(property, null); <END> } else { result.put(property, age); } } } return new DictionaryPatientData<>(getName(), result); }</code><technical_language>Is a difference age 0 age == null? logically "no age is set", if yes, "null" a indication</technical_language>

Target:
public PatientData<Integer> readJSON(JSONObject json) { if (json == null || json.length() == 0) { return null; } JSONObject data = json.optJSONObject(getJsonPropertyName()); if (data == null || data.length() == 0) { return null; } Map<String, Integer> result = new LinkedHashMap<>(); for (String property : getProperties()) { if (data.has(property)) { int age = data.optInt(property); if (age == 0) { result.put(property, null); } else { result.put(property, age); } } } return new DictionaryPatientData<>(getName(), result); }
Source:
<code>public void startUp(IngestJobContext context) throws IngestModuleException { this.context = context; Extract registry = null; try { registry = new ExtractRegistry(); } catch (FileNotFoundException ex) { <START> Exceptions.printStackTrace(ex); <END> } Extract iexplore = new ExtractIE(); Extract recentDocuments = new RecentDocumentsByLnk(); Extract chrome = new Chrome(); Extract firefox = new Firefox(); Extract SEUQA = new SearchEngineURLQueryAnalyzer(); extracters.add(chrome); extracters.add(firefox); extracters.add(iexplore); extracters.add(recentDocuments); extracters.add(SEUQA); extracters.add(registry); browserExtracters.add(chrome); browserExtracters.add(firefox); browserExtracters.add(iexplore); for (Extract extracter : extracters) { extracter.init(); } }</code><technical_language>This throw IngestModuleExceptions. And, print stack. need log act it</technical_language>

Target:
public void startUp(IngestJobContext context) throws IngestModuleException { this.context = context; Extract registry = new ExtractRegistry(); Extract iexplore = new ExtractIE(); Extract recentDocuments = new RecentDocumentsByLnk(); Extract chrome = new Chrome(); Extract firefox = new Firefox(); Extract SEUQA = new SearchEngineURLQueryAnalyzer(); extracters.add(chrome); extracters.add(firefox); extracters.add(iexplore); extracters.add(recentDocuments); extracters.add(SEUQA); extracters.add(registry); browserExtracters.add(chrome); browserExtracters.add(firefox); browserExtracters.add(iexplore); for (Extract extracter : extracters) { extracter.init(); } }
Source:
<code>public TestNGCucumberRunner(Class clazz) { <START> this.clazz = clazz; <END> classLoader = clazz.getClassLoader(); resourceLoader = new MultiLoader(classLoader); RuntimeOptionsFactory runtimeOptionsFactory = new RuntimeOptionsFactory(clazz, new Class[]{CucumberOptions.class}); runtimeOptions = runtimeOptionsFactory.create(); List<String> uniqueGlue = new ArrayList<String>(new HashSet<String>(runtimeOptions.getGlue())); runtimeOptions.getGlue().clear(); runtimeOptions.getGlue().addAll(uniqueGlue); reporter = new TestNgReporter(System.out); runtimeOptions.getFormatters().add(reporter); classFinder = new ResourceLoaderClassFinder(resourceLoader, classLoader); }</code><technical_language>This line deleted clazz field is used</technical_language>

Target:
public TestNGCucumberRunner(Class clazz) { classLoader = clazz.getClassLoader(); resourceLoader = new MultiLoader(classLoader); RuntimeOptionsFactory runtimeOptionsFactory = new RuntimeOptionsFactory(clazz, new Class[]{CucumberOptions.class}); runtimeOptions = runtimeOptionsFactory.create(); List<String> uniqueGlue = new ArrayList<String>(new HashSet<String>(runtimeOptions.getGlue())); runtimeOptions.getGlue().clear(); runtimeOptions.getGlue().addAll(uniqueGlue); TestNgReporter reporter = new TestNgReporter(System.out); runtimeOptions.getFormatters().add(reporter); classFinder = new ResourceLoaderClassFinder(resourceLoader, classLoader); }
Source:
<code>public ValidationResult isOperationAllowedOnDisk(VdcActionType actionType) { List<DiskContentType> allowedTypes = allowedCommandsOnTypes.get(actionType); if (allowedTypes == null) { throw new IllegalArgumentException( String.format("Cannot validate operation on disk for action of type %s as it is not <START> included in the allowed commands.", <END> actionType)); } if (!allowedTypes.contains(disk.getContentType())) { return new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_DISK_CONTENT_TYPE_NOT_SUPPORTED_FOR_OPERATION, String.format("$diskContentType %s", disk.getContentType())); } return ValidationResult.VALID; }</code><technical_language>Consider replace "an allowed command"</technical_language>

Target:
public ValidationResult isOperationAllowedOnDisk(VdcActionType actionType) { List<DiskContentType> allowedTypes = allowedCommandsOnTypes.get(actionType); if (allowedTypes == null) { throw new IllegalArgumentException( String.format("Cannot validate operation on disk for action of type %s as it is not an allowed commands for the disk content type.", actionType)); } if (!allowedTypes.contains(disk.getContentType())) { return new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_DISK_CONTENT_TYPE_NOT_SUPPORTED_FOR_OPERATION, String.format("$diskContentType %s", disk.getContentType())); } return ValidationResult.VALID; }
Source:
<code>public void verifySemanticException(QualifierType type, String invalidInput) { TurboIssue issue = new TurboIssue(REPO, 1, ""); thrown.expect(SemanticException.class); thrown.expectMessage(String.format(SemanticException.ERR_MSG, type, <START> type.getValidInputs())); <END> matches(invalidInput, issue); }</code><technical_language>Line wrapping better, show nested relationship. e.g. java thrown.expectMessage( String.format(SemanticException.ERR_MSG, type, type.getValidInputs()));</technical_language>

Target:
public void verifySemanticException(QualifierType type, String invalidInput) { TurboIssue issue = new TurboIssue(REPO, 1, ""); thrown.expect(SemanticException.class); thrown.expectMessage( String.format(SemanticException.ERROR_MESSAGE, type, type.getDescriptionOfValidInputs())); matches(invalidInput, issue); }
Source:
<code>public void init(Map<String, String> options) { storeName = options.getOrDefault(STORE_NAME_OPTION, DEFAULT_STORE_NAME); thresholdSize = parseIntOrDefault(options.get(THRESHOLD_SIZE_OPTION), DEFAULT_THRESHOLD_SIZE); <START> storeTTLSeconds = parseIntOrDefault(options.get(STORE_TTL_OPTION), DEFAULT_STORE_TTL); <END> }</code><technical_language>instead a storeTTL option a string parsed DurationUtils, for more readable config. I other places storeTTL is inconsistent</technical_language>

Target:
public void init(Map<String, String> options) { storeName = options.getOrDefault(STORE_NAME_OPTION, DEFAULT_STORE_NAME); thresholdSize = parseIntOrDefault(options.get(THRESHOLD_SIZE_OPTION), DEFAULT_THRESHOLD_SIZE); storeTTL = DurationUtils.parse(options.getOrDefault(STORE_TTL_OPTION, DEFAULT_STORE_TTL)); }
Source:
<code>public void printStackTrace(PrintStream err) { super.printStackTrace(err); int currentIndex = -1; for (Throwable throwable : innerThrowables) { err.append("\n"); <START> err.append(" Inner throwable "); <END> err.append(Integer.toString(++currentIndex)); err.append(") "); throwable.printStackTrace(err); err.append("\n"); } }</code><technical_language>err.append(" throwable #");</technical_language>

Target:
public void printStackTrace(PrintStream err) { super.printStackTrace(err); int currentIndex = -1; for (Throwable throwable : innerThrowables) { err.append("\n"); err.append(" Inner throwable #"); err.append(Integer.toString(++currentIndex)); err.append(": "); throwable.printStackTrace(err); err.append("\n"); } }