auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Vector3f getSpawnPosition(World world, EntityRef clientEntity) { <START> return new Vector3f(0, 65, 252); <END> }</code><technical_language>Magic numbers</technical_language>

Target:
public Vector3f getSpawnPosition(World world, EntityRef clientEntity) { return new Vector3i(LASUtils.FLOATING_PLATFORM_POSITION) .add(0, 5, 0) .toVector3f(); }
Source:
<code>public void uploadSnapshotTest() throws IOException, InterruptedException, ExecutionException{ String currentLiveIndex = getLiveIndex(); esIndexAPI.closeIndex(currentLiveIndex); esIndexAPI.delete(currentLiveIndex); ZipFile file = new ZipFile("test-resources/index.zip"); String pathToRepo = Config.getStringProperty("es.path.repo","test-resources"); File tempDir = new File(pathToRepo); boolean response = esIndexAPI.uploadSnapshot(file, tempDir.getAbsolutePath(), "backup"); <START> assertTrue(response); <END> }</code><technical_language>Nice :)</technical_language>

Target:
public void uploadSnapshotTest() throws IOException, InterruptedException, ExecutionException{ String currentLiveIndex = getLiveIndex(); esIndexAPI.closeIndex(currentLiveIndex); ZipFile file = new ZipFile("test-resources/index.zip"); String pathToRepo = Config.getStringProperty("es.path.repo","test-resources"); File tempDir = new File(pathToRepo); boolean response = esIndexAPI.uploadSnapshot(file, tempDir.getAbsolutePath()); assertTrue(response); }
Source:
<code>public void returnsMultipleSecretsWhenAllowed() throws Exception { SanitizedSecret sanitizedSecret = SanitizedSecret.fromSecret(secret); SanitizedSecret sanitizedSecret2 = SanitizedSecret.fromSecret(secret2); ImmutableList<String> secretnames = ImmutableList.of(sanitizedSecret.name(), sanitizedSecret2.name()); BatchSecretRequest req = BatchSecretRequest.create(secretnames); when(aclDAO.getBatchSanitizedSecretsFor(client, secretnames)) .thenReturn(List.of(sanitizedSecret, sanitizedSecret2)); when(secretController.getSecretsByName(secretnames)) .thenReturn(List.of(secret, secret2)); List<SecretDeliveryResponse> response = batchSecretDeliveryResource.getBatchSecret(client, req); boolean matches = false; <START> if (response.equals(ImmutableList.of(SecretDeliveryResponse.fromSecret(secret), SecretDeliveryResponse.fromSecret(secret2)))) { <END> matches = true; } else if (response.equals(ImmutableList.of(SecretDeliveryResponse.fromSecret(secret2), SecretDeliveryResponse.fromSecret(secret)))) { matches = true; } assertThat(matches).isTrue(); }</code><technical_language>assertThat(list).containsExactlyInAnyOrder(item1, item2, item3...) simplify this</technical_language>

Target:
public void returnsMultipleSecretsWhenAllowed() throws Exception { SanitizedSecret sanitizedSecret = SanitizedSecret.fromSecret(secret); SanitizedSecret sanitizedSecret2 = SanitizedSecret.fromSecret(secret2); ImmutableList<String> secretnames = ImmutableList.of(sanitizedSecret.name(), sanitizedSecret2.name()); BatchSecretRequest req = BatchSecretRequest.create(secretnames); when(aclDAO.getBatchSanitizedSecretsFor(client, secretnames)) .thenReturn(List.of(sanitizedSecret, sanitizedSecret2)); when(clientDAO.getClientByName(client.getName())).thenReturn(Optional.of(client)); when(secretController.getSecretsByName(secretnames)) .thenReturn(List.of(secret, secret2)); List<SecretDeliveryResponse> response = batchSecretDeliveryResource.getBatchSecret(client, req); assertThat(response).containsExactlyInAnyOrder(SecretDeliveryResponse.fromSecret(secret), SecretDeliveryResponse.fromSecret(secret2)); }
Source:
<code>public void testConsumerProperties() throws Exception { Binder<MessageChannel> binder = getBinder(); Properties properties = new Properties(); properties.put("maxAttempts", "1"); Binding<MessageChannel> binding = binder.bindConsumer("props.0", "test", new DirectChannel(), properties); <START> assertEquals(binding, binding); <END> AbstractEndpoint endpoint = extractEndpoint(binding); assertThat(endpoint, instanceOf(RedisQueueMessageDrivenEndpoint.class)); assertSame(DirectChannel.class, TestUtils.getPropertyValue(endpoint, "outputChannel").getClass()); binding.unbind(); assertFalse(extractEndpoint(binding).isRunning()); properties.put("backOffInitialInterval", "2000"); properties.put("backOffMaxInterval", "20000"); properties.put("backOffMultiplier", "5.0"); properties.put("concurrency", "2"); properties.put("maxAttempts", "23"); properties.put("partitionIndex", 0); binding = binder.bindConsumer("props.0", "test", new DirectChannel(), properties); endpoint = extractEndpoint(binding); verifyConsumer(endpoint); binding.unbind(); assertFalse(extractEndpoint(binding).isRunning()); }</code><technical_language>this pointless</technical_language>

