auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public NetworkView mapRow(ResultSet rs, int rowNum) throws SQLException { NetworkView entity = new NetworkView(); Network network = new Network(); <START> network.setId(Guid.createGuidFromString(rs.getString("network_id"))); <END> network.setname(rs.getString("network_name")); network.setdescription(rs.getString("network_description")); network.settype((Integer) rs.getObject("network_type")); network.setaddr(rs.getString("addr")); network.setsubnet(rs.getString("subnet")); network.setgateway(rs.getString("gateway")); network.setvlan_id((Integer) rs.getObject("vlan_id")); network.setstp(rs.getBoolean("stp")); network.setstorage_pool_id(NGuid.createGuidFromString(rs.getString("storage_pool_id"))); network.setMtu(rs.getInt("mtu")); network.setVmNetwork(rs.getBoolean("vm_network")); entity.setNetwork(network); entity.setStoragePoolName(rs.getString("storage_pool_name")); entity.setCompatabilityVersion(new Version(rs.getString("compatibility_version"))); return entity; }</code><technical_language>I consider re-using org.ovirt.engine.core.dao.NetworkDAODbFacadeImpl.NetworkRowMapper main entity in question, changing field names in view (otherwise work) -or- some approach reuse bulk of code</technical_language>

Target:
public NetworkView mapRow(ResultSet rs, int rowNum) throws SQLException { NetworkView entity = new NetworkView(); entity.setNetwork(NetworkRowMapper.instance.mapRow(rs, rowNum)); entity.setStoragePoolName(rs.getString("storage_pool_name")); entity.setCompatabilityVersion(new Version(rs.getString("compatibility_version"))); return entity; }
Source:
<code>public Client(String publicKey, String secretKey) throws ClientException { Preconditions.checkNotNull(secretKey); Config config = new Config(Endpoint.API_VERSION, publicKey, secretKey); httpClient = buildHttpClient(config); Serializer serializer = Serializer.defaultSerializer(); <START> requester = new RequesterImpl(httpClient, serializer); <END> balance = new BalanceResource(httpClient); charges = new ChargeResource(httpClient); customers = new CustomerResource(httpClient); disputes = new DisputeResource(httpClient); events = new EventResource(httpClient); forexes = new ForexResource(httpClient); links = new LinkResource(httpClient); occurrences = new OccurrenceResource(httpClient); receipts = new ReceiptResource(httpClient); recipients = new RecipientResource(httpClient); schedules = new ScheduleResource(httpClient); tokens = new TokenResource(httpClient); transactions = new TransactionResource(httpClient); transfers = new TransferResource(httpClient); sources = new SourceResource(httpClient); }</code><technical_language>@Namiii allow configuration of implementation add app engine support in future</technical_language>

Target:
public Client(String publicKey, String secretKey) throws ClientException { Preconditions.checkNotNull(secretKey); Config config = new Config(Endpoint.API_VERSION, publicKey, secretKey); httpClient = buildHttpClient(config); Serializer serializer = Serializer.defaultSerializer(); requester = new RequesterImpl(httpClient, serializer); initResources(); }
Source:
<code><START> public void addBuild(AbstractBuild<?, ?> build, PrintStream logger) { <END> if (project == null) { project = build.getProject(); } loadPlotData(); for (Series series : getSeries()) { if (series == null) { continue; } List<PlotPoint> seriesData = series.loadSeries( build.getWorkspace(), build.getNumber(), logger); if (seriesData != null) { for (PlotPoint point : seriesData) { if (point == null) { continue; } rawPlotData.add(new String[] { point.getYvalue(), point.getLabel(), build.getNumber() + "", build.getTimestamp().getTimeInMillis() + "", point.getUrl() }); } } } savePlotData(); }</code><technical_language>remove duplicate logic invoke version a Run? a lot of this condensed</technical_language>

Target:
public void addBuild(AbstractBuild<?, ?> build, PrintStream logger) { addBuild(build, logger, build.getWorkspace()); }
Source:
<code>public void fire(final Connection conn, final Object[] oldRow, final Object[] newRow) throws SQLException { final int updateCount; final int orgId = (int) (oldRow != null ? oldRow[_orgIndex] : newRow[_orgIndex]); Logger.info("Updating etag for organization " + orgId); try (final PreparedStatement stmt = conn.prepareStatement(_updateStatement)) { <START> stmt.setInt(1, orgId); <END> stmt.execute(); updateCount = stmt.getUpdateCount(); } if (updateCount == 0) { try (final PreparedStatement insert = conn.prepareStatement(_updateStatement)) { insert.setInt(1, orgId); insert.execute(); } } Logger.info("Done updating etag for organization " + orgId); }</code><technical_language>named positional arguments. I supported EBean</technical_language>

Target:
public void fire(final Connection conn, final Object[] oldRow, final Object[] newRow) throws SQLException { final long orgId = (long) (oldRow != null ? oldRow[_orgIndex] : newRow[_orgIndex]); final Organization org = Organization.refById(orgId); _incrementEtag.accept(org); }
Source:
<code>public List<NameKey> getParentCandidates() throws OrmException { final List<Project.NameKey> r = new ArrayList<Project.NameKey>(); for (final Project p : db.projects().getAllOrderedByParent()) { try { if (p.getParent() != null) { ProjectControl c = projectControlFactory.controlFor(p.getParent()); <START> if (user.isAdministrator() || c.isVisible() || c.isOwner()) { <END> if (!r.contains(p.getParent()) && !p.getParent().equals(wp)) { r.add(p.getParent()); } } } } catch (NoSuchProjectException e) { continue; } } return r; }</code><technical_language>c.isOwner imply user.isAdministrator</technical_language>

Target:
public List<NameKey> getParentCandidates() throws OrmException { final List<Project.NameKey> r = new ArrayList<Project.NameKey>(); for (final Project p : db.projects().getAllOrderedByParent()) { try { if (p.getParent() != null) { ProjectControl c = projectControlFactory.controlFor(p.getParent()); if (c.isVisible() || c.isOwner()) { if (!r.contains(p.getParent()) && !p.getParent().equals(wildProject)) { r.add(p.getParent()); } } } } catch (NoSuchProjectException e) { continue; } } return r; }
Source:
<code>public void testHandleIoTune() { qos.setMaxThroughput(100); qos.setMaxIops(10000); VmInfoBuilder.handleIoTune(vmDevice, DISK_ID); Map<String, Long> ioTune = (Map<String, Long>) vmDevice.getSpecParams().get(VdsProperties.Iotune); assertIoTune(ioTune, 100L * <START> 1024L * 1024L, 0, <END> 0, 10000, 0, 0); }</code><technical_language>Consider constants for values this, in other test class increase readability</technical_language>

