auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public ClientKeyValueStoreListener(EntryStatus[] types) { List<EntryStatus> eventTypes = Arrays.asList(types); <START> listenCreated = eventTypes.contains(EntryStatus.CREATED) ? true : false; <END> listenUpdated = eventTypes.contains(EntryStatus.UPDATED) ? true : false; listenDeleted = eventTypes.contains(EntryStatus.DELETED) ? true : false; }</code><technical_language>eventTypes.contains() is enough xD</technical_language>

Target:
private ClientKeyValueStoreListener(EntryStatus[] types) { List<EntryStatus> eventTypes = Arrays.asList(types); listenCreated = eventTypes.contains(EntryStatus.CREATED); listenUpdated = eventTypes.contains(EntryStatus.UPDATED); listenDeleted = eventTypes.contains(EntryStatus.DELETED); }
Source:
<code>Mono<Response<Void>> setTagsWithResponse(Map<String, String> tags, Context context) { List<BlobTag> tagList = null; if (tags != null) { tagList = new ArrayList<>(); for (String tag : tags.keySet()) { tagList.add(new BlobTag().setKey(tag).setValue(tags.get(tag))); } } BlobTags t = new BlobTags().setBlobTagSet(tagList); return this.azureBlobStorage.blobs().setTagsWithRestResponseAsync(null, null, null, snapshot, <START> null , null, null, null, t, context) <END> .map(response -> new SimpleResponse<>(response, null)); }</code><technical_language>here. if update tags version. AFAIK version immutable result of write operations. updating/setting tags bump blob version? (updating metadata that)</technical_language>

Target:
Mono<Response<Void>> setTagsWithResponse(Map<String, String> tags, Context context) { List<BlobTag> tagList = null; if (tags != null) { tagList = new ArrayList<>(); for (Map.Entry<String, String> entry : tags.entrySet()) { tagList.add(new BlobTag().setKey(entry.getKey()).setValue(entry.getValue())); } } BlobTags t = new BlobTags().setBlobTagSet(tagList); return this.azureBlobStorage.blobs().setTagsWithRestResponseAsync(null, null, null, versionId, null, null, null, t, context) .map(response -> new SimpleResponse<>(response, null)); }
Source:
<code>public Builder<?> read(NearCacheConfiguration template) { mode = template.mode(); maxEntries = template.maxEntries(); Pattern pattern = template.cacheNamePattern(); <START> cacheNamePattern = pattern; <END> return this; }</code><technical_language>cacheNamePattern = template.cacheNamePattern();</technical_language>

Target:
public Builder<?> read(NearCacheConfiguration template) { mode = template.mode(); maxEntries = template.maxEntries(); cacheNamePattern = template.cacheNamePattern(); return this; }
Source:
<code>public LowResMapOverlay(final Context aContext, boolean isMLSTileStore, MapView mapView) { super(aContext); ITileSource coverageTileSource; if (isMLSTileStore) { coverageTileSource = new XYTileSource("MozStumbler Tile Store", null, <START> 13, 13, AbstractMapOverlay.TILE_PIXEL_SIZE, <END> AbstractMapOverlay.FILE_TYPE_SUFFIX_PNG, new String[]{BuildConfig.TILE_SERVER_URL}); } else { coverageTileSource = new XYTileSource("MapquestOSM", ResourceProxy.string.mapquest_osm, 13, 13, AbstractMapOverlay.TILE_PIXEL_SIZE, ".jpg", new String[]{ "<LINK_3>", "<LINK_1>", "<LINK_2>", "<LINK_0>"}); } this.setLoadingBackgroundColor(Color.TRANSPARENT); mTileProvider.setTileRequestCompleteHandler(new SimpleInvalidationHandler(mapView)); mTileProvider.setTileSource(coverageTileSource); }</code><technical_language>Magic numbers again. Pull out 13, 13 MIN MAX zoom level constants</technical_language>

Target:
public LowResMapOverlay(final Context aContext, boolean isMLSTileStore, MapView mapView) { super(aContext); ITileSource coverageTileSource; if (isMLSTileStore) { coverageTileSource = new XYTileSource("MozStumbler Tile Store", null, AbstractMapOverlay.MIN_ZOOM_LEVEL_OF_MAP, AbstractMapOverlay.MIN_ZOOM_LEVEL_OF_MAP, AbstractMapOverlay.TILE_PIXEL_SIZE, AbstractMapOverlay.FILE_TYPE_SUFFIX_PNG, new String[]{BuildConfig.TILE_SERVER_URL}); } else { coverageTileSource = new XYTileSource("MapquestOSM", ResourceProxy.string.mapquest_osm, AbstractMapOverlay.MIN_ZOOM_LEVEL_OF_MAP, AbstractMapOverlay.MIN_ZOOM_LEVEL_OF_MAP, AbstractMapOverlay.TILE_PIXEL_SIZE, ".jpg", new String[]{ "<LINK_3>", "<LINK_1>", "<LINK_2>", "<LINK_0>"}); } this.setLoadingBackgroundColor(Color.TRANSPARENT); mTileProvider.setTileRequestCompleteHandler(new SimpleInvalidationHandler(mapView)); mTileProvider.setTileSource(coverageTileSource); }
Source:
<code>public void run() { Properties properties = new Properties(); properties.put("metadata.broker.list", "localhost:9092"); properties.put("partitioner.class", "com.pinterest.secor.tools.RandomPartitioner"); properties.put("serializer.class", "kafka.serializer.DefaultEncoder"); properties.put("key.serializer.class", "kafka.serializer.StringEncoder"); properties.put("request.required.acks", "1"); ProducerConfig config = new ProducerConfig(properties); Producer<String, byte[]> producer = new Producer<String, byte[]>(config); TProtocolFactory protocol = null; if(mType.equals("json")) { protocol = new TSimpleJSONProtocol.Factory(); } else if (mType.equals("binary")) { protocol = new TBinaryProtocol.Factory(); } else { <START> throw new RuntimeException("Undefined message encoding type"); <END> } TSerializer serializer = new TSerializer(protocol); for (int i = 0; i < mNumMessages; ++i) { TestMessage testMessage = new TestMessage(System.currentTimeMillis() * 1000000L + i, "some_value_" + i); if (i % 2 == 0) { testMessage.setEnumField(TestEnum.SOME_VALUE); } else { testMessage.setEnumField(TestEnum.SOME_OTHER_VALUE); } byte[] bytes; try { bytes = serializer.serialize(testMessage); } catch(TException e) { throw new RuntimeException("Failed to serialize message " + testMessage, e); } KeyedMessage<String, byte[]> data = new KeyedMessage<String, byte[]>( mTopic, Integer.toString(i), bytes); producer.send(data); } producer.close(); }</code><technical_language>Consider including unsupported type (mType) in exception</technical_language>