Target:
public void testConsumerProperties() throws Exception { Binder<MessageChannel> binder = getBinder(); Properties properties = new Properties(); properties.put("maxAttempts", "1"); Binding<MessageChannel> binding = binder.bindConsumer("props.0", "test", new DirectChannel(), properties); AbstractEndpoint endpoint = extractEndpoint(binding); assertThat(endpoint, instanceOf(RedisQueueMessageDrivenEndpoint.class)); assertSame(DirectChannel.class, TestUtils.getPropertyValue(endpoint, "outputChannel").getClass()); binding.unbind(); assertFalse(endpoint.isRunning()); properties.put("backOffInitialInterval", "2000"); properties.put("backOffMaxInterval", "20000"); properties.put("backOffMultiplier", "5.0"); properties.put("concurrency", "2"); properties.put("maxAttempts", "23"); properties.put("partitionIndex", 0); binding = binder.bindConsumer("props.0", "test", new DirectChannel(), properties); endpoint = extractEndpoint(binding); verifyConsumer(endpoint); binding.unbind(); assertFalse(endpoint.isRunning()); }
Source:
<code>private void showCommonalityDetails() { if (correlationAttributes.isEmpty()) { JOptionPane.showConfirmDialog(showCommonalityMenuItem, Bundle.DataContentViewerOtherCases_correlatedArtifacts_isEmpty(), Bundle.DataContentViewerOtherCases_correlatedArtifacts_title(), DEFAULT_OPTION, PLAIN_MESSAGE); } else { StringBuilder msg = new StringBuilder(correlationAttributes.size()); int percentage; try { EamDb dbManager = EamDb.getInstance(); for (CorrelationAttribute eamArtifact : correlationAttributes) { try { percentage = dbManager.getFrequencyPercentage(eamArtifact); msg.append(Bundle.DataContentViewerOtherCases_correlatedArtifacts_byType(percentage, eamArtifact.getCorrelationType().getDisplayName(), eamArtifact.getCorrelationValue())); } catch (CorrelationAttributeNormalizationException ex) { String message = String.format("Unable to determine commonality for artifact %s", eamArtifact.toString()); LOGGER.log(Level.SEVERE, message, ex); <START> Exceptions.printStackTrace(ex); <END> } } JOptionPane.showConfirmDialog(showCommonalityMenuItem, msg.toString(), Bundle.DataContentViewerOtherCases_correlatedArtifacts_title(), DEFAULT_OPTION, PLAIN_MESSAGE); } catch (EamDbException ex) { LOGGER.log(Level.SEVERE, "Error getting commonality details.", ex); JOptionPane.showConfirmDialog(showCommonalityMenuItem, Bundle.DataContentViewerOtherCases_correlatedArtifacts_failed(), Bundle.DataContentViewerOtherCases_correlatedArtifacts_title(), DEFAULT_OPTION, ERROR_MESSAGE); } } }</code><technical_language>Yeah leave as-is</technical_language>

Target:
private void showCommonalityDetails() { if (correlationAttributes.isEmpty()) { JOptionPane.showConfirmDialog(showCommonalityMenuItem, Bundle.DataContentViewerOtherCases_correlatedArtifacts_isEmpty(), Bundle.DataContentViewerOtherCases_correlatedArtifacts_title(), DEFAULT_OPTION, PLAIN_MESSAGE); } else { StringBuilder msg = new StringBuilder(correlationAttributes.size()); int percentage; try { EamDb dbManager = EamDb.getInstance(); for (CorrelationAttributeInstance eamArtifact : correlationAttributes) { try { percentage = dbManager.getFrequencyPercentage(eamArtifact); msg.append(Bundle.DataContentViewerOtherCases_correlatedArtifacts_byType(percentage, eamArtifact.getCorrelationType().getDisplayName(), eamArtifact.getCorrelationValue())); } catch (CorrelationAttributeNormalizationException ex) { LOGGER.log(Level.WARNING, String.format("Error getting commonality details for artifact with ID: %s.", eamArtifact.getID()), ex); } } JOptionPane.showConfirmDialog(showCommonalityMenuItem, msg.toString(), Bundle.DataContentViewerOtherCases_correlatedArtifacts_title(), DEFAULT_OPTION, PLAIN_MESSAGE); } catch (EamDbException ex) { LOGGER.log(Level.SEVERE, "Error getting commonality details.", ex); JOptionPane.showConfirmDialog(showCommonalityMenuItem, Bundle.DataContentViewerOtherCases_correlatedArtifacts_failed(), Bundle.DataContentViewerOtherCases_correlatedArtifacts_title(), DEFAULT_OPTION, ERROR_MESSAGE); } } }
Source:
<code>private void handleWebSocketHandshake(HttpRequest httpRequest) throws ProtocolException { try { WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory( getWebSocketURL(httpRequest), null, true); handshaker = wsFactory.newHandshaker(httpRequest); handshaker.handshake(ctx.channel(), httpRequest); boolean isSecuredConnection = false; if (listenerConfiguration.getSslConfig() != null) { isSecuredConnection = true; } ChannelPipeline pipeline = ctx.pipeline(); <START> int maxThreads = 15; <END> EventExecutorGroup executorGroup = new DefaultEventExecutorGroup(maxThreads); pipeline.addLast(executorGroup, "ws_handler", new WebSocketSourceHandler(generateWebSocketChannelID(), this.connectionManager, this.listenerConfiguration, httpRequest.getUri(), isSecuredConnection, ctx)); pipeline.remove(this); } catch (Exception e) { ctx.channel().write(new CloseWebSocketFrame(1002, "")); ctx.close(); throw new ProtocolException("Error occurred in HTTP to WebSocket Upgrade."); } }</code><technical_language>this configurable</technical_language>

Target:
private void handleWebSocketHandshake(HttpRequest httpRequest) throws ProtocolException { try { WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory( getWebSocketURL(httpRequest), null, true); handshaker = wsFactory.newHandshaker(httpRequest); handshaker.handshake(ctx.channel(), httpRequest); boolean isSecuredConnection = false; if (listenerConfiguration.getSslConfig() != null) { isSecuredConnection = true; } ChannelPipeline pipeline = ctx.pipeline(); int maxThreads = PoolConfiguration.getInstance().getEventGroupExecutorThreads(); EventExecutorGroup executorGroup = new DefaultEventExecutorGroup(maxThreads); pipeline.addLast(executorGroup, "ws_handler", new WebSocketSourceHandler(generateWebSocketChannelID(), this.connectionManager, this.listenerConfiguration, httpRequest.getUri(), isSecuredConnection, ctx)); pipeline.remove(this); } catch (Exception e) { ctx.channel().writeAndFlush(new CloseWebSocketFrame(1002, "")); ctx.close(); throw new ProtocolException("Error occurred in HTTP to WebSocket Upgrade : " + e.getMessage()); } }
Source:
<code>public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (savedInstanceState != null) { this.modifier = savedInstanceState.getParcelable(MODIFIER_KEY); } Detail childDetail = getChildDetail(); TreeReference childReference = getChildReference(); <START> NodeEntityFactory factory = new NodeEntityFactory(childDetail, this.getFactoryContext()); <END> View rootView = inflater.inflate(R.layout.entity_detail_list, container, false); final Activity thisActivity = getActivity(); final Entity entity = factory.getEntity(childReference); final DetailCalloutListener detailCalloutListener = thisActivity instanceof DetailCalloutListener ? ((DetailCalloutListener)thisActivity) : null; adapter = new EntityDetailAdapter( thisActivity, asw.getSession(), childDetail, entity, detailCalloutListener, getArguments().getInt(DETAIL_INDEX), modifier ); ((ListView)rootView.findViewById(R.id.screen_entity_detail_list)).setAdapter((ListAdapter)adapter); return rootView; }</code><technical_language>worries reference retrieved (line 74) (line 116) same, coupled. worth passing in duplicating future proof synchronicity issues two</technical_language>