Target:
public void testHandleIoTune() { qos.setMaxThroughput(100); qos.setMaxIops(10000); VmInfoBuilder.handleIoTune(vmDevice, DISK_ID); Map<String, Long> ioTune = (Map<String, Long>) vmDevice.getSpecParams().get(VdsProperties.Iotune); assertIoTune(ioTune, 100L * MB_TO_BYTES, 0, 0, 10000, 0, 0); }
Source:
<code>public void deregisterSpecialPathInfo( SpecialPathInfo pathInfo, String pkgType ) { <START> for ( Map.Entry<String, SpecialPathSet> entry : pkgtypes.entrySet() ) <END> { if ( pkgType.equals( entry.getKey() ) ) { entry.getValue().deregisterSpecialPathInfo( pathInfo ); } } }</code><technical_language>pkgtypes.get(pkgType)..</technical_language>

Target:
public void deregisterSpecialPathInfo( SpecialPathInfo pathInfo, String pkgType ) { pkgtypes.get(pkgType).deregisterSpecialPathInfo( pathInfo ); }
Source:
<code>public Sequence selectInputSequence(SimpleList<Sequence> candidates) { <START> double totalWeight = updateWeightMapForCandidates(candidates); <END> Sequence selectedSequence = Randomness.randomMemberWeighted(candidates, weightMap, totalWeight); incrementCountInMap(sequenceSelectionCount, selectedSequence); return selectedSequence; }</code><technical_language>In other pull requests, mechanisms ensured necessary recompute weight for selection. this trick</technical_language>

Target:
public Sequence selectInputSequence(SimpleList<Sequence> candidates) { double totalWeight = computeTotalWeightForCandidates(candidates); Sequence selectedSequence = Randomness.randomMemberWeighted(candidates, weightMap, totalWeight); SequenceDetails sequenceDetails = sequenceDetailsMap.get(selectedSequence); sequenceDetails.incrementSelectionCount(); sequenceDetails.updateWeight(); weightMap.put(selectedSequence, sequenceDetails.getWeight()); return selectedSequence; }
Source:
<code>public Response execute(ResourcePersistenceAPI api) throws Throwable; } private Response execute(Worker worker) throws WebApplicationException { ResourcePersistenceAPI api = null; try { api = persistenceFactory.getInstance(ZEN_CHART); return worker.execute(api); } catch (WebApplicationException w) { throw w; <START> } catch (Throwable t) { <END> throw new WebApplicationException(Utils.getErrorResponse( Utils.NOT_SPECIFIED, 500, "Exception while accessing resource", t.getMessage())); } finally { if (api != null) { persistenceFactory.returnInstance(api); } } }</code><technical_language>catch Throwable sort of JVM error. catch blanket Exception wan't some special handling. Exceptions thrown out jersey result in a 50x error default. web specific exceptions thrown remote/resource class</technical_language>

Target:
public Response execute(ResourcePersistenceAPI api) throws Exception; } private Response execute(Worker worker) throws WebApplicationException { ResourcePersistenceAPI api = null; try { api = persistenceFactory.getInstance(ZEN_CHART); return worker.execute(api); } catch (WebApplicationException w) { throw w; } catch (Exception e) { throw new WebApplicationException(Utils.getErrorResponse( Utils.NOT_SPECIFIED, 500, "Exception while accessing resource", e.getMessage())); } finally { if (api != null) { persistenceFactory.returnInstance(api); } } }
Source:
<code>protected Pair<Boolean, EngineFault> runConnectionStorageToDomain(StorageDomain storageDomain, Guid vdsId, int type, LUNs lun, Guid storagePoolId) { <START> if(storagePoolId == null || storagePoolId.equals(Guid.Empty)){ <END> return new Pair<>(false, null); } if (FeatureSupported.refreshLunSupported(DbFacade.getInstance() .getStoragePoolDao() .get(storagePoolId) .getCompatibilityVersion())) { VDSReturnValue returnValue = Backend .getInstance() .getResourceManager() .RunVdsCommand( VDSCommandType.forValue(type), new StorageServerConnectionManagementVDSParameters(vdsId, storagePoolId, StorageType.FCP, Arrays.asList(getFCPConnection()))); boolean isSuccess = returnValue.getSucceeded(); EngineFault engineFault = null; if (!isSuccess && returnValue.getVdsError() != null) { engineFault = new EngineFault(); engineFault.setError(returnValue.getVdsError().getCode()); } return new Pair<>(isSuccess, engineFault); } else { return new Pair<>(true, null); } }</code><technical_language>replace Guid.isNullOrEmpty(..) want return false current behavior (which is equivalent retun ture) , if operations depend connect operation fail "later" in calling flows..it before. do think? checked safe return false in case callers? fail flows</technical_language>