Target:
public void run() { Properties properties = new Properties(); properties.put("metadata.broker.list", "localhost:9092"); properties.put("partitioner.class", "com.pinterest.secor.tools.RandomPartitioner"); properties.put("serializer.class", "kafka.serializer.DefaultEncoder"); properties.put("key.serializer.class", "kafka.serializer.StringEncoder"); properties.put("request.required.acks", "1"); ProducerConfig config = new ProducerConfig(properties); Producer<String, byte[]> producer = new Producer<String, byte[]>(config); TProtocolFactory protocol = null; if(mType.equals("json")) { protocol = new TSimpleJSONProtocol.Factory(); } else if (mType.equals("binary")) { protocol = new TBinaryProtocol.Factory(); } else { throw new RuntimeException("Undefined message encoding type: " + mType); } TSerializer serializer = new TSerializer(protocol); for (int i = 0; i < mNumMessages; ++i) { TestMessage testMessage = new TestMessage(System.currentTimeMillis() * 1000000L + i, "some_value_" + i); if (i % 2 == 0) { testMessage.setEnumField(TestEnum.SOME_VALUE); } else { testMessage.setEnumField(TestEnum.SOME_OTHER_VALUE); } byte[] bytes; try { bytes = serializer.serialize(testMessage); } catch(TException e) { throw new RuntimeException("Failed to serialize message " + testMessage, e); } KeyedMessage<String, byte[]> data = new KeyedMessage<String, byte[]>( mTopic, Integer.toString(i), bytes); producer.send(data); } producer.close(); }
Source:
<code>public void testHlsSampleAes_bbb_unmuxed_1500k() throws Exception { if (!MediaUtils.checkDecoder(MediaFormat.MIMETYPE_VIDEO_AVC)) { return; } MediaCodecList mcl = new MediaCodecList(MediaCodecList.REGULAR_CODECS); <START> for (MediaCodecInfo info : mcl.getCodecInfos()) { <END> if (info.isEncoder() || info.getName().toLowerCase().startsWith("omx.google.")) { continue; } try { CodecCapabilities caps = info.getCapabilitiesForType(MediaFormat.MIMETYPE_VIDEO_AVC); VideoCapabilities vcaps = caps.getVideoCapabilities(); if (vcaps.areSizeAndRateSupported(1920 ,1080, 30)) { playLiveVideoTest( "<LINK_0>" + "bbb_1080p_30fps_11min/unmuxed_1500k/prog_index.m3u8", 60 * 1000); } } catch (IllegalArgumentException e) { } } }</code><technical_language>Is intended test decoders support stream? original test check decoder. Meanwhile, is good MediaUtils.supports(String codecName, String mime, int w, int h) here? (cts/common/device-side/util/src/com/android/compatibility/common/util/MediaUtils.java)</technical_language>

Target:
public void testHlsSampleAes_bbb_unmuxed_1500k() throws Exception { if (!MediaUtils.checkDecoder(MediaFormat.MIMETYPE_VIDEO_AVC)) { return; } MediaFormat format = MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_AVC, 1920, 1080); String[] decoderNames = MediaUtils.getDecoderNames(false, format); if (decoderNames.length == 0) { MediaUtils.skipTest("No decoders for " + format); } else { playLiveVideoTest( "<LINK_0>" + "bbb_1080p_30fps_11min/unmuxed_1500k/prog_index.m3u8", 60 * 1000); } }
Source:
<code>public static org.eclipse.uml2.uml.Package getPackage(EPackage definition, EObject context) { org.eclipse.uml2.uml.Package package_ = getPackage(definition); if (package_ == null && context != null) { Resource eResource = context.eResource(); if (eResource != null) { ResourceSet resourceSet = eResource.getResourceSet(); if (resourceSet != null) { String nsURI = definition.getNsURI(); URI location = UMLPlugin .getEPackageNsURIToPackageLocationMap().get(nsURI); if (location == null) { location = UMLPlugin.getEPackageNsURIToProfileLocationMap().get(nsURI); } if (location != null) { try { package_ = (org.eclipse.uml2.uml.Package) resourceSet.getEObject( location, true); } catch (Exception e) { UMLPlugin.INSTANCE.log(e); } } else { LOOP : for (Resource resource : resourceSet .getResources()) { for (TreeIterator<Object> allProperContents = EcoreUtil .getAllProperContents(resource, false); allProperContents .hasNext();) { Object object = allProperContents.next(); if (object instanceof org.eclipse.uml2.uml.Package) { <START> EAnnotation eAnnotation <END> = ((org.eclipse.uml2.uml.Package) object) .getEAnnotation(UML2_UML_PACKAGE_2_0_NS_URI); if (eAnnotation != null) { for (EObject content : eAnnotation .getContents()) { if (content instanceof EPackage && safeEquals(nsURI, ((EPackage) content) .getNsURI())) { package_ = (org.eclipse.uml2.uml.Package) object; break LOOP; } } } allProperContents.prune(); } } } } } } } return package_; }</code><technical_language>This apply generally packages get annotated this annotation profiles do</technical_language>