Target:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (savedInstanceState != null) { this.modifier = savedInstanceState.getParcelable(MODIFIER_KEY); } Detail childDetail = getChildDetail(); TreeReference childReference = getChildReference(); NodeEntityFactory factory = new NodeEntityFactory(childDetail, this.getFactoryContext(childReference)); View rootView = inflater.inflate(R.layout.entity_detail_list, container, false); final Activity thisActivity = getActivity(); final Entity entity = factory.getEntity(childReference); final DetailCalloutListener detailCalloutListener = thisActivity instanceof DetailCalloutListener ? ((DetailCalloutListener)thisActivity) : null; adapter = new EntityDetailAdapter( thisActivity, asw.getSession(), childDetail, entity, detailCalloutListener, getArguments().getInt(DETAIL_INDEX), modifier ); ((ListView)rootView.findViewById(R.id.screen_entity_detail_list)).setAdapter((ListAdapter)adapter); return rootView; }
Source:
<code>public Certificate getCertificate(String alias) { try { return getUnderlyingKeyStore().getCertificate(alias); } catch (KeyStoreException e) { <START> logger.info("could not retrieve certificate for alias " + alias, e); <END> } return null; }</code><technical_language>error/warn log level</technical_language>

Target:
public Certificate getCertificate(String alias) { try { return getUnderlyingKeyStore().getCertificate(alias); } catch (KeyStoreException e) { logger.warn("could not retrieve certificate for alias " + alias, e); } return null; }
Source:
<code>public List<View> getRootViews() { try { <START> return Collections.unmodifiableList(Arrays.asList((View[]) mViewsField.get(mWindowManagerGlobal))); <END> } catch (IllegalAccessException e) { throw new RuntimeException("unfortunately, you cannot view the view tree of the dialog etc.", e); } }</code><technical_language>Some of impls precompute root views return list getRootViews is called others snapshot current values time getRootViews is called. Why? API work consistently for impls. I personally get current decor views call get instance of compat object, store it, call number of times get current list</technical_language>

Target:
public List<View> getRootViews() { try { return Collections.unmodifiableList(Arrays.asList((View[]) mViewsField.get(mWindowManagerGlobal))); } catch (IllegalAccessException e) { throw new RuntimeException(e); } }
Source:
<code>public List<Map<String, Object>> getServices(String applicationID) { List<Map<String, Object>> services = configAdminExt.listServices(getDefaultFactoryLdapFilter(), getDefaultLdapFilter()); List<Map<String, Object>> returnValues = new ArrayList<Map<String, Object>>(); if (!services.isEmpty()) { Application app = appService.getApplication(applicationID); if (app != null) { try { Set<BundleInfo> bundles = app.getBundles(); Set<String> bundleLocations = new HashSet<String>(); for (BundleInfo info : bundles) { bundleLocations.add(info.getLocation()); } for (Map<String, Object> service : services) { if (service.containsKey("configurations")) { List<Map<String, Object>> configurations = (List<Map<String, Object>>) service.get("configurations"); for (Map<String, Object> item : configurations) { if (item.containsKey("bundle_location")) { String bundleLocation = (String) item.get("bundle_location"); if (bundleLocations.contains(bundleLocation)) { returnValues.add(service); } } } } } } catch (ApplicationServiceException e) { <START> logger.error("There was an error while trying to access the application", e); <END> return new ArrayList<Map<String, Object>>(); } } } return returnValues; }</code><technical_language>if this is in conventions (DDF otherwise). @shaundmorris know, for consistency rest of code (including this file) I this a warn level: java logger.warn("There error while access application", e); warn for other exceptions good same. This more severe though, if is :)</technical_language>

Target:
public List<Map<String, Object>> getServices(String applicationID) { List<Map<String, Object>> services = configAdminExt.listServices(getDefaultFactoryLdapFilter(), getDefaultLdapFilter()); List<Map<String, Object>> returnValues = new ArrayList<Map<String, Object>>(); if (!services.isEmpty()) { Application app = appService.getApplication(applicationID); MetaTypeService metatypeService = getMetaTypeService(); if (app != null) { try { Set<BundleInfo> bundles = app.getBundles(); Set<String> bundleLocations = new HashSet<String>(); Set<MetaTypeInformation> metatypeInformation = new HashSet<MetaTypeInformation>(); for (BundleInfo info : bundles) { bundleLocations.add(info.getLocation()); } for (Bundle bundle : this.bundleContext.getBundles()) { for (BundleInfo info : bundles) { if (info.getLocation().equals(bundle.getLocation())) { metatypeInformation.add(metatypeService.getMetaTypeInformation(bundle)); } } } for (Map<String, Object> service : services) { if (service.containsKey("configurations")) { List<Map<String, Object>> configurations = (List<Map<String, Object>>) service.get("configurations"); for (Map<String, Object> item : configurations) { if (item.containsKey("bundle_location")) { String bundleLocation = (String) item.get("bundle_location"); if (bundleLocations.contains(bundleLocation)) { returnValues.add(service); } } } } else { if (checkForMetaTypesForService(metatypeInformation, service)) { returnValues.add(service); } } } } catch (ApplicationServiceException e) { logger.warn("There was an error while trying to access the application", e); return new ArrayList<Map<String, Object>>(); } } } return returnValues; }
Source:
<code>public MethodNode(String selector, List<VarRefNode> arguments, SequenceNode sequence) { <START> this.objectName = null; END> this.selector = selector; this.arguments = arguments; this.sequence = sequence; }</code><technical_language>Agreed. Optional<VarRefNode></technical_language>