Target:
protected Pair<Boolean, EngineFault> runConnectionStorageToDomain(StorageDomain storageDomain, Guid vdsId, int type, LUNs lun, Guid storagePoolId) { if (Guid.isNullOrEmpty(storagePoolId)) { return new Pair<>(true, null); } if (FeatureSupported.refreshLunSupported(DbFacade.getInstance() .getStoragePoolDao() .get(storagePoolId) .getCompatibilityVersion())) { VDSReturnValue returnValue = Backend .getInstance() .getResourceManager() .RunVdsCommand( VDSCommandType.forValue(type), new StorageServerConnectionManagementVDSParameters(vdsId, storagePoolId, StorageType.FCP, Arrays.asList(getFCPConnection()))); boolean isSuccess = returnValue.getSucceeded(); EngineFault engineFault = null; if (!isSuccess && returnValue.getVdsError() != null) { engineFault = new EngineFault(); engineFault.setError(returnValue.getVdsError().getCode()); } return new Pair<>(isSuccess, engineFault); } else { return new Pair<>(true, null); } }
Source:
<code>private static ITmfTimeAligned getReferenceView(TmfTimeViewAlignmentInfo alignmentInfo, TmfView blackListedView) { IWorkbenchPage page = getWorkbenchWindow(alignmentInfo.getShell()).getActivePage(); int lowestTimeAxisOffset = Integer.MAX_VALUE; ITmfTimeAligned referenceView = null; for (IViewReference ref : page.getViewReferences()) { IViewPart view = ref.getView(false); if (view != blackListedView && view instanceof TmfView && view instanceof ITmfTimeAligned) { TmfView tmfView = (TmfView) view; ITmfTimeAligned alignedView = (ITmfTimeAligned) view; Composite parentComposite = tmfView.getParentComposite(); TmfTimeViewAlignmentInfo timeViewAlignmentInfo = alignedView.getTimeViewAlignmentInfo(); <START> if (parentComposite != null && parentComposite.isVisible() && timeViewAlignmentInfo != null && isViewLocationNear(alignmentInfo.getViewLocation(), getViewLocation(tmfView)) <END> && alignedView.getAvailableWidth(timeViewAlignmentInfo.getTimeAxisOffset()) > 0 && timeViewAlignmentInfo.getTimeAxisOffset() < lowestTimeAxisOffset) { referenceView = (ITmfTimeAligned) view; lowestTimeAxisOffset = timeViewAlignmentInfo.getTimeAxisOffset(); break; } } } return referenceView; }</code><technical_language>this put a method</technical_language>

Target:
private static ITmfTimeAligned getReferenceView(TmfTimeViewAlignmentInfo alignmentInfo, TmfView blackListedView) { IWorkbenchPage page = getWorkbenchWindow(alignmentInfo.getShell()).getActivePage(); int lowestTimeAxisOffset = Integer.MAX_VALUE; ITmfTimeAligned referenceView = null; for (IViewReference ref : page.getViewReferences()) { IViewPart view = ref.getView(false); if (view != blackListedView && isTimeAlignedView(view)) { if (isCandidateForReferenceView((TmfView) view, alignmentInfo, lowestTimeAxisOffset)) { referenceView = (ITmfTimeAligned) view; lowestTimeAxisOffset = getClampedTimeAxisOffset(referenceView.getTimeViewAlignmentInfo()); break; } } } return referenceView; }
Source:
<code><START> protected final Integer readVarInteger() throws IOException <END> { long retvalue = 0; boolean is_negative = false; int b; done: for (;;) { if ((b = read()) < 0) throwUnexpectedEOFException(); if ((b & 0x40) != 0) { is_negative = true; } retvalue = (b & 0x3F); if ((b & 0x80) != 0) break done; if ((b = read()) < 0) throwUnexpectedEOFException(); retvalue = (retvalue << 7) | (b & 0x7F); if ((b & 0x80) != 0) break done; if ((b = read()) < 0) throwUnexpectedEOFException(); retvalue = (retvalue << 7) | (b & 0x7F); if ((b & 0x80) != 0) break done; if ((b = read()) < 0) throwUnexpectedEOFException(); retvalue = (retvalue << 7) | (b & 0x7F); if ((b & 0x80) != 0) break done; if ((b = read()) < 0) throwUnexpectedEOFException(); retvalue = (retvalue << 7) | (b & 0x7F); if ((b & 0x80) != 0) break done; throwVarIntOverflowException(); } if (is_negative) { retvalue = -retvalue; } int retValueAsInt = (int) retvalue; if(retvalue != ((long)retValueAsInt)) { throwVarIntOverflowException(); } if (is_negative && retValueAsInt == 0) { return null; } return retValueAsInt; }</code><technical_language>consider a single impl for readVarInt() readVarInteger()</technical_language>

Target:
protected final Integer readVarInteger() throws IOException { int firstByte = read(); if (firstByte == 0xC0) { return null; } return readVarInt(firstByte); }
Source:
<code>private static void populateTestRegions() { Cache cache = CacheFactory.getAnyInstance(); Region<String, String> replicateRegion = cache.getRegion(REPLICATE_REGION_NAME); replicateRegion.put(EMPTY_STRING, "valueForEmptyKey"); <START> replicateRegion.put("key1", "value1"); <END> replicateRegion.put("key2", "value2"); Region<String, String> partitionedRegion = cache.getRegion(PARTITIONED_REGION_NAME); partitionedRegion.put("key1", "value1"); partitionedRegion.put("key2", "value2"); }</code><technical_language>I putting more values here, ensure bucket key. Buckets fully created data is put them, keys, system is in a realistic state</technical_language>

Target:
private static void populateTestRegions() { Cache cache = CacheFactory.getAnyInstance(); Region<String, String> replicateRegion = cache.getRegion(REPLICATE_REGION_NAME); replicateRegion.put(EMPTY_STRING, "valueForEmptyKey"); for (int i = 0; i < NUM_ENTRIES; i++) { replicateRegion.put("key" + i, "value" + i); } Region<String, String> partitionedRegion = cache.getRegion(PARTITIONED_REGION_NAME); replicateRegion.put(EMPTY_STRING, "valueForEmptyKey"); for (int i = 0; i < NUM_ENTRIES; i++) { partitionedRegion.put("key" + i, "value" + i); } }
Source:
<code>private void applySeverityAndParamToChange(RuleActivation request, RuleActivatorContext context, ActiveRuleChange change) { String severity; if (request.isReset()) { severity = firstNonNull(context.parentSeverity(), context.defaultSeverity()); } else if (context.getRulesProfile().isBuiltIn()) { severity = firstNonNull(request.getSeverity(), context.defaultSeverity()); } else { severity = firstNonNull(request.getSeverity(), context.currentSeverity(), context.parentSeverity(), context.defaultSeverity()); } change.setSeverity(severity); for (RuleParamDto ruleParamDto : context.ruleParams()) { String paramKey = ruleParamDto.getName(); String paramValue; if (request.isReset()) { paramValue = firstNonNull(context.parentParamValue(paramKey), context.defaultParamValue(paramKey)); } else if (context.getRulesProfile().isBuiltIn()) { paramValue = firstNonNull(context.requestParamValue(request, paramKey), context.defaultParamValue(paramKey)); } else { paramValue = context.hasRequestParamValue(request, paramKey) ? firstNonNull( context.requestParamValue(request, paramKey), context.parentParamValue(paramKey), context.defaultParamValue(paramKey)) : firstNonNull( context.currentParamValue(paramKey), context.parentParamValue(paramKey), context.defaultParamValue(paramKey)); change.setParameter(paramKey, validateParam(ruleParamDto, paramValue)); } <START> change.setParameter(paramKey, validateParam(ruleParamDto, firstNonNull(paramValue))); <END> } }</code><technical_language>firstNonNull() is useless of single parameter</technical_language>