Target:
public static org.eclipse.uml2.uml.Package getPackage(EPackage definition, EObject context) { org.eclipse.uml2.uml.Package package_ = getPackage(definition); if (package_ == null && context != null) { Resource eResource = context.eResource(); if (eResource != null) { ResourceSet resourceSet = eResource.getResourceSet(); if (resourceSet != null) { String nsURI = definition.getNsURI(); URI location = UMLPlugin .getEPackageNsURIToPackageLocationMap().get(nsURI); if (location != null) { try { package_ = (org.eclipse.uml2.uml.Package) resourceSet.getEObject( location, true); } catch (Exception e) { UMLPlugin.INSTANCE.log(e); } } else { LOOP : for (Resource resource : resourceSet .getResources()) { for (TreeIterator<Object> allProperContents = EcoreUtil .getAllProperContents(resource, false); allProperContents .hasNext();) { Object object = allProperContents.next(); if (object instanceof org.eclipse.uml2.uml.Package) { EAnnotation eAnnotation = ((org.eclipse.uml2.uml.Package) object) .getEAnnotation(UML2_UML_PACKAGE_2_0_NS_URI); if (eAnnotation != null) { for (EObject content : eAnnotation .getContents()) { if (content instanceof EPackage && safeEquals(nsURI, ((EPackage) content) .getNsURI())) { package_ = (org.eclipse.uml2.uml.Package) object; break LOOP; } } } allProperContents.prune(); } } } } } } } return package_; }
Source:
<code>public boolean canProvision(Label label) { if (slaveInfos != null) { for (MesosSlaveInfo slaveInfo : slaveInfos) { if (slaveInfo.matchesLabel(label)) { return true; } <START> if (label.toString().startsWith(slaveInfo.getLabelString() + ":")) { <END> return true; } } } return false; }</code><technical_language>This test slaveInfo#matchesLabel</technical_language>

Target:
public boolean canProvision(Label label) { if (slaveInfos != null) { for (MesosSlaveInfo slaveInfo : slaveInfos) { if (slaveInfo.matchesLabel(label)) { return true; } } } return false; }
Source:
<code>public void testGetWithStartIndexAndPageSize() throws PersistenceException, IOException, SolrServerException { QueryResponse response = mock(QueryResponse.class); SolrDocumentList docList = getSolrDocuments(); when(response.getResults()).thenReturn(docList); when(solrClient.query(any(), eq(METHOD.POST))).thenReturn(response); List<Map<String, Object>> items = persistentStore.get("testcore", "", 0, 1); verify(solrClient).query(solrParamsArgumentCaptor.capture(), eq(METHOD.POST)); final SolrParams solrParams = solrParamsArgumentCaptor.getValue(); <START> assertThat(items.size(), equalTo(2)); <END> assertThat(solrParams.get("start"), is("0")); assertThat(solrParams.get("rows"), is("1")); assertThat(items.get(0).get("id_txt"), equalTo("idvalue1")); }</code><technical_language>This test queries a page size of 1 2 results back. modify stubs return number of results for startIndex pageSize arguments</technical_language>

Target:
public void testGetWithStartIndexAndPageSize() throws PersistenceException, IOException, SolrServerException { QueryResponse response = mock(QueryResponse.class); when(response.getResults()).thenReturn(getSolrDocuments(1)); when(solrClient.query(any(), eq(METHOD.POST))).thenReturn(response); List<Map<String, Object>> items = persistentStore.get("testcore", "", 0, 1); verify(solrClient).query(solrParamsArgumentCaptor.capture(), eq(METHOD.POST)); final SolrParams solrParams = solrParamsArgumentCaptor.getValue(); assertThat(items.size(), equalTo(1)); assertThat(solrParams.get("start"), is("0")); assertThat(solrParams.get("rows"), is("1")); assertThat(items.get(0).get("id_txt"), equalTo("idvalue1")); }
Source:
<code>private void logResultOfPrestartVms(int prestartedVmsCounter, int numOfVmsToPrestart, Guid vmPoolId, Map<String, Integer> failureReasons) { if (prestartedVmsCounter > 0) { log.info("Prestarted Vms out of the required, in VmPool '{}'", prestartedVmsCounter, numOfVmsToPrestart, vmPoolId); } else { log.info("Failed to prestart any Vms for VmPool '{}'", vmPoolId); } if (prestartedVmsCounter < numOfVmsToPrestart) { for (Map.Entry<String, Integer> entry : failureReasons.entrySet()) { <START> log.info("Failed to prestart Vms with reason {}", <END> entry.getValue(), entry.getKey()); } } }</code><technical_language>s/Vms/VMs</technical_language>

Target:
private void logResultOfPrestartVms(int prestartedVmsCounter, int numOfVmsToPrestart, Guid vmPoolId, Map<String, Integer> failureReasons) { if (prestartedVmsCounter > 0) { log.info("Prestarted VMs out of the required, in VmPool '{}'", prestartedVmsCounter, numOfVmsToPrestart, vmPoolId); } else { log.info("Failed to prestart any VMs for VmPool '{}'", vmPoolId); } if (prestartedVmsCounter < numOfVmsToPrestart) { for (Map.Entry<String, Integer> entry : failureReasons.entrySet()) { log.info("Failed to prestart VMs with reason {}", entry.getValue(), entry.getKey()); } } }
Source:
<code>public OperationResult<String> d_mset(final String... keysvalues) { if (CompressionStrategy.NONE == connPool.getConfiguration().getCompressionStrategy()) { return connPool.executeWithFailover(new MultiKeyOperation<String>(Arrays.asList(keysvalues), OpName.MSET) { @Override public String execute(Jedis client, ConnectionContext state) { return client.mset(keysvalues); } }); } else { return connPool.executeWithFailover(new CompressionValueMultiKeyOperation<String>(Arrays.asList(keysvalues), OpName.MSET) { @Override public String execute(final Jedis client, final ConnectionContext state) throws DynoException { <START> return client.mset(keysvalues); <END> } }); } }</code><technical_language>same, compression happening</technical_language>

Target:
public OperationResult<String> d_mset(final String... keysvalues) { if (CompressionStrategy.NONE == connPool.getConfiguration().getCompressionStrategy()) { return connPool.executeWithFailover(new MultiKeyOperation<String>(Arrays.asList(keysvalues), OpName.MSET) { @Override public String execute(Jedis client, ConnectionContext state) { return client.mset(keysvalues); } }); } else { return connPool.executeWithFailover(new CompressionValueMultiKeyOperation<String>(Arrays.asList(keysvalues), OpName.MSET) { @Override public String execute(final Jedis client, final ConnectionContext state) { return client.mset(compressMultiKeyValue(state,keysvalues)); } }); } }
Source:
<code>public DelegatingResourceDescription getUpdatableProperties() throws ResourceDoesNotSupportOperationException { DelegatingResourceDescription description = super.getUpdatableProperties(); description.removeProperty("property"); <START> addPropertiesCommonForCreateAndUpdate(description); <END> return description; }</code><technical_language>if instead of pulling this out a method this this method do: DelegatingResourceDescription description = getCreatableProperties(); description.removeProperty("property")</technical_language>