Target:
public MethodNode(String selector, List<VarRefNode> arguments, SequenceNode sequence) { this.objectName = Optional.empty(); this.selector = selector; this.arguments = arguments; this.sequence = sequence; }
Source:
<code>public void deleteSecretSeriesById(long id) { long now = OffsetDateTime.now().toEpochSecond(); dslContext.transaction(configuration -> { SecretsRecord r = DSL.using(configuration) <START> .fetchOne(SECRETS, SECRETS.ID.eq(id).and(SECRETS.CURRENT.isNotNull())); <END> if (r != null) { DSL.using(configuration) .update(SECRETS) .set(SECRETS.NAME, transformNameForDeletion(r.getName())) .set(SECRETS.CURRENT, (Long) null) .set(SECRETS.UPDATEDAT, now) .where(SECRETS.ID.eq(id)) .execute(); DSL.using(configuration) .delete(ACCESSGRANTS) .where(ACCESSGRANTS.SECRETID.eq(id)) .execute(); } }); }</code><technical_language>I this call .forUpdate(), row is locked subsequent UPPDATE</technical_language>

Target:
public void deleteSecretSeriesById(long id) { long now = OffsetDateTime.now().toEpochSecond(); dslContext.transaction(configuration -> { SecretsRecord r = DSL.using(configuration) .select() .from(SECRETS) .where(SECRETS.ID.eq(id).and(SECRETS.CURRENT.isNotNull())) .forUpdate() .fetchOneInto(SECRETS); if (r != null) { DSL.using(configuration) .update(SECRETS) .set(SECRETS.NAME, transformNameForDeletion(r.getName())) .set(SECRETS.CURRENT, (Long) null) .set(SECRETS.UPDATEDAT, now) .where(SECRETS.ID.eq(id)) .execute(); DSL.using(configuration) .delete(ACCESSGRANTS) .where(ACCESSGRANTS.SECRETID.eq(id)) .execute(); } }); }
Source:
<code>public boolean removeAcl(OzoneObj obj, OzoneAcl acl) throws IOException { Objects.requireNonNull(obj); Objects.requireNonNull(acl); if (!obj.getResourceType().equals(OzoneObj.ResourceType.BUCKET)) { throw new IllegalArgumentException("Unexpected argument passed to " + "BucketManager. OzoneObj type:" + obj.getResourceType()); } String volume = obj.getVolumeName(); String bucket = obj.getBucketName(); metadataManager.getLock().acquireBucketLock(volume, bucket); try { String dbBucketKey = metadataManager.getBucketKey(volume, bucket); OmBucketInfo bucketInfo = metadataManager.getBucketTable().get(dbBucketKey); if (bucketInfo == null) { LOG.debug("Bucket:{}/{} does not exist", volume, bucket); throw new OMException("Bucket " + bucket + " is not found", BUCKET_NOT_FOUND); } for(OzoneAcl a: bucketInfo.getAcls()) { <START> if(a.getName().equals(acl.getName()) && <END> a.getType().equals(acl.getType())) { BitSet bits = (BitSet) acl.getAclBitSet().clone(); bits.and(a.getAclBitSet()); if (bits.equals(ZERO_BITSET)) { return false; } bits = (BitSet) acl.getAclBitSet().clone(); bits.and(a.getAclBitSet()); a.getAclBitSet().xor(bits); if(a.getAclBitSet().equals(ZERO_BITSET)) { bucketInfo.getAcls().remove(a); } break; } } metadataManager.getBucketTable().put(dbBucketKey, bucketInfo); } catch (IOException ex) { if (!(ex instanceof OMException)) { LOG.error("Remove acl operation failed for bucket:{}/{} acl:{}", volume, bucket, acl, ex); } throw ex; } finally { metadataManager.getLock().releaseBucketLock(volume, bucket); } return true; }</code><technical_language>return false if acl is found</technical_language>

Target:
public boolean removeAcl(OzoneObj obj, OzoneAcl acl) throws IOException { Objects.requireNonNull(obj); Objects.requireNonNull(acl); if (!obj.getResourceType().equals(OzoneObj.ResourceType.BUCKET)) { throw new IllegalArgumentException("Unexpected argument passed to " + "BucketManager. OzoneObj type:" + obj.getResourceType()); } String volume = obj.getVolumeName(); String bucket = obj.getBucketName(); metadataManager.getLock().acquireBucketLock(volume, bucket); try { String dbBucketKey = metadataManager.getBucketKey(volume, bucket); OmBucketInfo bucketInfo = metadataManager.getBucketTable().get(dbBucketKey); if (bucketInfo == null) { LOG.debug("Bucket:{}/{} does not exist", volume, bucket); throw new OMException("Bucket " + bucket + " is not found", BUCKET_NOT_FOUND); } for(OzoneAcl a: bucketInfo.getAcls()) { if(a.getName().equals(acl.getName()) && a.getType().equals(acl.getType())) { BitSet bits = (BitSet) acl.getAclBitSet().clone(); bits.and(a.getAclBitSet()); if (bits.equals(ZERO_BITSET)) { return false; } bits = (BitSet) acl.getAclBitSet().clone(); bits.and(a.getAclBitSet()); a.getAclBitSet().xor(bits); if(a.getAclBitSet().equals(ZERO_BITSET)) { bucketInfo.getAcls().remove(a); } break; } else { return false; } } metadataManager.getBucketTable().put(dbBucketKey, bucketInfo); } catch (IOException ex) { if (!(ex instanceof OMException)) { LOG.error("Remove acl operation failed for bucket:{}/{} acl:{}", volume, bucket, acl, ex); } throw ex; } finally { metadataManager.getLock().releaseBucketLock(volume, bucket); } return true; }
Source:
<code>private Message decodeDelivery(Delivery delivery) { ExtendedAmqpMessage extendedAmqpMessage = null; final Message response = Proton.message(); final int msgSize = delivery.pending(); final byte[] buffer = new byte[msgSize]; final int read = receiveLink.recv(buffer, 0, msgSize); response.decode(buffer, 0, read); if (senderSettleMode == SenderSettleMode.SETTLED) { delivery.disposition(Accepted.getInstance()); delivery.settle(); extendedAmqpMessage = new ExtendedAmqpMessage(response, null); } else { extendedAmqpMessage = new ExtendedAmqpMessage(response, ByteBuffer.wrap(delivery.getTag())); } <START> return extendedAmqpMessage; <END> }</code><technical_language>question maintaining type information</technical_language>