Target:
private void applySeverityAndParamToChange(RuleActivation request, RuleActivatorContext context, ActiveRuleChange change) { String severity; if (request.isReset()) { severity = firstNonNull(context.parentSeverity(), context.defaultSeverity()); } else if (context.getRulesProfile().isBuiltIn()) { severity = firstNonNull(request.getSeverity(), context.defaultSeverity()); } else { severity = firstNonNull(request.getSeverity(), context.currentSeverity(), context.parentSeverity(), context.defaultSeverity()); } change.setSeverity(severity); for (RuleParamDto ruleParamDto : context.ruleParams()) { String paramKey = ruleParamDto.getName(); String paramValue; if (request.isReset()) { paramValue = firstNonNull(context.parentParamValue(paramKey), context.defaultParamValue(paramKey)); } else if (context.getRulesProfile().isBuiltIn()) { paramValue = firstNonNull(context.requestParamValue(request, paramKey), context.defaultParamValue(paramKey)); } else { paramValue = context.hasRequestParamValue(request, paramKey) ? firstNonNull( context.requestParamValue(request, paramKey), context.parentParamValue(paramKey), context.defaultParamValue(paramKey)) : firstNonNull( context.currentParamValue(paramKey), context.parentParamValue(paramKey), context.defaultParamValue(paramKey)); } change.setParameter(paramKey, validateParam(ruleParamDto, paramValue)); } }
Source:
<code>private void setPlatformPropertiesToState(Dictionary<Object, Object> props) { Properties platformProperties = setDefaultPlatformProperties(); for (Enumeration<Object> enumeration = props.keys(); enumeration.hasMoreElements();) { String key = (String) enumeration.nextElement(); for (String <START> PROPS1 : <END> PROPS) { if (key.equals(PROPS1)) { platformProperties.put(key, props.get(key)); break; } } } platformProperties.put("osgi.resolver.usesMode", "ignore"); state.setPlatformProperties(platformProperties); }</code><technical_language>this is naming convention - variable CONSTANT name</technical_language>

Target:
private void setPlatformPropertiesToState(Dictionary<Object, Object> props) { Properties platformProperties = setDefaultPlatformProperties(); for (Enumeration<Object> enumeration = props.keys(); enumeration.hasMoreElements();) { String key = (String) enumeration.nextElement(); for (String property : PROPS) { if (key.equals(property)) { platformProperties.put(key, props.get(key)); break; } } } platformProperties.put("osgi.resolver.usesMode", "ignore"); state.setPlatformProperties(platformProperties); }
Source:
<code>public void makeBucket(String bucketName, String region, boolean objectLock) throws InvalidBucketNameException, IllegalArgumentException, RegionConflictException, NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, XmlParserException, ErrorResponseException, InternalException, InvalidResponseException { if (region == null) { region = this.region; } if (this.region != null && !this.region.equals(region)) { throw new RegionConflictException( "passed region conflicts with the one previously specified"); } String configString = ""; if (region != null && !region.equals(US_EAST_1)) { CreateBucketConfiguration config = new CreateBucketConfiguration(region); <START> configString = config.toString(); <END> } Map<String, String> headerMap = null; if (objectLock) { headerMap = new HashMap<>(); headerMap.put("x-amz-bucket-object-lock-enabled", "true"); } Response response = executePut(bucketName, null, US_EAST_1, headerMap, null, configString, 0); response.body().close(); }</code><technical_language>@balamurugana I issue is config.toString() is returning XML</technical_language>

Target:
public void makeBucket(String bucketName, String region, boolean objectLock) throws InvalidBucketNameException, IllegalArgumentException, RegionConflictException, NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, XmlParserException, ErrorResponseException, InternalException, InvalidResponseException { if (region == null) { region = this.region; } if (this.region != null && !this.region.equals(region)) { throw new RegionConflictException( "passed region conflicts with the one previously specified"); } if (region == null) { region = US_EAST_1; } CreateBucketConfiguration config = null; if (!region.equals(US_EAST_1)) { config = new CreateBucketConfiguration(region); } Map<String, String> headerMap = null; if (objectLock) { headerMap = new HashMap<>(); headerMap.put("x-amz-bucket-object-lock-enabled", "true"); } Response response = executePut(bucketName, null, region, headerMap, null, config, 0); response.body().close(); }
Source:
<code>public List<CloudResourceStatus> terminate(AuthenticatedContext ac, CloudStack stack, List<CloudResource> resources) { AzureClient client = ac.getParameter(AzureClient.class); String resourceGroupName = azureResourceGroupMetadataProvider.getResourceGroupName(ac.getCloudContext(), stack); Boolean singleResourceGroup = azureResourceGroupMetadataProvider.useSingleResourceGroup(stack); if (singleResourceGroup) { List<CloudResource> cloudResourceList = collectResourcesToRemove(ac, stack, resources, azureUtils.getInstanceList(stack)); resources.addAll(cloudResourceList); azureTerminationHelperService.terminate(ac, stack, resources); return check(ac, Collections.emptyList()); } else { try { try { <START> retryService.testWith2SecDelayMax5Times(() -> { if (!client.resourceGroupExists(resourceGroupName)) { throw new ActionFailedException("Resource group not exists"); } return true; }); <END> client.deleteResourceGroup(resourceGroupName); } catch (ActionFailedException ignored) { LOGGER.debug("Resource group not found with name: {}", resourceGroupName); } } catch (CloudException e) { if (e.response().code() != AzureConstants.NOT_FOUND) { throw new CloudConnectorException(String.format("Could not delete resource group: %s", resourceGroupName), e); } else { return check(ac, Collections.emptyList()); } } return check(ac, resources); } }</code><technical_language>This part AzureUtils</technical_language>