Target:
public DelegatingResourceDescription getUpdatableProperties() throws ResourceDoesNotSupportOperationException { DelegatingResourceDescription description = getCreatableProperties(); description.removeProperty("property"); return description; }
Source:
<code>public static ResultProducer<ResultSetIterable> returningGeneratedKeys(String... generatedKeyColumnNames) { return (supplier, ctx) -> { String[] columnNames = Stream.of(generatedKeyColumnNames) <START> .filter(name -> name != null && !name.isEmpty()) <END> .toArray(String[]::new); ctx.setReturningGeneratedKeys(true); if (columnNames.length > 0) { ctx.setGeneratedKeysColumnNames(columnNames); } return ResultSetIterable.of(getGeneratedKeys(supplier, ctx), ctx); }; }</code><technical_language>This filter surprising me. If else, means result set column numbers longer align key column names array index. Do people pass null empty strings? I soon forbid throw exception</technical_language>

Target:
public static ResultProducer<ResultSetIterable> returningGeneratedKeys(String... generatedKeyColumnNames) { return (supplier, ctx) -> { ctx.setReturningGeneratedKeys(true); if (generatedKeyColumnNames.length > 0) { ctx.setGeneratedKeysColumnNames(generatedKeyColumnNames); } return ResultSetIterable.of(getGeneratedKeys(supplier, ctx), ctx); }; }
Source:
<code>private String getAdapterQueryLogUnsecuredSerrviceUrl() { String url = null; try { url = proxyHelper.getUrlLocalHomeCommunity(NhincConstants.ADAPTER_AUDIT_QUERY_LOG_SERVICE_NAME); } catch (ConnectionManagerException ex) { <START> LOG.debug("Error while retrieving url for " + NhincConstants.ADAPTER_AUDIT_QUERY_LOG_SERVICE_NAME <END> + ex.getLocalizedMessage(), ex); return url; } catch (Exception ex) { LOG.error("Failed to call the web service " + NhincConstants.ADAPTER_AUDIT_QUERY_LOG_SERVICE_NAME + ex.getLocalizedMessage(), ex); } return url; }</code><technical_language>Fix logging level (error)</technical_language>

Target:
private String getAdapterQueryLogUnsecuredSerrviceUrl() { String url = null; try { url = proxyHelper.getUrlLocalHomeCommunity(NhincConstants.ADAPTER_AUDIT_QUERY_LOG_SERVICE_NAME); } catch (ConnectionManagerException ex) { LOG.error("Error while retrieving url for {}: {}", NhincConstants.ADAPTER_AUDIT_QUERY_LOG_SERVICE_NAME, ex.getLocalizedMessage(), ex); return url; } catch (Exception ex) { LOG.error("Failed to call the web service {}: {}", NhincConstants.ADAPTER_AUDIT_QUERY_LOG_SERVICE_NAME, ex.getLocalizedMessage(), ex); } return url; }
Source:
<code>public StoreStats storeStats() { final LongSupplier remainingRecoveryBytesSupplier; <START> synchronized (mutex) { <END> if (recoveryState == null) { remainingRecoveryBytesSupplier = () -> 0L; } else if (recoveryState.getStage() == RecoveryState.Stage.INIT) { remainingRecoveryBytesSupplier = () -> StoreStats.UNKNOWN_RESERVED_BYTES; } else if (recoveryState.getStage() == RecoveryState.Stage.INDEX) { final RecoveryState.Index indexStageRecoveryState = recoveryState.getIndex(); remainingRecoveryBytesSupplier = () -> { final long bytesStillToRecover = indexStageRecoveryState.bytesStillToRecover(); return bytesStillToRecover == -1 ? StoreStats.UNKNOWN_RESERVED_BYTES : bytesStillToRecover; }; } else { remainingRecoveryBytesSupplier = () -> 0L; } } try { return store.stats(remainingRecoveryBytesSupplier.getAsLong()); } catch (IOException e) { failShard("Failing shard because of exception during storeStats", e); throw new ElasticsearchException("io exception while building 'store stats'", e); } }</code><technical_language>avoid global mutex here? adding a method recoveryState (which synchronization)</technical_language>

Target:
public StoreStats storeStats() { try { final RecoveryState recoveryState = this.recoveryState; final long bytesStillToRecover = recoveryState == null ? -1L : recoveryState.getIndex().bytesStillToRecover(); return store.stats(bytesStillToRecover == -1 ? StoreStats.UNKNOWN_RESERVED_BYTES : bytesStillToRecover); } catch (IOException e) { failShard("Failing shard because of exception during storeStats", e); throw new ElasticsearchException("io exception while building 'store stats'", e); } }
Source:
<code>public void updateModelToTarget() { <START> final IObservableSet<M> modelSet = model; <END> modelSet.getRealm().exec(() -> { SetDiff<M> diff = Diffs.computeSetDiff(Collections.emptySet(), modelSet); doUpdate(modelSet, target, diff, modelToTarget, true, true); }); }</code><technical_language>necessary</technical_language>