Target:
private Message decodeDelivery(Delivery delivery) { final Message response = Proton.message(); final int msgSize = delivery.pending(); final byte[] buffer = new byte[msgSize]; final int read = receiveLink.recv(buffer, 0, msgSize); response.decode(buffer, 0, read); if (this.senderSettleMode == SenderSettleMode.SETTLED) { delivery.disposition(Accepted.getInstance()); delivery.settle(); } return response; }
Source:
<code>public void initChecker() { @Nullable Trees trees = Trees.instance(processingEnv); assert trees != null; this.trees = trees; this.messager = processingEnv.getMessager(); this.messagesProperties = getMessagesProperties(); this.visitor = createSourceVisitor(); <START> this.activeLints = createActiveLints(getOptions()); <END> }</code><technical_language>This good. Thanks</technical_language>

Target:
public void initChecker() { @Nullable Trees trees = Trees.instance(processingEnv); assert trees != null; this.trees = trees; this.messager = processingEnv.getMessager(); this.messagesProperties = getMessagesProperties(); this.visitor = createSourceVisitor(); if (this.activeLints == null) { this.activeLints = createActiveLints(getOptions()); } }
Source:
<code>private void doOpenSelectionDialog(FormEntry entry) { FilteredSchemaAttributeSelectionDialog dialog = new FilteredSchemaAttributeSelectionDialog(PDEPlugin.getActiveWorkbenchShell()); int status = dialog.open(); if (status == Window.OK) { Object[] selectedAttributes = dialog.getResult(); StringBuilder result = new StringBuilder(); for (Object object : selectedAttributes) { if (object instanceof ISchemaAttribute) { ISchemaAttribute attribute = (ISchemaAttribute) object; String id = PDESchemaHelper.getReferenceIdentifier(attribute); <START> if (result.length() > 0) <END> result.append(","); result.append(id); } } entry.setValue(result.toString()); entry.commit(); } }</code><technical_language>{} for single statements</technical_language>

Target:
private void doOpenSelectionDialog(FormEntry entry) { FilteredSchemaAttributeSelectionDialog dialog = new FilteredSchemaAttributeSelectionDialog(PDEPlugin.getActiveWorkbenchShell()); int status = dialog.open(); if (status == Window.OK) { Object[] selectedAttributes = dialog.getResult(); StringBuilder result = new StringBuilder(); for (Object object : selectedAttributes) { if (object instanceof ISchemaAttribute) { ISchemaAttribute attribute = (ISchemaAttribute) object; String id = PDESchemaHelper.getReferenceIdentifier(attribute); if (result.length() > 0) { result.append(","); } result.append(id); } } entry.setValue(result.toString()); entry.commit(); } }
Source:
<code>public VoidResponse downloadWithResponse(OutputStream stream, BlobRange range, ReliableDownloadOptions options, BlobAccessConditions accessConditions, boolean rangeGetContentMD5, Duration timeout, Context context) { Mono<VoidResponse> download = blobAsyncClient .downloadWithResponse(range, options, accessConditions, rangeGetContentMD5, context) .flatMapMany(res -> res.getValue() .doOnNext(bf -> { try { <START> WritableByteChannel channel = Channels.newChannel(stream); <END> channel.write(bf); channel.close(); } catch (IOException e) { throw logger.logExceptionAsError(new UncheckedIOException(e)); } }).map(bf -> res)) .last() .map(VoidResponse::new); return Utility.blockWithOptionalTimeout(download, timeout); }</code><technical_language>this channel instantiation of reactive stream? This is creating a new channel time another item is emitted stream</technical_language>

Target:
public Response<Void> downloadWithResponse(OutputStream stream, BlobRange range, ReliableDownloadOptions options, BlobAccessConditions accessConditions, boolean rangeGetContentMD5, Duration timeout, Context context) { Utility.assertNotNull("stream", stream); Mono<Response<Void>> download = blobAsyncClient .downloadWithResponse(range, options, accessConditions, rangeGetContentMD5, context) .flatMapMany(res -> res.getValue() .doOnNext(bf -> { try { stream.write(FluxUtil.byteBufferToArray(bf)); } catch (IOException e) { throw logger.logExceptionAsError(new UncheckedIOException(e)); } }).map(bf -> res)) .last() .map(response -> new SimpleResponse<>(response, null)); return Utility.blockWithOptionalTimeout(download, timeout); }
Source:
<code>public String show(Request request, Response response) throws IOException { String pluginId = request.params("id"); CombinedPluginInfo pluginInfo = this.pluginInfoFinder.pluginInfoFor(pluginId); CombinedPluginInfo badPluginInfo = null; <START> if (pluginInfo != null && hasUnsupportedExtensionType(pluginInfo)) { <END> throw new RecordNotFoundException(notFoundMessage()); } if (pluginInfo == null) { GoPluginDescriptor pluginDescriptor = defaultPluginManager.getPluginDescriptorFor(pluginId); if (pluginDescriptor != null && pluginDescriptor.isInvalid()) { badPluginInfo = new CombinedPluginInfo(new BadPluginInfo(pluginDescriptor)); } } if (pluginInfo == null && badPluginInfo == null) { throw new RecordNotFoundException(notFoundMessage()); } CombinedPluginInfo extractedPluginInfo = badPluginInfo != null ? badPluginInfo : pluginInfo; String etag = etagFor(extractedPluginInfo); if (fresh(request, etag)) { return notModified(response); } setEtagHeader(response, etag); return writerForTopLevelObject(request, response, writer -> PluginInfoRepresenter.toJSON(writer, extractedPluginInfo)); }</code><technical_language>simplified case1: pluginInfo === null => return RecoredNotFound case2: isBadPluignInfo => return response(instead of record found) else return pluginInfo</technical_language>