Target:
public List<CloudResourceStatus> terminate(AuthenticatedContext ac, CloudStack stack, List<CloudResource> resources) { AzureClient client = ac.getParameter(AzureClient.class); String resourceGroupName = azureResourceGroupMetadataProvider.getResourceGroupName(ac.getCloudContext(), stack); Boolean singleResourceGroup = azureResourceGroupMetadataProvider.useSingleResourceGroup(stack); if (singleResourceGroup) { List<CloudResource> cloudResourceList = collectResourcesToRemove(ac, stack, resources, azureUtils.getInstanceList(stack)); resources.addAll(cloudResourceList); azureTerminationHelperService.terminate(ac, stack, resources); return check(ac, Collections.emptyList()); } else { try { try { azureUtils.checkResourceGroupExistence(client, resourceGroupName); client.deleteResourceGroup(resourceGroupName); } catch (ActionFailedException ignored) { LOGGER.debug("Resource group not found with name: {}", resourceGroupName); } } catch (CloudException e) { if (e.response().code() != AzureConstants.NOT_FOUND) { throw new CloudConnectorException(String.format("Could not delete resource group: %s", resourceGroupName), e); } else { return check(ac, Collections.emptyList()); } } return check(ac, resources); } }
Source:
<code>public void handleNotification(PayaraNotification event) { if (session == null) { LOGGER.fine("Email notifier received notification, but no Java Mail session was available."); return; } final String message = event.getMessage(); final String subject = String.format("%s. (host: %s, server: %s, domain: %s, instance: %s)", event.getSubject(), event.getHostName(), event.getServerName(), event.getDomainName(), event.getInstanceName()); try { Message mime = new MimeMessage(session); mime.setRecipients(Message.RecipientType.TO, InternetAddress.parse(configuration.getRecipient())); mime.setSubject(subject); mime.setText(message); Transport.send(mime); LOGGER.log(Level.FINE, "Email successfully sent"); } catch (IllegalArgumentException e) { <START> LOGGER.log(Level.SEVERE, "mail configuration properties are not provided carefully.", e); <END> } catch (AuthenticationFailedException e) { LOGGER.log(Level.SEVERE, "Username and Password not accepted.", e); } catch (SendFailedException e) { LOGGER.log(Level.SEVERE, "Cannot send to specified recipient", e); } catch (MessagingException e) { LOGGER.log(Level.SEVERE, "Error occurred while trying to send mail.", e); } }</code><technical_language>suggestion LOGGER.log(Level.SEVERE, "Email configuration properties provided correctly.", e);</technical_language>

Target:
public void handleNotification(PayaraNotification event) { if (session == null) { LOGGER.fine("Email notifier received notification, but no Java Mail session was available."); return; } final String message = event.getMessage(); final String subject = String.format("%s. (host: %s, server: %s, domain: %s, instance: %s)", event.getSubject(), event.getHostName(), event.getServerName(), event.getDomainName(), event.getInstanceName()); try { Message mime = new MimeMessage(session); mime.setRecipients(Message.RecipientType.TO, InternetAddress.parse(configuration.getRecipient())); mime.setSubject(subject); mime.setText(message); Transport.send(mime); LOGGER.log(Level.FINE, "Email successfully sent"); } catch (IllegalArgumentException e) { LOGGER.log(Level.SEVERE, "Email configuration properties were not provided correctly.", e); } catch (AuthenticationFailedException e) { LOGGER.log(Level.SEVERE, "Username and Password not accepted.", e); } catch (SendFailedException e) { LOGGER.log(Level.SEVERE, "Cannot send to specified recipient", e); } catch (MessagingException e) { LOGGER.log(Level.SEVERE, "Error occurred while trying to send mail.", e); } }
Source:
<code>public void kill(Process process) { if (C_LIBRARY != null) { killTree(getPid(process)); } else { <START> throw new IllegalStateException("Cannot terminate process. Not a UNIX system?"); <END> } }</code><technical_language>Is this terminating, sending a specific signal (there TERM KILL signals)</technical_language>

Target:
public void kill(Process process) { if (C_LIBRARY != null) { killTree(getPid(process)); } else { throw new IllegalStateException("Cannot kill process. Not a UNIX system?"); } }
Source:
<code>public void testDefaultAccessorCreateCustomData() { String className = TestHelper.getTestClassName(); String methodName = TestHelper.getTestMethodName(); String testName = className + "_" + methodName; System.out.println("START " + testName + " at " + new Date(System.currentTimeMillis())); String path = String.format("/%s/%s", _rootPath, "msg_0"); <START> ZkBaseDataAccessor defaultAccessor = new ZkBaseDataAccessor(ZK_ADDR); <END> List<Integer> l0 = ImmutableList.of(1, 2, 3); boolean createResult = defaultAccessor.create(path, l0, AccessOption.PERSISTENT); Assert.assertFalse(createResult); createResult = defaultAccessor.create(path, new ZNRecord("test"), AccessOption.PERSISTENT); Assert.assertTrue(createResult); }</code><technical_language>Please close this defaultAccessor end of test prevent a ZkClient leak</technical_language>

Target:
public void testDefaultAccessorCreateCustomData() { String className = TestHelper.getTestClassName(); String methodName = TestHelper.getTestMethodName(); String testName = className + "_" + methodName; System.out.println("START " + testName + " at " + new Date(System.currentTimeMillis())); String path = String.format("/%s/%s", _rootPath, "msg_0"); ZkBaseDataAccessor defaultAccessor = new ZkBaseDataAccessor(ZK_ADDR); List<Integer> l0 = ImmutableList.of(1, 2, 3); boolean createResult = defaultAccessor.create(path, l0, AccessOption.PERSISTENT); Assert.assertFalse(createResult); createResult = defaultAccessor.create(path, new ZNRecord("test"), AccessOption.PERSISTENT); Assert.assertTrue(createResult); defaultAccessor.close(); System.out.println("END " + testName + " at " + new Date(System.currentTimeMillis())); }
Source:
<code><START> public LBClient(ILoadBalancer lb, IClientConfig clientConfig) { <END> super(lb, clientConfig); this.setRetryHandler(RetryHandler.DEFAULT); this.clientConfig = clientConfig; connectTimeout = clientConfig.get(CommonClientConfigKey.ConnectTimeout); readTimeout = clientConfig.get(CommonClientConfigKey.ReadTimeout); }</code><technical_language>hide this expose factory method</technical_language>