Target:
public void updateModelToTarget() { model.getRealm().exec(() -> { SetDiff<M> diff = Diffs.computeSetDiff(Collections.emptySet(), model); doUpdate(model, target, diff, modelToTarget, true, true); }); }
Source:
<code>private Optional<Class> getClassByName(String name) { try { return Optional.of(Class .forName("com.vaadin.flow.component.dnd.DragSource")); <START> } catch (ClassNotFoundException e) { <END> return Optional.empty(); } }</code><technical_language>![MAJOR](<LINK_1> 'Severity: MAJOR') log rethrow this exception. [![rule](<LINK_2>](<LINK_0></technical_language>

Target:
private Optional<Class> getClassByName(String name) { try { return Optional.of(Class .forName(name)); } catch (ClassNotFoundException e) { return Optional.empty(); } }
Source:
<code>private static <AutoClosableWrapper extends AutoCloseable & Wrapper> void close(AutoClosableWrapper dbObject) { if (dbObject != null) { try { dbObject.close(); <START> } catch (SQLRecoverableException ex) { <END> handleSQLRecoverableException(dbObject, ex); } catch (SQLException e) { log.error("Database error. Could not close statement. Continuing with others. - " + e.getMessage(), e); } catch (Exception e) { log.error("An unknown error occurred during close operation" + e.getMessage(), e); } finally { dbObject = null; } } }</code><technical_language>jtds , microsoft drivers throw this exception (I suppose not). if case resort sqlstate class code. <LINK_0></technical_language>

Target:
private static <AutoClosableWrapper extends AutoCloseable & Wrapper> void close(AutoClosableWrapper dbObject) { if (dbObject != null) { try { dbObject.close(); } catch (SQLRecoverableException ex) { handleSQLRecoverableExceptionOnClose(dbObject, ex); } catch (SQLException e) { log.error("Database error. Could not close statement. Continuing with others. - " + e.getMessage(), e); } catch (Exception e) { log.error("An unknown error occurred during close operation" + e.getMessage(), e); } finally { dbObject = null; } } }
Source:
<code>public ResponseEntity<?> addProfile(@AuthenticationPrincipal User user, @Validated @RequestBody ProfileDTO input) { Collection<RFIDLink> linkCollection = rfidLinkRepository.findRFIDLinksByEmail(user.getEmail()); if (linkCollection.isEmpty()) <START> return this.addProfile(user.getId(), input); <END> LocalDate currentBirthday = user.getProfile().getBirthday(); boolean isDateChanged = currentBirthday != input.getBirthday(); if (isDateChanged) { ProfileDTO changedInput = input; changedInput.setBirthday(currentBirthday); return this.addProfile(user.getId(), input); } return this.addProfile(user.getId(), input); }</code><technical_language>{ } please</technical_language>

Target:
public ResponseEntity<?> addProfile(@AuthenticationPrincipal User user, @Validated @RequestBody ProfileDTO input) { boolean isUserCheckedIn = rfidService.isOwnerLinked(user.getEmail()); if (!isUserCheckedIn) { return this.addProfile(user.getId(), input); } LocalDate currentBirthday = user.getProfile().getBirthday(); boolean isDateChanged = currentBirthday != input.getBirthday(); if (isDateChanged) { return createResponseEntity(HttpStatus.BAD_REQUEST, "Unable to change date during event", user.getProfile()); } return this.addProfile(user.getId(), input); }
Source:
<code><START> public Response add(LinkedHashMap<String, Long> entity) throws SQLException, ClassNotFoundException { <END> Context.getPermissionsManager().checkReadonly(getUserId()); checkAndLinkPermission(entity, true); Context.getPermissionsManager().refreshPermissions(entity); return Response.noContent().build(); }</code><technical_language>Idea for improvement. some helper class methods get owner property keys values. extend LinkedHashMap, work automatically argument here. I this simplify some places "parse" this entity</technical_language>

Target:
public Response add(LinkedHashMap<String, Long> entity) throws SQLException, ClassNotFoundException { Context.getPermissionsManager().checkReadonly(getUserId()); Permission permission = new Permission(entity); checkPermission(permission, true); Context.getDataManager().linkObject(permission.getOwnerClass(), permission.getOwnerId(), permission.getPropertyClass(), permission.getPropertyId(), true); Context.getPermissionsManager().refreshPermissions(permission); return Response.noContent().build(); }
Source:
<code>private void teleportAllPlayers(Server server, CommandSource sender, User target, String label) { sender.sendMessage(tl("teleportAll")); final Location loc = target.getLocation(); for (User player : ess.getOnlineUsers()) { if (target == player) { continue; } if (sender.equals(target.getBase()) && target.getWorld() != player.getWorld() && ess.getSettings().isWorldTeleportPermissions() && !target.isAuthorized("essentials.worlds." + target.getWorld().getName())) { continue; } CompletableFuture<Exception> eFuture = new CompletableFuture<>(); <START> eFuture.thenAccept(e -> showError(sender.getSender(), e, label)); <END> player.getAsyncTeleport().now(loc, false, TeleportCause.COMMAND, eFuture, new CompletableFuture<>()); } }</code><technical_language>getNewExceptionFuture</technical_language>

Target:
private void teleportAllPlayers(Server server, CommandSource sender, User target, String label) { sender.sendMessage(tl("teleportAll")); final Location loc = target.getLocation(); for (User player : ess.getOnlineUsers()) { if (target == player) { continue; } if (sender.getSender().equals(target.getBase()) && target.getWorld() != player.getWorld() && ess.getSettings().isWorldTeleportPermissions() && !target.isAuthorized("essentials.worlds." + target.getWorld().getName())) { continue; } player.getAsyncTeleport().now(loc, false, TeleportCause.COMMAND, getNewExceptionFuture(sender, label)); } }
Source:
<code>protected void verifyProcessor(@NonNull MethodTree tree, final @NonNull IdentifierTree processorAnnotation) { <START> final long count = Iterables.size(Iterables.filter(tree.parameters(), ClassParserUtils.getSimpleTypePredicate(imports))); <END> if (count > maxArgumentsAllowed) { final String message = String .format("Processor '%s' has %d simple-type parameters marked as @Optional (more than %d, which is the maximum allowed). It's strongly recommended that all optional parameters are grouped inside a separate POJO class.", tree.simpleName(), count, maxArgumentsAllowed); logAndRaiseIssue(processorAnnotation, message); } }</code><technical_language>Hum... actually, checking @Optional is there. need add check. I add a compound predicate (Predicates.and(predicate1, predicate2)) predicate is now, other parameter contains @Optional annotation</technical_language>

Target:
protected void verifyProcessor(@NonNull MethodTree tree, final @NonNull IdentifierTree processorAnnotation) { long count = Iterables.size(Iterables.filter(tree.parameters(), Predicates.and(ClassParserUtils.simpleTypePredicate(imports), new Predicate<VariableTree>() { @Override public boolean apply(@Nullable VariableTree input) { return Iterables.any(input.modifiers().annotations(), ClassParserUtils.hasAnnotationPredicate(Optional.class)); } }))); if (count > maxArgumentsAllowed) { final String message = String .format("Processor '%s' has %d simple-type parameters marked as @Optional (more than %d, which is the maximum allowed). It's strongly recommended that all optional parameters are grouped inside a separate POJO class.", tree.simpleName(), count, maxArgumentsAllowed); logAndRaiseIssue(processorAnnotation, message); } }
Source:
<code>public void createUserCardShouldReturnTheRequest() throws Exception { final AtomicReference<Request> bodyRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); final RestAdapter adapter = new RestAdapter.Builder().setEndpoint(MOCK_URL).setClient(new Client() { @Override public Response execute(Request request) throws IOException { bodyRef.set(request); latch.countDown(); <START> return null; <END> } }).build(); final UserCardService userCardService = adapter.create(UserCardService.class); userCardService.createUserCard(new CardRequest("foo", "bar"), new RetrofitPromise<Card>()); latch.await(); Assert.assertEquals(bodyRef.get().getUrl(), String.format("%s/v0/me/cards", MOCK_URL)); Assert.assertEquals(bodyRef.get().getMethod(), "POST"); }</code><technical_language>Add newline return</technical_language>

Target:
public void createUserCardShouldReturnTheRequest() throws Exception { final AtomicReference<Request> bodyRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); final RestAdapter adapter = new RestAdapter.Builder().setEndpoint(MOCK_URL).setClient(new Client() { @Override public Response execute(Request request) throws IOException { bodyRef.set(request); latch.countDown(); return null; } }).build(); final UserCardService userCardService = adapter.create(UserCardService.class); userCardService.createUserCard(new CardRequest("foo", "bar"), new RetrofitPromise<Card>()); latch.await(); Assert.assertEquals(bodyRef.get().getMethod(), "POST"); Assert.assertEquals(bodyRef.get().getUrl(), String.format("%s/v0/me/cards", MOCK_URL)); }
Source:
<code>private static URL fileToUrl(File file) { URI uri; try { uri = file.toURI(); } catch (SecurityException e) { <START> throw new IllegalArgumentException("No access to the underlying file " + file.getPath()); <END> } try { return uri.toURL(); } catch (MalformedURLException e) { throw new IllegalArgumentException("Unable to convert URI " + uri + " to URL", e); } }</code><technical_language>do omit SecurityException e in caused chain</technical_language>