Target:
public String show(Request request, Response response) throws IOException { String pluginId = request.params("id"); CombinedPluginInfo pluginInfo = this.pluginInfoFinder.pluginInfoFor(pluginId); if (pluginInfo == null) { GoPluginDescriptor pluginDescriptor = defaultPluginManager.getPluginDescriptorFor(pluginId); if (pluginDescriptor != null && pluginDescriptor.isInvalid()) { pluginInfo = new CombinedPluginInfo(new BadPluginInfo(pluginDescriptor)); } else { throw new RecordNotFoundException(notFoundMessage()); } } String etag = etagFor(pluginInfo); if (fresh(request, etag)) { return notModified(response); } setEtagHeader(response, etag); CombinedPluginInfo finalPluginInfo = pluginInfo; return writerForTopLevelObject(request, response, writer -> PluginInfoRepresenter.toJSON(writer, finalPluginInfo)); }
Source:
<code>public boolean isNonCodedDrug() { <START> return getDrugNonCoded() != null; <END> }</code><technical_language>I this check coded is blank, user StringUtils.isNotBlank</technical_language>

Target:
public boolean isNonCodedDrug() { return StringUtils.isNotBlank(this.drugNonCoded); }
Source:
<code>public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } NewSpatialDimensionSchema that = (NewSpatialDimensionSchema) o; <START> if (dims != null ? dims.equals(that.dims) : that.dims == null) { <END> return true; } return this.delimiter.equals(that.delimiter); }</code><technical_language>java.util.Objects.equals(dims, that.dims)</technical_language>

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } NewSpatialDimensionSchema that = (NewSpatialDimensionSchema) o; if (!super.equals(that)) { return false; } if (!Objects.equals(dims, that.dims)) { return false; } return this.delimiter.equals(that.delimiter); }
Source:
<code>public static void deleteFile(String name) { <START> File file = files.get(name + XML_EXTENSION); <END> if (file == null) { return; } file.delete(); }</code><technical_language>For this API, file name received in parameter complete, include .xml extension this method eventually called anywhere</technical_language>