Target:
LBClient(ILoadBalancer lb, IClientConfig clientConfig) { super(lb, clientConfig); this.setRetryHandler(RetryHandler.DEFAULT); this.clientConfig = clientConfig; connectTimeout = clientConfig.get(CommonClientConfigKey.ConnectTimeout); readTimeout = clientConfig.get(CommonClientConfigKey.ReadTimeout); }
Source:
<code>public IPatient createPatient(int userID, String firstName, String lastName, String phoneNumber, Date birthday, String sex, String address, String city, Integer photoID) { if (userID < 0 || StringUtils.isNullOrWhiteSpace(firstName) || StringUtils.isNullOrWhiteSpace(lastName)) { return null; } IPatient patient = patientProvider.get(); patient.setUserId(userID); patient.setFirstName(firstName); patient.setLastName(lastName); <START> patient.setPhoneNumber(phoneNumber); <END> if (birthday != null) patient.setAge(birthday); patient.setSex(sex); patient.setAddress(address); patient.setCity(city); if (photoID != null) patient.setPhoto(Ebean.getReference(photoProvider.get().getClass(), photoID)); return patient; }</code><technical_language>needs a NULL check phone_number column empty string instead of NULL. Assuming this is intention..</technical_language>

Target:
public IPatient createPatient(int userID, String firstName, String lastName, String phoneNumber, Date birthday, String sex, String address, String city, Integer photoID) { if (userID < 0 || StringUtils.isNullOrWhiteSpace(firstName) || StringUtils.isNullOrWhiteSpace(lastName)) { return null; } IPatient patient = patientProvider.get(); patient.setUserId(userID); patient.setFirstName(firstName); patient.setLastName(lastName); if (StringUtils.isNotNullOrWhiteSpace(phoneNumber)) patient.setPhoneNumber(phoneNumber); if (birthday != null) patient.setAge(birthday); patient.setSex(sex); patient.setAddress(address); patient.setCity(city); if (photoID != null) patient.setPhoto(Ebean.getReference(photoProvider.get().getClass(), photoID)); return patient; }
Source:
<code>public static Map<String, Serializable> getFileMetadata( final Session session, final Serializable fileId ) throws ItemNotFoundException, RepositoryException { Map<String, Serializable> values = new HashMap<String, Serializable>(); String prefix = session.getNamespacePrefix( PentahoJcrConstants.PHO_NS ); Node fileNode; try { fileNode = session.getNodeByIdentifier( fileId.toString() ); } catch ( ItemNotFoundException e ) { <START> return values; <END> } PentahoJcrConstants pentahoJcrConstants = new PentahoJcrConstants( session ); String metadataNodeName = pentahoJcrConstants.getPHO_METADATA(); Node metadataNode = null; try { metadataNode = NodeHelper.checkGetNode( fileNode, metadataNodeName ); } catch ( PathNotFoundException pathNotFound ) { return values; } PropertyIterator iter = metadataNode.getProperties( prefix + ":*" ); while ( iter.hasNext() ) { Property property = iter.nextProperty(); String key = property.getName().substring( property.getName().indexOf( ':' ) + 1 ); Serializable value = null; switch ( property.getType() ) { case PropertyType.STRING: value = property.getString(); break; case PropertyType.DATE: value = property.getDate(); break; case PropertyType.DOUBLE: value = property.getDouble(); break; case PropertyType.LONG: value = property.getLong(); break; case PropertyType.BOOLEAN: value = property.getBoolean(); break; } if ( value != null ) { values.put( key, value ); } } return values; }</code><technical_language>this is correct. If item found, "pretending" is OK returning map anyway. correct throw exception? Minimally, exception logged, a warning log is amiss</technical_language>

Target:
public static Map<String, Serializable> getFileMetadata( final Session session, final Serializable fileId ) throws ItemNotFoundException, RepositoryException { Map<String, Serializable> values = new HashMap<String, Serializable>(); String prefix = session.getNamespacePrefix( PentahoJcrConstants.PHO_NS ); Node fileNode = session.getNodeByIdentifier( fileId.toString() ); PentahoJcrConstants pentahoJcrConstants = new PentahoJcrConstants( session ); String metadataNodeName = pentahoJcrConstants.getPHO_METADATA(); Node metadataNode = null; try { metadataNode = NodeHelper.checkGetNode( fileNode, metadataNodeName ); } catch ( PathNotFoundException pathNotFound ) { return values; } PropertyIterator iter = metadataNode.getProperties( prefix + ":*" ); while ( iter.hasNext() ) { Property property = iter.nextProperty(); String key = property.getName().substring( property.getName().indexOf( ':' ) + 1 ); Serializable value = null; switch ( property.getType() ) { case PropertyType.STRING: value = property.getString(); break; case PropertyType.DATE: value = property.getDate(); break; case PropertyType.DOUBLE: value = property.getDouble(); break; case PropertyType.LONG: value = property.getLong(); break; case PropertyType.BOOLEAN: value = property.getBoolean(); break; } if ( value != null ) { values.put( key, value ); } } return values; }
Source:
<code>public ResultSet executeCommand(String <START> command) { <END> openConnection(); ResultSet rs = null; try { rs = stat.executeQuery(command); } catch (SQLException e) { e.printStackTrace(); } closeConnection(); return rs; }</code><technical_language>if command is null empty? A null/empty check cool</technical_language>

Target:
public ResultSet executeCommand(String command) { openConnection(); ResultSet resultSet = null; try { resultSet = statement.executeQuery(command); } catch (SQLException e) { e.printStackTrace(); } closeConnection(); return resultSet; }
Source:
<code>public Token(Locator locator, String[] tokens, int level) { if (level > tokens.length - 1) throw new IllegalArgumentException("Invalid level for the given tokens"); this.locator = locator; <START> this.token = tokens[level]; <END> this.isLeaf = level == tokens.length - 1; String prefix = locator.getTenantId() + Token.SEPARATOR; this.parent = joinTokens("", "", tokens, level); String suffix = isLeaf ? LEAF_NODE_SUFFIX : ""; this.id = joinTokens(prefix, suffix, tokens, level + 1); }</code><technical_language>Do want add more checks size of array itself</technical_language>