Target:
private static URL fileToUrl(File file) { String filePath = file.getPath(); if (!file.isAbsolute()) { filePath = filePath.replace(File.separatorChar, '/'); if (file.isDirectory() && !filePath.endsWith("/")) { filePath += "/"; } try { String encodedPath = new URI(null, null, filePath, null).getRawPath(); return new URL("file", null, 0, encodedPath); } catch (MalformedURLException | URISyntaxException e) { throw new IllegalArgumentException("Unable to create URL for file " + filePath, e); } } URI uri = null; try { uri = file.toURI(); return uri.toURL(); } catch (SecurityException e) { throw new IllegalArgumentException("No access to the underlying file " + filePath, e); } catch (MalformedURLException e) { throw new IllegalArgumentException("Unable to convert URI " + uri + " to URL", e); } }
Source:
<code>public static ModuleManager create() throws Exception { <START> ModuleManager moduleManager = new ModuleManagerImpl(""); return LoadModuleEnvironment(moduleManager); <END> }</code><technical_language>suggestion return create("");</technical_language>

Target:
public static ModuleManager create() throws Exception { return create(""); }
Source:
<code>protected void calculateBounds() { if (this.dropdownShell != null && !this.dropdownShell.isDisposed()) { Point size = getSize(); <START> int gridLineAdjustment = this.dropdownTableViewer.getTable().getGridLineWidth() * 2; <END> int listHeight = getVisibleItemCount() * this.dropdownTableViewer.getTable().getItemHeight() + gridLineAdjustment; this.dropdownTableViewer.getTable().getColumn(0).pack(); this.selectAllItemViewer.getTable().getColumn(0).pack(); int listWidth = Math.max( this.dropdownTableViewer.getTable().computeSize(SWT.DEFAULT, listHeight, true).x, size.x); int viewerHeight = this.selectAllItemViewer.getTable().getItemHeight(); listWidth = Math.max( this.selectAllItemViewer.getTable().computeSize(SWT.DEFAULT, viewerHeight, true).x, listWidth); this.dropdownTableViewer.getTable().setSize(listWidth, listHeight); this.selectAllItemViewer.getTable().setSize(listWidth, viewerHeight); calculateColumnWidth(); Point textPosition = this.text.toDisplay(this.text.getLocation()); if (this.dropdownTableViewer.getTable().getVerticalBar() != null && this.maxVisibleItems > -1 && this.dropdownTableViewer.getTable().getItemCount() > this.maxVisibleItems) { listWidth += gridLineAdjustment; } this.dropdownShell.setBounds(textPosition.x, textPosition.y + this.text.getBounds().height, listWidth, listHeight + viewerHeight); } }</code><technical_language>If dropdownTable stays in NatCombo, changes necessary</technical_language>

Target:
protected void calculateBounds() { if (this.dropdownShell != null && !this.dropdownShell.isDisposed()) { Point size = getSize(); int gridLineAdjustment = this.dropdownTable.getGridLineWidth() * 2; int listHeight = getVisibleItemCount() * this.dropdownTable.getItemHeight() + gridLineAdjustment; this.dropdownTable.getColumn(0).pack(); this.selectAllItemViewer.getTable().getColumn(0).pack(); int listWidth = Math.max( this.dropdownTable.computeSize(SWT.DEFAULT, listHeight, true).x, size.x); int viewerHeight = this.selectAllItemViewer.getTable().getItemHeight(); listWidth = Math.max( this.selectAllItemViewer.getTable().computeSize(SWT.DEFAULT, viewerHeight, true).x, listWidth); this.dropdownTable.setSize(listWidth, listHeight); this.selectAllItemViewer.getTable().setSize(listWidth, viewerHeight); calculateColumnWidth(); Point textPosition = this.text.toDisplay(this.text.getLocation()); if (this.dropdownTable.getVerticalBar() != null && this.maxVisibleItems > -1 && this.dropdownTable.getItemCount() > this.maxVisibleItems) { listWidth += gridLineAdjustment; } int filterTextBoxHeight = 0; if (this.dropdownFilter) { Point point = this.filterBox.computeSize(SWT.DEFAULT, SWT.DEFAULT); filterTextBoxHeight = this.filterBox.getBorderWidth() + point.y; } this.dropdownShell.setBounds(textPosition.x, textPosition.y + this.text.getBounds().height, listWidth, listHeight + viewerHeight + filterTextBoxHeight); } }
Source:
<code>private Constraint maximumCapacity(ConstraintFactory factory) { return factory.from(MrMachineCapacity.class) .join(MrProcessAssignment.class, equal(MrMachineCapacity::getMachine, MrProcessAssignment::getMachine) ) .groupBy((machineCapacity, processAssignment) -> machineCapacity, sumLong( (machineCapacity, processAssignment) -> processAssignment.getUsage(machineCapacity.getResource())) ) .filter(((machineCapacity, usage) -> machineCapacity.getMaximumCapacity() < usage)) .penalizeLong(MrConstraints.MAXIMUM_CAPACITY, HardSoftLongScore.ofHard(1L), <START> (machineCapacity, usage) -> machineCapacity.getMaximumCapacity() - usage); <END> }</code><technical_language>If usage is higher capacity, capacity - usage return a negative number? a fail fast for that. I missing</technical_language>