Target:
public static void deleteFile(String name) { Map<String, File> files = listFile(); File file = files.get(name); if (file == null) { return; } file.delete(); }
Source:
<code>private void generateRequestInterface(Method method) { generateDoc(method); String request = getRequestName(method); String response = getResponseName(method); javaBuffer.addLine("public interface %1$s extends Request<%1$s, %2$s> {", request, response); method.parameters() .filter(Parameter::isIn) .sorted() .forEach(this::generateRequestParameterInterface); javaBuffer.addImport(Map.class); javaBuffer.addDocComment("Additional HTTP headers."); javaBuffer.addLine("%1s headers(Map<String, String> headers);", request); javaBuffer.addDocComment("Additional URL query parameters."); <START> javaBuffer.addLine("%1s query(Map<String, String> query);", request); <END> javaBuffer.addLine("}"); javaBuffer.addLine(); }</code><technical_language>I is add this generic 'Request' interface. easier I 'header' 'query' methods in interface, two: set header/query, another set a map (I'd consider this optional), user do following: vmService.start() .header("My", "header") .query("my", "parameter") .send(); a new 'BaseRequest', similar, implementing interface providing implementations of methods</technical_language>

Target:
private void generateRequestInterface(Method method) { generateDoc(method); String request = getRequestName(method); String response = getResponseName(method); javaBuffer.addLine("public interface %1$s extends Request<%1$s, %2$s> {", request, response); method.parameters() .filter(Parameter::isIn) .sorted() .forEach(this::generateRequestParameterInterface); javaBuffer.addLine("}"); javaBuffer.addLine(); }
Source:
<code>private static Expression convertRow(Row expression) { List<Expression> fields = IntStream.range(0, expression.getArity()) .mapToObj(expression::getField) .map(ApiExpressionUtils::objectToExpression) .collect(Collectors.toList()); <START> return ApiExpressionUtils.unresolvedCall(BuiltInFunctionDefinitions.ROW, fields); <END> }</code><technical_language>nit: in class need fully qualify method</technical_language>

Target:
private static Expression convertRow(Row expression) { List<Expression> fields = IntStream.range(0, expression.getArity()) .mapToObj(expression::getField) .map(ApiExpressionUtils::objectToExpression) .collect(Collectors.toList()); return unresolvedCall(BuiltInFunctionDefinitions.ROW, fields); }
Source:
<code>public void testSmallList() { <START> int testSize = 100; <END> doTestIntList(testSize); }</code><technical_language>values relative MAX_SLAB_SIZE if changed tests remain valid</technical_language>

Target:
public void testSmallList() { int testSize = IntList.INITIAL_SLAB_SIZE - 100; doTestIntList(testSize, IntList.INITIAL_SLAB_SIZE); }
Source:
<code><START> public void testAddDeleteUser() { <END> UserApi userApi = api.getUserApi().get(); Set<? extends User> initialUsers = userApi.list().concat().toSet(); String randUser = "test_user_" + UUID.randomUUID().toString(); String email = "test@testmail.tm"; String password = "secrete"; User newUser = userApi.add(randUser, email, true, password); Set<? extends User> newUsers = userApi.list().concat().toSet(); assertTrue(newUsers.contains(newUser)); assertTrue(userApi.delete(newUser.getId())); Set<? extends User> finalUsers = userApi.list().concat().toSet(); assertEquals(initialUsers, finalUsers); }</code><technical_language>Split this out tests, depending other? this, if test fails, of operations broke..</technical_language>

Target:
public void testAddDeleteUser() { UserApi userApi = api.getUserApi().get(); Set<? extends User> initialUsers = userApi.list().concat().toSet(); String randUser = "test_user_" + UUID.randomUUID().toString(); String email = "test@testmail.tm"; String password = "secrete"; User newUser = userApi.create(randUser, email, true, password); Set<? extends User> newUsers = userApi.list().concat().toSet(); assertTrue(newUsers.contains(newUser)); assertTrue(userApi.delete(newUser.getId())); Set<? extends User> finalUsers = userApi.list().concat().toSet(); assertEquals(initialUsers, finalUsers); }
Source:
<code>public void restoreRedundancyWithNoArgumentsRestoresRedundancyForAllRegions() { List<String> regionNames = getAllRegionNames(); createAndPopulateRegions(regionNames); int numberOfServers = servers.size(); regionNames.forEach(region -> locator .waitUntilRegionIsReadyOnExactlyThisManyServers(SEPARATOR + region, numberOfServers)); String command = new CommandStringBuilder(COMMAND_NAME).getCommandString(); CommandResultAssert commandResult = gfsh.executeAndAssertThat(command).statusIsSuccess() .hasNoSection(ZERO_REDUNDANCY_SECTION) .hasNoSection(UNDER_REDUNDANCY_SECTION); InfoResultModelAssert summary = commandResult.hasInfoSection(SUMMARY_SECTION); <START> summary.hasOutput().contains(ZERO_REDUNDANT_COPIES + 0); summary.hasOutput().contains(PARTIALLY_SATISFIED_REDUNDANCY + 0); summary.hasOutput().contains(FULLY_SATISFIED_REDUNDANCY + regionNames.size()); InfoResultModelAssert satisfiedSection = commandResult.hasInfoSection(SATISFIED_REDUNDANCY_SECTION); satisfiedSection.hasHeader().isEqualTo(REDUNDANCY_SATISFIED_FOR_REGIONS); satisfiedSection.hasOutput().contains(regionNames); <END> InfoResultModelAssert primariesSection = commandResult.hasInfoSection(PRIMARIES_INFO_SECTION); primariesSection.hasOutput().contains(PRIMARY_TRANSFERS_COMPLETED, PRIMARY_TRANSFER_TIME); int numberOfActiveServers = servers.size(); servers.get(0).invoke(() -> { for (String regionName : regionNames) { assertRedundancyStatusForRegion(regionName, true); assertPrimariesBalanced(regionName, numberOfActiveServers, true); } }); }</code><technical_language>This code block is duplicated test, extracted a separate method</technical_language>

Target:
public void restoreRedundancyWithNoArgumentsRestoresRedundancyForAllRegions() { List<String> regionNames = getAllRegionNames(); createAndPopulateRegions(regionNames); int numberOfServers = servers.size(); regionNames.forEach(region -> locator .waitUntilRegionIsReadyOnExactlyThisManyServers(SEPARATOR + region, numberOfServers)); String command = new CommandStringBuilder(RESTORE_REDUNDANCY).getCommandString(); CommandResultAssert commandResult = gfsh.executeAndAssertThat(command).statusIsSuccess(); verifyGfshOutput(commandResult, new ArrayList<>(), new ArrayList<>(), regionNames); int numberOfActiveServers = servers.size(); servers.get(0).invoke(() -> { for (String regionName : regionNames) { assertRedundancyStatusForRegion(regionName, true); assertPrimariesBalanced(regionName, numberOfActiveServers, true); } }); }
Source:
<code>protected ColumnRef resolveColumn(ColumnParseNode node) throws SQLException { ColumnRef ref = null; try { ref = context.getResolver().resolveColumn(node.getSchemaName(), node.getTableName(), node.getName()); } catch (ColumnNotFoundException e) { if (context.getCurrentTable().getTable().getIndexType() == IndexType.LOCAL) { try { return new LocalIndexDataColumnRef(context, node.getName()); } catch (ColumnFamilyNotFoundException c) { throw e; } } else { throw e; } } PTable table = ref.getTable(); int pkPosition = ref.getPKSlotPosition(); if (pkPosition >= 0) { boolean isSalted = table.getBucketNum() != null; <START> boolean isMultiTenant = context.getConnection()==null ? table.isMultiTenant() : <END> (context.getConnection().getTenantId() != null && table.isMultiTenant()); boolean isSharedViewIndex = table.getViewIndexId() != null; int minPosition = (isSalted ? 1 : 0) + (isMultiTenant ? 1 : 0) + (isSharedViewIndex ? 1 : 0); if (pkPosition < minPosition) { throw new ColumnNotFoundException(table.getSchemaName().getString(), table.getTableName().getString(), null, ref.getColumn().getName().getString()); } } return ref; }</code><technical_language>is connection null</technical_language>

Target:
protected ColumnRef resolveColumn(ColumnParseNode node) throws SQLException { ColumnRef ref = null; try { ref = context.getResolver().resolveColumn(node.getSchemaName(), node.getTableName(), node.getName()); } catch (ColumnNotFoundException e) { if (context.getCurrentTable().getTable().getIndexType() == IndexType.LOCAL) { try { return new LocalIndexDataColumnRef(context, node.getName()); } catch (ColumnFamilyNotFoundException c) { throw e; } } else { throw e; } } PTable table = ref.getTable(); int pkPosition = ref.getPKSlotPosition(); if (pkPosition >= 0) { boolean isSalted = table.getBucketNum() != null; boolean isMultiTenant = context.getConnection().getTenantId() != null && table.isMultiTenant(); boolean isSharedViewIndex = table.getViewIndexId() != null; int minPosition = (isSalted ? 1 : 0) + (isMultiTenant ? 1 : 0) + (isSharedViewIndex ? 1 : 0); if (pkPosition < minPosition) { throw new ColumnNotFoundException(table.getSchemaName().getString(), table.getTableName().getString(), null, ref.getColumn().getName().getString()); } } return ref; }
Source:
<code>public String generateUserDelegationSas(UserDelegationKey delegationKey, String accountName, Context context) { StorageImplUtils.assertNotNull("delegationKey", delegationKey); StorageImplUtils.assertNotNull("accountName", accountName); ensureState(); final String canonicalName = getCanonicalName(accountName); final String stringToSign = stringToSign(delegationKey, canonicalName); <START> if (context != null && Boolean.TRUE.equals(context.getData("Log-String-To-Sign").orElse(false))) { logger.info("The string to sign computed by the SDK is: {}{}", stringToSign, System.getProperty("line.separator")); logger.warning("Please remember to disable 'Log-String-To-Sign' before going to production as this " + "string can potentially contain PII."); } <END> String signature = StorageImplUtils.computeHMac256(delegationKey.getValue(), stringToSign); return encode(delegationKey, signature); }</code><technical_language>this is in multiple spots a method if needs updated location needs modification</technical_language>

Target:
public String generateUserDelegationSas(UserDelegationKey delegationKey, String accountName, Context context) { StorageImplUtils.assertNotNull("delegationKey", delegationKey); StorageImplUtils.assertNotNull("accountName", accountName); ensureState(); final String canonicalName = getCanonicalName(accountName); final String stringToSign = stringToSign(delegationKey, canonicalName); StorageImplUtils.logStringToSign(logger, stringToSign, context); String signature = StorageImplUtils.computeHMac256(delegationKey.getValue(), stringToSign); return encode(delegationKey, signature); }
Source:
<code>public Response updateChildrenBulk(@Context HttpServletRequest request, String content) { Response response; if (StringUtils.isNotBlank(content)) { try { JsonObject jsonObj = (JsonObject) new JsonParser().parse(content); Set<Entry<String, JsonElement>> entrySet = jsonObj.entrySet(); int itemCount = entrySet.size(); if (itemCount > 0) { <START> Map<String, JsonObject> itemMap = new HashMap<>(itemCount); <END> for (Entry<String, JsonElement> entry : entrySet) { itemMap.put(entry.getKey(), (JsonObject) entry.getValue()); } if (updateItemChildren(itemMap)) { response = Response.ok().build(); } else { response = Response.serverError().build(); } } else { log.error("Incoming content had no items"); response = Response.status(Response.Status.BAD_REQUEST).build(); } } catch (JsonSyntaxException ex) { log.error("Could not parse incoming content: {}", content, ex); response = Response.status(Response.Status.BAD_REQUEST).build(); } } else { log.error("Incoming content was empty"); response = Response.status(Response.Status.BAD_REQUEST).build(); } return response; }</code><technical_language>a great idea set initial capacity number of add. If optimize map set initial size itemCount*1.35 trigger resize</technical_language>

Target:
public Response updateChildrenBulk(@Context HttpServletRequest request, String content) { Response response; if (StringUtils.isNotBlank(content)) { try { JsonObject jsonObj = (JsonObject) new JsonParser().parse(content); Set<Entry<String, JsonElement>> entrySet = jsonObj.entrySet(); int itemCount = entrySet.size(); if (itemCount > 0) { Map<String, JsonObject> itemMap = new HashMap<>(); for (Entry<String, JsonElement> entry : entrySet) { itemMap.put(entry.getKey(), (JsonObject) entry.getValue()); } if (updateItemChildren(itemMap)) { response = Response.ok().build(); } else { response = Response.serverError().build(); } } else { log.error("Incoming content had no items"); response = Response.status(Response.Status.BAD_REQUEST).build(); } } catch (JsonSyntaxException ex) { log.error("Could not parse incoming content: {}", content, ex); response = Response.status(Response.Status.BAD_REQUEST).build(); } } else { log.error("Incoming content was empty"); response = Response.status(Response.Status.BAD_REQUEST).build(); } return response; }
Source:
<code>private DFUFilePartWrapper[] wrapAndResolveFileParts(DFUPartLocation[] fileLocations, DFUFilePart[] fileParts) throws Exception { if(fileLocations == null || fileLocations.length == 0) throw new Exception("Encountered empty DFU Part Locations array"); if(fileParts == null || fileParts.length == 0) throw new Exception("Encountered empty DFU Parts array"); Hashtable<Integer, String> availableLocations = new Hashtable<Integer, String>(fileLocations.length); for (int locationindex = 0; locationindex < fileLocations.length; locationindex++) { availableLocations.put(fileLocations[locationindex].getLocationIndex(), fileLocations[locationindex].getHost()); } int dataFilePartsCount = fileParts.length; if (fileType == DFUFileTypeWrapper.Index && dataFilePartsCount % availableLocations.size() != 0) <START> { <END> dataFilePartsCount--; } DFUFilePartWrapper wrappedDFUFileParts = new DFUFilePartWrapper[dataFilePartsCount]; for (int i = 0; i < dataFilePartsCount; i++) { Integer filepartindex = fileParts[i].getPartIndex(); if (filepartindex < 1 || filepartindex > dataFilePartsCount) throw new IndexOutOfBoundsException("Encountered invalid Filepart index: '" + filepartindex + "'"); if ( wrappedDFUFileParts[filepartindex-1] != null) throw new IndexOutOfBoundsException("Encountered duplicate Filepart copy index: '" + filepartindex + "'"); wrappedDFUFileParts[filepartindex-1] = new DFUFilePartWrapper(fileParts[i], availableLocations); } return wrappedDFUFileParts; }</code><technical_language>I agree this a hacky, I work</technical_language>

Target:
private DFUFilePartWrapper[] wrapAndResolveFileParts(DFUPartLocation[] fileLocations, DFUFilePart[] fileParts) throws Exception { if(fileLocations == null || fileLocations.length == 0) throw new Exception("Encountered empty DFU Part Locations array"); if(fileParts == null || fileParts.length == 0) throw new Exception("Encountered empty DFU Parts array"); Hashtable<Integer, String> availableLocations = new Hashtable<Integer, String>(fileLocations.length); for (int locationindex = 0; locationindex < fileLocations.length; locationindex++) { availableLocations.put(fileLocations[locationindex].getLocationIndex(), fileLocations[locationindex].getHost()); } int dataFilePartsCount = fileParts.length; if (fileType == DFUFileTypeWrapper.Index && dataFilePartsCount % availableLocations.size() != 0) { dataFilePartsCount--; log.warn("Ignoring " + fileParts.length +"th filepart (determined to be indexed file top-level-key)"); } DFUFilePartWrapper wrappedDFUFileParts = new DFUFilePartWrapper[dataFilePartsCount]; for (int i = 0; i < dataFilePartsCount; i++) { Integer filepartindex = fileParts[i].getPartIndex(); if (filepartindex < 1 || filepartindex > dataFilePartsCount) throw new IndexOutOfBoundsException("Encountered invalid Filepart index: '" + filepartindex + "'"); if ( wrappedDFUFileParts[filepartindex-1] != null) throw new IndexOutOfBoundsException("Encountered duplicate Filepart copy index: '" + filepartindex + "'"); wrappedDFUFileParts[filepartindex-1] = new DFUFilePartWrapper(fileParts[i], availableLocations); } return wrappedDFUFileParts; }