Target:
public Token(Locator locator, String[] tokens, int level) { if (tokens == null || tokens.length <= 0) throw new IllegalArgumentException("Invalid tokens. Must be an array of size " + "greater than 0, representing tokens of a metric name."); if (level < 0 || level > tokens.length - 1) throw new IllegalArgumentException("Invalid level for the given tokens"); this.locator = locator; this.token = tokens[level]; this.isLeaf = level == tokens.length - 1; String prefix = locator.getTenantId() + Token.SEPARATOR; this.parent = joinTokens("", "", tokens, level); String suffix = isLeaf ? LEAF_NODE_SUFFIX : ""; this.id = joinTokens(prefix, suffix, tokens, level + 1); }
Source:
<code>static URL substitute(URL input, String variable, String substitution) throws IOException { File output = File.createTempFile(input.getFile(), ".substituted", new File("build")); <START> try (BufferedWriter writer = new BufferedWriter(new FileWriter(output))) { <END> try (BufferedReader reader = new BufferedReader(new InputStreamReader(input.openStream(), "UTF-8"))) { while (true) { String line = reader.readLine(); if (line == null) { break; } else { writer.write(line.replace("${" + variable + "}", substitution)); writer.newLine(); } } } } return output.toURI().toURL(); }</code><technical_language>in a single try</technical_language>

Target:
static URL substitute(URL input, String variable, String substitution) throws IOException { File output = File.createTempFile(input.getFile(), ".substituted", new File("build")); try (BufferedWriter writer = new BufferedWriter(new FileWriter(output)); BufferedReader reader = new BufferedReader(new InputStreamReader(input.openStream(), "UTF-8"))) { while (true) { String line = reader.readLine(); if (line == null) { break; } else { writer.write(line.replace("${" + variable + "}", substitution)); writer.newLine(); } } } return output.toURI().toURL(); }
Source:
<code>public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); return true; case R.id.search_posts_list: <START> mSearchMenuItem = item; <END> mSearchView = (SearchView) item.getActionView(); mSearchView.setOnQueryTextListener(this); if (!NetworkUtils.checkConnection(this)) { mSearchView.clearFocus(); MenuItemCompat.collapseActionView(mSearchMenuItem); } else { MenuItemCompat.setOnActionExpandListener(mSearchMenuItem, this); MenuItemCompat.expandActionView(mSearchMenuItem); if (!TextUtils.isEmpty(mQuery)) { onQueryTextSubmit(mQuery); mSearchView.setQuery(mQuery, true); } } return true; default: return super.onOptionsItemSelected(item); } }</code><technical_language>Do need this set mSearchMenuItem in onCreateOptionsMenu</technical_language>

Target:
public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); return true; case R.id.search_posts_list: onSearchPostsListSelected(); return true; default: return super.onOptionsItemSelected(item); } }
Source:
<code>public boolean onActionItemClicked(ActionMode mode, MenuItem item) { switch (item.getItemId()) { case Menu.FIRST: if (mLabel == mAddedLabel) { addIssue(); } else { editIssueLabel(); } break; case Menu.FIRST + 1: new AlertDialog.Builder(IssueLabelListActivity.this) .setMessage(getString(R.string.issue_dialog_delete_message, mLabel.getName())) .setPositiveButton(R.string.delete, (dialog, whichButton) -> { IssuesLabelService <START> .deleteIssueLabel(IssueLabelListActivity.this, getRootLayout(), mRepoOwner, mRepoName, mLabel.getName()) <END> .subscribe(result -> { forceLoaderReload(0); setResult(RESULT_OK); }, e -> {}); }) .setNegativeButton(R.string.cancel, null) .show(); break; default: break; } mode.finish(); return true; }</code><technical_language>Code style: please line lengths <= 100 chars. Github's web UI show full text</technical_language>

Target:
public boolean onActionItemClicked(ActionMode mode, MenuItem item) { switch (item.getItemId()) { case Menu.FIRST: if (mLabel == mAddedLabel) { addIssue(); } else { editIssueLabel(); } break; case Menu.FIRST + 1: new AlertDialog.Builder(IssueLabelListActivity.this) .setMessage(getString(R.string.issue_dialog_delete_message, mLabel.getName())) .setPositiveButton(R.string.delete, (dialog, whichButton) -> { IssuesLabelService .deleteIssueLabel( IssueLabelListActivity.this, mRepoOwner, mRepoName, mLabel.getName() ).subscribe(result -> { forceLoaderReload(0); setResult(RESULT_OK); }, error -> {}); }) .setNegativeButton(R.string.cancel, null) .show(); break; default: break; } mode.finish(); return true; }
Source:
<code>static void validExposedSubsystems(Set<String> subsystems, List<String> exposedSubsystems) throws OperationFailedException { <START> List<String> unkownSubsystems = new LinkedList<>(); <END> for (String esub : exposedSubsystems) { if (!"*".equals(esub) && !subsystems.contains(esub)) { unkownSubsystems.add(esub); } } if (!unkownSubsystems.isEmpty()) { throw MicroProfileMetricsLogger.LOGGER.unknownSubsystems(unkownSubsystems); } }</code><technical_language>suggestion s/unkown/unknown</technical_language>

Target:
static void validExposedSubsystems(Set<String> subsystems, List<String> exposedSubsystems) throws OperationFailedException { List<String> unknownSubsystems = new LinkedList<>(); for (String esub : exposedSubsystems) { if (!"*".equals(esub) && !subsystems.contains(esub)) { unknownSubsystems.add(esub); } } if (!unknownSubsystems.isEmpty()) { throw MicroProfileMetricsLogger.LOGGER.unknownSubsystems(unknownSubsystems); } }
Source:
<code>public void testTimeoutViaSystemProperty() throws Exception { System.setProperty("org.jbpm.cxf.client.connectionTimeout", "10"); System.setProperty("org.jbpm.cxf.client.receiveTimeout", "10"); try { KieBase kbase = readKnowledgeBase(); KieSession ksession = createSession(kbase); ksession.getWorkItemManager().registerWorkItemHandler("Service Task", new WebServiceWorkItemHandler(ksession)); Map<String, Object> params = new HashMap<String, Object>(); params.put("s", "john"); params.put("mode", "sync"); WorkflowProcessInstance processInstance = (WorkflowProcessInstance) ksession.startProcess("org.jboss.qa.jbpm.CallWS", params); fail("should throw Read Timeout error"); } catch (Exception e) { <START> assertTrue(true); <END> } finally { System.clearProperty("org.jbpm.cxf.client.connectionTimeout"); System.clearProperty("org.jbpm.cxf.client.receiveTimeout"); } }</code><technical_language>please assert exception, is timeout error message</technical_language>