Target:
private Constraint maximumCapacity(ConstraintFactory factory) { return factory.from(MrMachineCapacity.class) .join(MrProcessAssignment.class, equal(MrMachineCapacity::getMachine, MrProcessAssignment::getMachine) ) .groupBy((machineCapacity, processAssignment) -> machineCapacity, sumLong((machineCapacity, processAssignment) -> processAssignment.getUsage(machineCapacity.getResource())) ) .filter(((machineCapacity, usage) -> machineCapacity.getMaximumCapacity() < usage)) .penalizeLong(MrConstraints.MAXIMUM_CAPACITY, HardSoftLongScore.ONE_HARD, (machineCapacity, usage) -> usage - machineCapacity.getMaximumCapacity()); }
Source:
<code>public void testInitialize() { fieldStateValidator.initialize(); <START> assertEquals(2, <END> fieldStateValidator.validators.size()); assertTrue(fieldStateValidator.validators.containsKey(String.class)); assertTrue(fieldStateValidator.validators.containsKey(ArrayList.class)); }</code><technical_language>In AssertJ, Assertions.assertThat(fieldStateValidator.validators).hasSize(2) is readable fails, error message more descriptive. Similar methods for other assertions in this method</technical_language>

Target:
public void testInitialize() { fieldStateValidator.initialize(); assertThat(fieldStateValidator.validators).hasSize(2); assertThat(fieldStateValidator.validators).containsKeys(String.class, ArrayList.class); }
Source:
<code>public static void setPermissionHandler(IPermissionHandler handler) { <START> FMLLog.log(Level.INFO, "Replacing " + permissionHandler.getClass().getName() + " with " + handler.getClass().getName()); <END> permissionHandler = handler; }</code><technical_language>This NPE if handler is null, checkNotNull(handler, "permission handler"); this</technical_language>

Target:
public static void setPermissionHandler(IPermissionHandler handler) { Preconditions.checkNotNull(handler, "Permission handler can't be null!"); Preconditions.checkState(Loader.instance().getLoaderState().ordinal() <= LoaderState.PREINITIALIZATION.ordinal(), "Can't register after IPermissionHandler PreInit!"); FMLLog.log(Level.WARN, "Replacing " + permissionHandler.getClass().getName() + " with " + handler.getClass().getName()); permissionHandler = handler; }
Source:
<code>protected void testAuditSourceIdentification(List<AuditSourceIdentificationType> auditSourceIdentification, AssertionType assertion) { if (assertion != null && assertion.getUserInfo() != null && assertion.getUserInfo().getOrg() != null && assertion.getUserInfo().getOrg().getHomeCommunityId() != null && auditSourceIdentification != null && !auditSourceIdentification.isEmpty() <START> && auditSourceIdentification.size() > 0) { <END> for (AuditSourceIdentificationType auditSourceId : auditSourceIdentification) { assertEquals(AuditTransformsConstants.HOME_COMMUNITY_ID_PREFIX + assertion.getUserInfo().getOrg().getHomeCommunityId(), auditSourceId.getAuditSourceID()); } } }</code><technical_language>things: 1. isEmpty() .size() > 0 is redundant (and prefer .isEmpty()) 2. isEmpty() needed here; enhanced for loop gracefully care of "empty list" case</technical_language>

Target:
protected void testAuditSourceIdentification(List<AuditSourceIdentificationType> auditSourceIdentification, AssertionType assertion) { if (assertion != null && assertion.getUserInfo() != null && assertion.getUserInfo().getOrg() != null && assertion.getUserInfo().getOrg().getHomeCommunityId() != null && auditSourceIdentification != null) { for (AuditSourceIdentificationType auditSourceId : auditSourceIdentification) { assertEquals(HomeCommunityMap.getHomeCommunityIdWithPrefix( assertion.getUserInfo().getOrg().getHomeCommunityId()), auditSourceId.getAuditSourceID()); } } }
Source:
<code>public static Algorithm RSA384(RSAKey key) throws IllegalArgumentException { RSAPublicKey publicKey = key instanceof PublicKey ? (RSAPublicKey) key : null; <START> RSAPrivateKey privateKey = key instanceof PrivateKey ? (RSAPrivateKey) key : null; <END> return RSA384(publicKey, privateKey); }</code><technical_language>type for instanceof force casting</technical_language>

Target:
public static Algorithm RSA384(RSAKey key) throws IllegalArgumentException { RSAPublicKey publicKey = key instanceof RSAPublicKey ? (RSAPublicKey) key : null; RSAPrivateKey privateKey = key instanceof RSAPrivateKey ? (RSAPrivateKey) key : null; return RSA384(publicKey, privateKey); }
Source:
<code>public CompletableFuture<Void> remove(Predicate<? super V> p) { <START> class Remover { <END> private Predicate<? super V> p; public Remover(Predicate<? super V> p) { this.p = p; } public Void removeEveryMatchingValue() { cache.keySet().stream().forEach((c, key) -> c.computeIfPresent(key, (o, o1) -> { Collection<V> values = (Collection<V>) o1; Collection<V> newValues = new HashSet<>(); for (V v : values) { if (!p.test(v)) newValues.add(v); } return newValues.isEmpty() ? null : newValues; })); return null; } } return CompletableFuture.completedFuture(new Remover(p).removeEveryMatchingValue()); }</code><technical_language>do define class all? inline call..</technical_language>