Target:
public void testTimeoutViaSystemProperty() throws Exception { System.setProperty("org.jbpm.cxf.client.connectionTimeout", "10"); System.setProperty("org.jbpm.cxf.client.receiveTimeout", "10"); try { KieBase kbase = readKnowledgeBase(); KieSession ksession = createSession(kbase); ksession.getWorkItemManager().registerWorkItemHandler("Service Task", new WebServiceWorkItemHandler(ksession)); Map<String, Object> params = new HashMap<String, Object>(); params.put("s", "john"); params.put("mode", "sync"); WorkflowProcessInstance processInstance = (WorkflowProcessInstance) ksession.startProcess("org.jboss.qa.jbpm.CallWS", params); fail("should throw Read Timeout error"); } catch (Exception e) { assertTrue(isCausedBySocketTimeoutException(e)); } finally { System.clearProperty("org.jbpm.cxf.client.connectionTimeout"); System.clearProperty("org.jbpm.cxf.client.receiveTimeout"); } }
Source:
<code>public static File newTempFile(String prefix, String ext) { String sanitizedPrefix = (prefix!=null ? prefix + "-" : ""); String sanitizedExt = (ext!=null ? ext.startsWith(".") || ext.length()>4 ? ext : "."+ext : ""); try { File tempFile = File.createTempFile(sanitizedPrefix, sanitizedExt, new File(tmp())); tempFile.deleteOnExit(); return tempFile; } catch (IOException e) { <START> Exceptions.propagate(e); <END> return null; } }</code><technical_language>of throw Exceptions.propagate(e) skip needing include a non-reachable return null; throw run of is misleading in a good :)</technical_language>

Target:
public static File newTempFile(String prefix, String ext) { String sanitizedPrefix = (prefix!=null ? prefix + "-" : ""); String sanitizedExt = (ext!=null ? ext.startsWith(".") || ext.length()>4 ? ext : "."+ext : ""); try { File tempFile = File.createTempFile(sanitizedPrefix, sanitizedExt, new File(tmp())); tempFile.deleteOnExit(); return tempFile; } catch (IOException e) { throw Exceptions.propagate(e); } }
Source:
<code>public List<Element> previousElementSiblings() { if (parentNode == null) { return null; } List<Element> siblings = parent().childElementsList(); int index = indexInList(this, siblings); Validate.notNull(index); if (index > 0 && index < siblings.size()) { return siblings.subList(0, index); } <START> return null; <END> }</code><technical_language>Empty list instead of null</technical_language>

Target:
public List<Element> previousElementSiblings() { if (parentNode == null) { return Collections.emptyList(); } List<Element> siblings = parent().childElementsList(); int index = indexInList(this, siblings); Validate.notNull(index); if (index > 0 && index < siblings.size()) { return siblings.subList(0, index); } return Collections.emptyList(); }
Source:
<code>public void calculateMip(double scale, double mapScale, double screenScale) { int size = (int) (16 * scale * viewSize()); if (isTile) { size *= mapScale; } if (icons.length > 1) { int smallestSide = (int) (size * screenScale); int closestValue = Integer.MAX_VALUE; int closestIndex = -1; <START> if(iconSizes != null) { <END> for (int i = 0; i < iconSizes.length; i++) { if (iconSizes[i] < closestValue && iconSizes[i] >= smallestSide) { closestValue = iconSizes[i]; closestIndex = i; } } } if (closestIndex > 0) { iconIndex = closestIndex; } } }</code><technical_language>Please remove this, I fixed in a432e377a8d4e7dd04f2267bc59b1e66ea6d6656</technical_language>

Target:
public void calculateMip(double scale, double mapScale, double screenScale) { int size = (int) (16 * scale * viewSize()); if (isTile) { size *= mapScale; } if (icons.length > 1) { int smallestSide = (int) (size * screenScale); int closestValue = Integer.MAX_VALUE; int closestIndex = -1; for (int i = 0; i < iconSizes.length; i++) { if (iconSizes[i] < closestValue && iconSizes[i] >= smallestSide) { closestValue = iconSizes[i]; closestIndex = i; } } if (closestIndex > 0) { iconIndex = closestIndex; } } }
Source:
<code>public static PushConfiguration read(String location) throws IOException { BufferedReader bufferedReader = null; PushConfiguration pushConfiguration = null; try { bufferedReader = new BufferedReader( new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(location))); Gson gson = new Gson(); pushConfiguration = gson.fromJson(bufferedReader, PushConfiguration.class); <START> pushConfiguration.setServerUrl(!pushConfiguration.getServerUrl().endsWith("/") ? pushConfiguration.getServerUrl() + '/' : pushConfiguration.getServerUrl()); <END> } finally { if (bufferedReader != null) { bufferedReader.close(); } } return pushConfiguration; }</code><technical_language>w/out '/' is set, need reset, no? do: if (!pushConfiguration.getServerUrl().endsWith("/")) { pushConfiguration.setServerUrl(pushConfiguration.getServerUrl() + '/'); }</technical_language>

Target:
public static PushConfiguration read(String location) throws IOException { BufferedReader bufferedReader = null; PushConfiguration pushConfiguration = null; try { bufferedReader = new BufferedReader( new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(location))); Gson gson = new Gson(); pushConfiguration = gson.fromJson(bufferedReader, PushConfiguration.class); if (!pushConfiguration.getServerUrl().endsWith("/")) { pushConfiguration.setServerUrl(pushConfiguration.getServerUrl() + '/'); } } finally { if (bufferedReader != null) { bufferedReader.close(); } } return pushConfiguration; }