Target:
public CompletableFuture<Void> remove(Predicate<? super V> p) { requireNonNull(p, "predicate can't be null"); CompletableFuture<Void> cf = CompletableFutures.completedNull(); try { if (isExplicitTxContext()) { cf = completedFuture(this.removeInternal(p)); } else { cf = runAsync(() -> this.removeInternal(p)); } } catch (SystemException e) { rethrowException(e); } return cf; }
Source:
<code>public static String pipeTextToFile(String text, String filepath) { String id = Identifiers.makeRandomId(8); <START> return "cat > " + filepath + " << EOL_" + id + "\n" <END> + text + "EOL_" + id + "\n"; }</code><technical_language>cat > \"" + filepath + "\" ... preferable handle paths spaces</technical_language>

Target:
public static String pipeTextToFile(String text, String filepath) { return "cat > \"" + filepath + "\" << EOF_BROOKLYN\n" + text + "\n" + "EOF_BROOKLYN\n"; }
Source:
<code>public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit unit = phaseContext.getDeploymentUnit(); if (DeploymentTypeMarker.isType(DeploymentType.EAR, unit)) { return; } final CompositeIndex index = unit.getAttachment(Attachments.COMPOSITE_ANNOTATION_INDEX); if (index != null) { if (hasWSEndpoints(index)) { AttachmentList<ResourceRoot> resourceRoots = unit.getAttachment(RESOURCE_ROOTS); if (resourceRoots != null) { for (ResourceRoot root : resourceRoots) { if (root.getRoot().getChild("META-INF/services/javax.xml.datatype.DatatypeFactory").exists() || root.getRoot().getChild("META-INF/services/javax.xml.parsers.DocumentBuilderFactory").exists() || root.getRoot().getChild("META-INF/services/javax.xml.parsers.SAXParserFactory").exists() <START> || root.getRoot().getChild("META-INF/services/jjavax.xml.validation.SchemaFactory").exists()) { <END> throw WSLogger.ROOT_LOGGER.invalidLibraryInDeployment("JAXP Implementation", root.getRootName()); } if (hasClassesFromPackage(root.getAttachment(ANNOTATION_INDEX), "org.apache.cxf")) { throw WSLogger.ROOT_LOGGER.invalidLibraryInDeployment("Apache CXF", root.getRootName()); } } } } } else { WSLogger.ROOT_LOGGER.tracef("Skipping WS annotation processing since no composite annotation index found in unit: %s", unit.getName()); } }</code><technical_language>I javax.xml.validation.SchemaFactory</technical_language>

Target:
public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { final DeploymentUnit unit = phaseContext.getDeploymentUnit(); if (DeploymentTypeMarker.isType(DeploymentType.EAR, unit)) { return; } final CompositeIndex index = unit.getAttachment(Attachments.COMPOSITE_ANNOTATION_INDEX); if (index != null) { if (hasWSEndpoints(index)) { AttachmentList<ResourceRoot> resourceRoots = unit.getAttachment(RESOURCE_ROOTS); if (resourceRoots != null) { for (ResourceRoot root : resourceRoots) { if (root.getRoot().getChild("META-INF/services/javax.xml.datatype.DatatypeFactory").exists() || root.getRoot().getChild("META-INF/services/javax.xml.parsers.DocumentBuilderFactory").exists() || root.getRoot().getChild("META-INF/services/javax.xml.parsers.SAXParserFactory").exists() || root.getRoot().getChild("META-INF/services/javax.xml.validation.SchemaFactory").exists()) { WSLogger.ROOT_LOGGER.warningLibraryInDeployment("JAXP Implementation", root.getRootName()); } if (hasClassesFromPackage(root.getAttachment(ANNOTATION_INDEX), "org.apache.cxf")) { throw WSLogger.ROOT_LOGGER.invalidLibraryInDeployment("Apache CXF", root.getRootName()); } } } } } else { WSLogger.ROOT_LOGGER.tracef("Skipping WS annotation processing since no composite annotation index found in unit: %s", unit.getName()); } }
Source:
<code>public int receiveEnergy( int maxReceive, boolean simulate ) { int total = 0; try { final int outputTunnels = PartP2PFEPower.this.getOutputs().size(); if( outputTunnels == 0 ) { return 0; } final int amountPerOutput = maxReceive / outputTunnels; int overflow = maxReceive % amountPerOutput; for( PartP2PFEPower target : PartP2PFEPower.this.getOutputs() ) { final IEnergyStorage output = target.getOutput(); final int toSend = amountPerOutput + overflow; final int received = output.receiveEnergy( toSend, simulate ); overflow = toSend - received; total += received; } PartP2PFEPower.this.queueTunnelDrain( PowerUnits.RF, total ); } <START> catch( GridAccessException ignored ) <END> { } return total; }</code><technical_language>![MAJOR](<LINK_1> 'Severity: MAJOR') log rethrow this exception. [![rule](<LINK_2>](<LINK_0></technical_language>

Target:
public int receiveEnergy( int maxReceive, boolean simulate ) { int total = 0; try { final int outputTunnels = PartP2PFEPower.this.getOutputs().size(); if( outputTunnels == 0 ) { return 0; } final int amountPerOutput = maxReceive / outputTunnels; int overflow = maxReceive % amountPerOutput; for( PartP2PFEPower target : PartP2PFEPower.this.getOutputs() ) { final IEnergyStorage output = target.getAttachedEnergyStorage(); final int toSend = amountPerOutput + overflow; final int received = output.receiveEnergy( toSend, simulate ); overflow = toSend - received; total += received; } PartP2PFEPower.this.queueTunnelDrain( PowerUnits.RF, total ); } catch( GridAccessException ignored ) { } return total; }
Source:
<code><START> public void setRestoring(boolean isRestoring) { <END> this.isRestore.set(isRestoring); }</code><technical_language>setting anywhere</technical_language>

Target:
public void setRestoring(boolean isRestoring) { this.isRestoring.set(isRestoring); }