auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void setUpClass() throws Exception { mgmt = new LocalManagementContextForTests(BrooklynProperties.Factory.newDefault()); JcloudsLocation loc = (JcloudsLocation) mgmt.getLocationRegistry().resolve("jclouds:aws-ec2:us-west-2", ImmutableMap.of( "inboundPorts", ImmutableList.of(5985, 3389), "displayName", "AWS Oregon (Windows)", <START> "imageNameRegex", ".*Windows.*2012.*", <END> "hardwareId", "m3.medium", "useJcloudsSshInit", false)); machine = (JcloudsWinRmMachineLocation) loc.obtain(); }</code><technical_language>A customer needed image owner, in order avoid a marketplace windows AMI picked. search for AMIs match regex if is a risk? For example: brooklyn.location.named.mywindows1.imageOwner=801119661308 brooklyn.location.named.mywindows1.imageNameRegex=Windows_Server-2012-R2_RTM-English-64Bit-Base-.* This is jclouds integration code (in ComputeServiceRegistryImpl.findComputeService) have: properties.setProperty(PROPERTY_EC2_AMI_QUERY, "owner-id="+conf.getStringKey("imageOwner")+";state=available;image-type=machine"); (It's a bit ugly code there; nicer if a first-class property jclouds' AWSEC2TemplateOptions. improvement in jclouds. nice a config key for imageOwner this hard-coded constant looked in config!)</technical_language>

Target:
public void setUpClass() throws Exception { mgmt = new LocalManagementContextForTests(BrooklynProperties.Factory.newDefault()); JcloudsLocation loc = (JcloudsLocation) mgmt.getLocationRegistry().resolve("jclouds:aws-ec2:us-west-2", ImmutableMap.<String, Object>builder() .put("inboundPorts", ImmutableList.of(5985, 3389)) .put("displayName", "AWS Oregon (Windows)") .put("imageOwner", "801119661308") .put("imageNameRegex", "Windows_Server-2012-R2_RTM-English-64Bit-Base-.*") .put("hardwareId", "m3.medium") .put("useJcloudsSshInit", false) .build()); machine = (JcloudsWinRmMachineLocation) loc.obtain(); }
Source:
<code>public void setAgentConnected(boolean agentConnected) { this.agentConnected = agentConnected; <START> } <END></code><technical_language>need for setter</technical_language>

Target:
protected void setAgentConnected(boolean agentConnected) { this.agentConnected = agentConnected; }
Source:
<code>public void launchImageLibrary(final ReadableMap options, final Callback callback) { final Activity currentActivity = getCurrentActivity(); if (currentActivity == null) { responseHelper.invokeError(callback, "can't find current Activity"); return; } this.callback = callback; this.options = options; if (!permissionsCheck(currentActivity, callback, REQUEST_PERMISSIONS_FOR_LIBRARY)) { return; } parseOptions(this.options); int requestCode; Intent libraryIntent; if (pickVideo) { requestCode = REQUEST_LAUNCH_VIDEO_LIBRARY; libraryIntent = new Intent(Intent.ACTION_PICK); libraryIntent.setType("video/*"); } else { requestCode = REQUEST_LAUNCH_IMAGE_LIBRARY; libraryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); } if (libraryIntent.resolveActivity(reactContext.getPackageManager()) == null) { responseHelper.invokeError(callback, "Cannot launch photo library"); return; } try { <START> currentActivity.startActivityForResult(Intent.createChooser(libraryIntent, "Choose gallery app"), requestCode); <END> } catch (ActivityNotFoundException e) { e.printStackTrace(); responseHelper.invokeError(callback, "Cannot launch photo library"); } }</code><technical_language>Change "Choose gallery app" options instead I merge this</technical_language>

Target:
public void launchImageLibrary(final ReadableMap options, final Callback callback) { final Activity currentActivity = getCurrentActivity(); if (currentActivity == null) { responseHelper.invokeError(callback, "can't find current Activity"); return; } this.callback = callback; this.options = options; if (!permissionsCheck(currentActivity, callback, REQUEST_PERMISSIONS_FOR_LIBRARY)) { return; } parseOptions(this.options); int requestCode; Intent libraryIntent; if (pickVideo) { requestCode = REQUEST_LAUNCH_VIDEO_LIBRARY; libraryIntent = new Intent(Intent.ACTION_PICK); libraryIntent.setType("video/*"); } else { requestCode = REQUEST_LAUNCH_IMAGE_LIBRARY; libraryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); } if (libraryIntent.resolveActivity(reactContext.getPackageManager()) == null) { responseHelper.invokeError(callback, "Cannot launch photo library"); return; } try { String chooseWhichLibraryTitle = null; if (ReadableMapUtils.hasAndNotEmptyString(options, "chooseWhichLibraryTitle")) { chooseWhichLibraryTitle = options.getString("chooseWhichLibraryTitle"); } currentActivity.startActivityForResult(Intent.createChooser(libraryIntent, chooseWhichLibraryTitle), requestCode); } catch (ActivityNotFoundException e) { e.printStackTrace(); responseHelper.invokeError(callback, "Cannot launch photo library"); } }
Source:
<code>private void evaluateGeoRepSessionStatus(CommandBase<?> rootCommand) { GlusterStorageSyncCommandParameters parameters = (GlusterStorageSyncCommandParameters) rootCommand.getParameters(); GlusterGeoRepSession session = geoRepDao.getById(parameters.getGeoRepSessionId()); if (session == null) { rootCommand.setCommandStatus(CommandStatus.FAILED); } switch (session.getStatus()) { case ACTIVE: boolean checkPointCompleted = true; <START> for (GlusterGeoRepSessionDetails details : session.getSessionDetails()) { if (details.getCheckPointStatus().equals("COMPLETED")) { checkPointCompleted = true; } else { checkPointCompleted = false; } } <END> if (checkPointCompleted) { invokeLiveMergeSnapshots(rootCommand, parameters); } case FAULTY: rootCommand.setCommandStatus(CommandStatus.FAILED); } }</code><technical_language>ist expected behavior here. Currently final result of 'checkPointCompleted' based Checkpoint status of row in session details</technical_language>

Target:
private void evaluateGeoRepSessionStatus(CommandBase<?> rootCommand) { GlusterStorageSyncCommandParameters parameters = (GlusterStorageSyncCommandParameters) rootCommand.getParameters(); GlusterGeoRepSession session = geoRepDao.getById(parameters.getGeoRepSessionId()); if (session == null) { rootCommand.setCommandStatus(CommandStatus.FAILED); } switch (session.getStatus()) { case ACTIVE: if (session.isCheckPointCompleted()) { stopGeoRepSessionCommand(rootCommand, session); rootCommand.setCommandStatus(CommandStatus.SUCCEEDED); } case FAULTY: rootCommand.setCommandStatus(CommandStatus.FAILED); default: break; } }
Source:
<code>protected void configureAddressPolicy(ActiveMQServer server) { super.configureAddressPolicy(server); <START> AddressSettings addressSettings = server.getConfiguration().getAddressesSettings().get("#"); <END> addressSettings.setDefaultGroupFirstKey(SimpleString.toSimpleString("JMSXFirstInGroupID")); }</code><technical_language>Ah, is unfortunate re: tests testing it, default of tests cover users default. In a negative test case, sounds good. check I get properties I (which none)</technical_language>

Target:
protected void configureAddressPolicy(ActiveMQServer server) { super.configureAddressPolicy(server); AddressSettings addressSettings = new AddressSettings(); addressSettings.setAddressFullMessagePolicy(AddressFullMessagePolicy.PAGE); addressSettings.setAutoCreateQueues(isAutoCreateQueues()); addressSettings.setAutoCreateAddresses(isAutoCreateAddresses()); addressSettings.setDeadLetterAddress(SimpleString.toSimpleString(getDeadLetterAddress())); addressSettings.setExpiryAddress(SimpleString.toSimpleString(getDeadLetterAddress())); addressSettings.setDefaultGroupFirstKey(SimpleString.toSimpleString("JMSXFirstInGroupID")); server.getConfiguration().getAddressesSettings().put("GroupFirst.#", addressSettings); }
Source:
<code>private URL promptForWorkspace(Shell shell, ChooseWorkspaceData launchData, boolean force) { URL url = null; do { new ChooseWorkspaceDialog(shell, launchData, false, true) { @Override protected Shell getParentShell() { return null; } }.prompt(force); String instancePath = launchData.getSelection(); if (instancePath == null) { return null; } force = true; if (instancePath.length() <= 0) { MessageDialog .openError( shell, IDEWorkbenchMessages.IDEApplication_workspaceEmptyTitle, IDEWorkbenchMessages.IDEApplication_workspaceEmptyMessage); continue; } File workspace = new File(instancePath); if (!workspace.exists()) { workspace.mkdir(); } try { String path = workspace.getAbsolutePath().replace( File.separatorChar, '/'); url = new URL("file", null, path); } catch (MalformedURLException e) { MessageDialog .openError( shell, IDEWorkbenchMessages.IDEApplication_workspaceInvalidTitle, IDEWorkbenchMessages.IDEApplication_workspaceInvalidMessage); continue; } boolean validWorkspace = checkValidWorkspace(shell, url); if (!validWorkspace) { <START> throw new OperationCanceledException(); <END> } return url; } while (true); }</code><technical_language>a huge fan of flow handling exceptions I good alternatives here. Add exception message in case this approach backfires some point (e.g. due some future changes)</technical_language>

Target:
private URL promptForWorkspace(Shell shell, ChooseWorkspaceData launchData, boolean force) { URL url = null; do { new ChooseWorkspaceDialog(shell, launchData, false, true) { @Override protected Shell getParentShell() { return null; } }.prompt(force); String instancePath = launchData.getSelection(); if (instancePath == null) { return null; } force = true; if (instancePath.length() <= 0) { MessageDialog .openError( shell, IDEWorkbenchMessages.IDEApplication_workspaceEmptyTitle, IDEWorkbenchMessages.IDEApplication_workspaceEmptyMessage); continue; } File workspace = new File(instancePath); if (!workspace.exists()) { workspace.mkdir(); } try { String path = workspace.getAbsolutePath().replace( File.separatorChar, '/'); url = new URL("file", null, path); } catch (MalformedURLException e) { MessageDialog .openError( shell, IDEWorkbenchMessages.IDEApplication_workspaceInvalidTitle, IDEWorkbenchMessages.IDEApplication_workspaceInvalidMessage); continue; } boolean validWorkspace = checkValidWorkspace(shell, url); if (!validWorkspace) { throw new OperationCanceledException("Invalid workspace location: " + url); } return url; } while (true); }
Source:
<code>public static void main(String[] args) { try { ClientArgs clientArgs = new ClientArgs(args); final NettyPerfClient nettyPerfClient = new NettyPerfClient(clientArgs.host, clientArgs.port, clientArgs.path, clientArgs.concurrency, clientArgs.postBlobTotalSize, clientArgs.postBlobChunkSize, clientArgs.sslPropsFilePath, clientArgs.serviceId, clientArgs.targetAccountName, clientArgs.targetContainerName, clientArgs.customHeaders); Runtime.getRuntime().addShutdownHook(new Thread(() -> { logger.info("Received shutdown signal. Requesting NettyPerfClient shutdown"); nettyPerfClient.shutdown(); })); nettyPerfClient.start(); if (clientArgs.testTime != null) { ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); scheduler.schedule(nettyPerfClient::shutdown, clientArgs.testTime, TimeUnit.SECONDS); nettyPerfClient.awaitShutdown(); <START> scheduler.shutdownNow(); <END> } } catch (Exception e) { logger.error("Exception during execution of NettyPerfClient", e); } }</code><technical_language>scheduler.awaitTermination()</technical_language>

Target:
public static void main(String[] args) { try { ClientArgs clientArgs = new ClientArgs(args); final NettyPerfClient nettyPerfClient = new NettyPerfClient(clientArgs.host, clientArgs.port, clientArgs.path, clientArgs.concurrency, clientArgs.postBlobTotalSize, clientArgs.postBlobChunkSize, clientArgs.sslPropsFilePath, clientArgs.serviceId, clientArgs.targetAccountName, clientArgs.targetContainerName, clientArgs.customHeaders); Runtime.getRuntime().addShutdownHook(new Thread(() -> { logger.info("Received shutdown signal. Requesting NettyPerfClient shutdown"); nettyPerfClient.shutdown(); })); nettyPerfClient.start(); ScheduledExecutorService scheduler = null; if (clientArgs.testTime != null) { scheduler = Executors.newSingleThreadScheduledExecutor(); scheduler.schedule(nettyPerfClient::shutdown, clientArgs.testTime, TimeUnit.SECONDS); } nettyPerfClient.awaitShutdown(); if (scheduler != null) { Utils.shutDownExecutorService(scheduler, 30, TimeUnit.SECONDS); } } catch (Exception e) { logger.error("Exception during execution of NettyPerfClient", e); } }
Source:
<code>public void visitToken(DetailAST ast) { if (ast.getType() == TokenTypes.PACKAGE_DEF) { samePackageDomainsRegExp = createSamePackageRegexp( samePackageMatchingDepth, ast); } else { final String importFullPath = getFullImportIdent(ast); final int lineNo = ast.getLineNo(); final int endLineNo = ast.getLastChild().getLineNo(); final boolean isStatic = ast.getType() == TokenTypes.STATIC_IMPORT; importToGroupList.add(new ImportDetails(importFullPath, lineNo, endLineNo, getImportGroup(isStatic, importFullPath), <START> isStatic, ast)); <END> } }</code><technical_language>@developerhb longer need startLineNumber endLineNumber fields in ImportDetails. Please replace getters ast.getLineNo() ast.getLastChild().getLineNo()</technical_language>

Target:
public void visitToken(DetailAST ast) { if (ast.getType() == TokenTypes.PACKAGE_DEF) { samePackageDomainsRegExp = createSamePackageRegexp( samePackageMatchingDepth, ast); } else { final String importFullPath = getFullImportIdent(ast); final boolean isStatic = ast.getType() == TokenTypes.STATIC_IMPORT; importToGroupList.add(new ImportDetails(importFullPath, getImportGroup(isStatic, importFullPath), isStatic, ast)); } }
Source:
<code>protected Map<String, Pair<String, String>> getExclusiveLocks() { if (isImageLockNeeded()) { <START> return Collections.singletonMap(getDisk().getId().toString(), LockMessagesMatchUtil.DISK); <END> } return Collections.EMPTY_MAP; }</code><technical_language>This method is called canDoAction(), if getDisk() is null - check in CDA, this result in a NullPointerException. Instead, get ID parameters</technical_language>

Target:
protected Map<String, Pair<String, String>> getExclusiveLocks() { if (getDisk() != null && isImageLockNeeded()) { return Collections.singletonMap(getDisk().getId().toString(), LockMessagesMatchUtil.DISK); } return null; }
Source:
<code>public void testHeaderVersions() throws Exception { for (final String version : SAMFileHeader.ACCEPTABLE_VERSIONS) { testHeaderVersion(version, true); } <START> testHeaderVersion("1.7", false); <END> }</code><technical_language>If 1.1 instead longer need update version changed. suggestion testHeaderVersion("1.1", false);</technical_language>

Target:
public void testHeaderVersions() throws Exception { for (final String version : SAMFileHeader.ACCEPTABLE_VERSIONS) { testHeaderVersion(version, true); } testHeaderVersion("1.1", false); }
Source:
<code><START> public LabelWithToolTip(SafeHtml text) { <END> super(text); tooltipPanel.setWidget(tooltip); tooltipPanel.getElement().getStyle().setZIndex(1); setTitle(text); registerHandlers(); }</code><technical_language>I a lot of changes in this file avoided. String constructor was, call this(text.asString())? change type of title member, add setTitle() overload, etc</technical_language>

Target:
public LabelWithToolTip(SafeHtml text) { this(text.asString()); }
Source:
<code>protected String generateVmConfiguration(VM vm, List<DiskImage> disks, Map<Guid, VmDevice> vmDevices) { if (vm.getInterfaces() == null || vm.getInterfaces().isEmpty()) { vm.setInterfaces(getVmNetworkInterfaceDao().getAllForVm(vm.getId())); } if (StringUtils.isEmpty(vm.getVmtName())) { VmTemplate t = getVmTemplateDao().get(vm.getVmtGuid()); vm.setVmtName(t.getName()); } if (vmDevices == null) { VmDeviceUtils.setVmDevices(vm.getStaticData()); } else { vm.getStaticData().setManagedDeviceMap(vmDevices); } if (disks == null) { disks = ImagesHandler.filterImageDisks(getDiskDao().getAllForVm(vm.getId()), false, true, true); disks.addAll(ImagesHandler.getCinderLeafImages(getDiskDao().getAllForVm(vm.getId()), false)); } for (DiskImage image : disks) { image.setStorageIds(null); } Version clusterCompatibilityVersion = ClusterUtils.getCompatibilityVersion(vm); if (vm.getCustomCompatibilityVersion() == null) { vm.setCustomCompatibilityVersion(clusterCompatibilityVersion); <START> } <END> return new OvfManager().exportVm(vm, new ArrayList<>(disks), clusterCompatibilityVersion); }</code><technical_language>I is wrong. Imagine exports a VM resides in a 4.0 cluster custom compatibility version. this code custom compatibility version of VM in OVF is set 4.0. import VM in 4.1, compatibility version of VM 4.0 define custom compatibility version for VM. I configuration of VM snapshot hold custom compatibility version cluster's compatibility version time snapshot</technical_language>

Target:
protected String generateVmConfiguration(VM vm, List<DiskImage> disks, Map<Guid, VmDevice> vmDevices) { if (vm.getInterfaces() == null || vm.getInterfaces().isEmpty()) { vm.setInterfaces(getVmNetworkInterfaceDao().getAllForVm(vm.getId())); } if (StringUtils.isEmpty(vm.getVmtName())) { VmTemplate t = getVmTemplateDao().get(vm.getVmtGuid()); vm.setVmtName(t.getName()); } if (vmDevices == null) { VmDeviceUtils.setVmDevices(vm.getStaticData()); } else { vm.getStaticData().setManagedDeviceMap(vmDevices); } if (disks == null) { disks = ImagesHandler.filterImageDisks(getDiskDao().getAllForVm(vm.getId()), false, true, true); disks.addAll(ImagesHandler.getCinderLeafImages(getDiskDao().getAllForVm(vm.getId()), false)); } for (DiskImage image : disks) { image.setStorageIds(null); } return new OvfManager().exportVm(vm, new ArrayList<>(disks), ClusterUtils.getCompatibilityVersion(vm)); }
Source:
<code>public static boolean runJobs(List<Jobby> jobs, HadoopDruidIndexerConfig config) { String failedMessage = null; for (Jobby job : jobs) { if (failedMessage == null) { if (!job.run()) { failedMessage = String.format("Job[%s] failed!", job.getClass()); } } } if (!config.getSchema().getTuningConfig().isLeaveIntermediate()) { if (failedMessage == null || config.getSchema().getTuningConfig().isCleanupOnFailure()) { Path workingPath = config.makeIntermediatePath(); log.info("Deleting path[%s]", workingPath); try { if( workingPath.getFileSystem(injectSystemProperties(new Configuration())).delete(workingPath, true) ){ <START> existing.clear(); <END> } } catch (IOException e) { log.error(e, "Failed to cleanup path[%s]", workingPath); } } } if (failedMessage != null) { throw new ISE(failedMessage); } return true; }</code><technical_language>existing.remove(workingPath)</technical_language>

Target:
public static boolean runJobs(List<Jobby> jobs, HadoopDruidIndexerConfig config) { String failedMessage = null; for (Jobby job : jobs) { if (failedMessage == null) { if (!job.run()) { failedMessage = String.format("Job[%s] failed!", job.getClass()); } } } if (!config.getSchema().getTuningConfig().isLeaveIntermediate()) { if (failedMessage == null || config.getSchema().getTuningConfig().isCleanupOnFailure()) { Path workingPath = config.makeIntermediatePath(); log.info("Deleting path[%s]", workingPath); try { workingPath.getFileSystem(injectSystemProperties(new Configuration())).delete(workingPath, true); } catch (IOException e) { log.error(e, "Failed to cleanup path[%s]", workingPath); } } } if (failedMessage != null) { throw new ISE(failedMessage); } return true; }
Source:
<code>public Builder<SecurityConfiguration> configure(OperationContext context, ModelNode model) throws OperationFailedException { <START> ModelNode sslContextRef = SSL_CONTEXT.resolveModelAttribute(context, model); <END> if (sslContextRef.isDefined()) { this.sslContextDependency = new InjectedValueDependency<>(CommonUnaryRequirement.SSL_CONTEXT.getServiceName(context, sslContextRef.asString()), SSLContext.class); } return this; }</code><technical_language>asStringOrNull() return a String</technical_language>

Target:
public Builder<SecurityConfiguration> configure(OperationContext context, ModelNode model) throws OperationFailedException { String sslContext = SSL_CONTEXT.resolveModelAttribute(context, model).asStringOrNull(); this.sslContextDependency = (sslContext != null) ? new InjectedValueDependency<>(CommonUnaryRequirement.SSL_CONTEXT.getServiceName(context, sslContext), SSLContext.class) : null; return this; }
Source:
<code><START> public static VmPropertiesUtils getInstance() { <END> if (vmPropertiesUtils == null) { vmPropertiesUtils = new VmPropertiesUtils(); } return vmPropertiesUtils; }</code><technical_language>critical is important lazy evaluation instead of initialize in declaration statement</technical_language>

Target:
public static VmPropertiesUtils getInstance() { if (vmPropertiesUtils == null) { synchronized (VmPropertiesUtils.class) { if (vmPropertiesUtils == null) { vmPropertiesUtils = new VmPropertiesUtils(); } } } return vmPropertiesUtils; }
Source:
<code>public void testRebaseWithUncommittedTopicChange() throws Exception { writeTrashFile(FILE1, "file1"); git.add().addFilepattern(FILE1).call(); RevCommit commit = git.commit().setMessage("commit1").call(); createBranch(commit, "refs/heads/topic"); checkoutBranch("refs/heads/topic"); writeTrashFile("file2", "file2"); git.add().addFilepattern("file2").call(); git.commit().setMessage("commit2").call(); checkoutBranch("refs/heads/master"); writeTrashFile(FILE1, "modified file1"); git.add().addFilepattern(FILE1).call(); git.commit().setMessage("commit3").call(); checkoutBranch("refs/heads/topic"); File uncommittedFile = writeTrashFile("file2", "uncommitted file2"); git.add().addFilepattern("file2").call(); RebaseResult result = git.rebase().setUpstream("refs/heads/master") .call(); assertEquals(result.getStatus(), Status.CONFLICTS); assertEquals(result.getConflicts().size(), 1); <START> assertEquals(result.getConflicts().get(0), "file2"); <END> checkFile(uncommittedFile, "uncommitted file2"); assertEquals(RepositoryState.SAFE, git.getRepository().getRepositoryState()); }</code><technical_language>assertEquals(excpected, actual)</technical_language>

Target:
public void testRebaseWithUncommittedTopicChange() throws Exception { writeTrashFile(FILE1, "file1"); git.add().addFilepattern(FILE1).call(); RevCommit commit = git.commit().setMessage("commit1").call(); createBranch(commit, "refs/heads/topic"); checkoutBranch("refs/heads/topic"); writeTrashFile("file2", "file2"); git.add().addFilepattern("file2").call(); git.commit().setMessage("commit2").call(); checkoutBranch("refs/heads/master"); writeTrashFile(FILE1, "modified file1"); git.add().addFilepattern(FILE1).call(); git.commit().setMessage("commit3").call(); checkoutBranch("refs/heads/topic"); File uncommittedFile = writeTrashFile("file2", "uncommitted file2"); git.add().addFilepattern("file2").call(); RebaseResult result = git.rebase().setUpstream("refs/heads/master") .call(); assertEquals(Status.CONFLICTS, result.getStatus()); assertEquals(1, result.getConflicts().size()); assertEquals("file2", result.getConflicts().get(0)); checkFile(uncommittedFile, "uncommitted file2"); assertEquals(RepositoryState.SAFE, git.getRepository().getRepositoryState()); }
Source:
<code>private DbUser buildUser(T params, String authzName) { DbUser dbUser = dbUserDao.getByExternalId(authzName, params.getPrincipalId()); <START> DbUser user = new DbUser(dbUser); <END> user.setId(dbUser == null ? Guid.newGuid() : dbUser.getId()); user.setExternalId(params.getPrincipalId()); user.setDomain(authzName); user.setEmail(params.getEmail()); user.setFirstName(params.getFirstName()); user.setLastName(params.getLastName()); user.setNamespace(params.getNamespace()); user.setLoginName(params.getPrincipalName()); List<Guid> groupIds = new ArrayList<>(); List<String> groupRecordIds = new ArrayList<>(); flatGroups((Collection<ExtMap>) params.getGroupIds(), groupRecordIds); for (String groupId : groupRecordIds) { DbGroup dbGroup = dbGroupDao.getByExternalId(authzName, groupId); if (dbGroup != null) { groupIds.add(dbGroup.getId()); } } user.setGroupIds(groupIds); if (dbUser == null) { dbUserDao.save(user); } else if (!dbUser.equals(user)) { dbUserDao.update(user); } return user; }</code><technical_language>This NPE, if user is in db, need avoid fix DBUser copy constructor</technical_language>

Target:
private DbUser buildUser(T params, String authzName) { DbUser dbUser = dbUserDao.getByExternalId(authzName, params.getPrincipalId()); DbUser user = dbUser != null ? new DbUser(dbUser) : new DbUser(); user.setId(dbUser == null ? Guid.newGuid() : dbUser.getId()); user.setExternalId(params.getPrincipalId()); user.setDomain(authzName); user.setEmail(params.getEmail()); user.setFirstName(params.getFirstName()); user.setLastName(params.getLastName()); user.setNamespace(params.getNamespace()); user.setLoginName(params.getPrincipalName()); List<Guid> groupIds = new ArrayList<>(); List<String> groupRecordIds = new ArrayList<>(); flatGroups((Collection<ExtMap>) params.getGroupIds(), groupRecordIds); for (String groupId : groupRecordIds) { DbGroup dbGroup = dbGroupDao.getByExternalId(authzName, groupId); if (dbGroup != null) { groupIds.add(dbGroup.getId()); } } user.setGroupIds(groupIds); boolean isAdmin = !roleDao.getAnyAdminRoleForUserAndGroups(user.getId(), StringUtils.join(user.getGroupIds(), ",")).isEmpty(); user.setAdmin(isAdmin); if (dbUser == null) { dbUserDao.save(user); } else if (!dbUser.equals(user)) { dbUserDao.update(user); } return user; }
Source:
<code>boolean mergeWithDefaults(OCD ocd, Map<String, Object> properties) throws KuraException { boolean changed = false; <START> Set<String> keys; <END> if (properties != null) { keys = properties.keySet(); } else { keys = new HashSet<String>(); } Map<String, Object> defaults = getDefaultProperties(ocd); Set<String> defaultsKeys = defaults.keySet(); defaultsKeys.removeAll(keys); if (!defaultsKeys.isEmpty()) { changed = true; s_logger.info("Merging configuration for pid: {}", ocd.getId()); for (String key : defaultsKeys) { Object value = defaults.get(key); properties.put(key, value); s_logger.debug("Merged configuration properties with property with name: and default value {}", key, value); } } return changed; }</code><technical_language>I sense call this method null properties. method modifies instance referenced properties parameter :-( I consider this occurrence a bug NPE runtime exception appropriate</technical_language>

Target:
boolean mergeWithDefaults(OCD ocd, Map<String, Object> properties) throws KuraException { boolean changed = false; Set<String> keys = properties.keySet(); Map<String, Object> defaults = getDefaultProperties(ocd); Set<String> defaultsKeys = defaults.keySet(); defaultsKeys.removeAll(keys); if (!defaultsKeys.isEmpty()) { changed = true; logger.info("Merging configuration for pid: {}", ocd.getId()); for (String key : defaultsKeys) { Object value = defaults.get(key); properties.put(key, value); logger.debug("Merged configuration properties with property with name: and default value {}", key, value); } } return changed; }
Source:
<code>private ComponentDto getByKey(DbSession dbSession, String key, String label) { <START> return checkComponent(() -> dbClient.componentDao().selectByKey(dbSession, key), () -> format("%s key '%s' not found", label, key)); <END> }</code><technical_language>I pattern a supplier compute error message for org.sonar.server.ws.WsUtils#checkRequest(condition, errorMessage, arguments...)</technical_language>

Target:
private ComponentDto getByKey(DbSession dbSession, String key, String label) { return checkComponent(dbClient.componentDao().selectByKey(dbSession, key), "%s key '%s' not found", label, key); }
Source:
<code>private Optional<AttributeValidationReport> generateValidationReports( List<AttributeValidationReport> validationReportList) { if (CollectionUtils.isEmpty(validationReportList)) { return Optional.empty(); } AttributeValidationReportImpl result = new AttributeValidationReportImpl(); for (AttributeValidationReport attributeValidationReport : validationReportList) { Set<ValidationViolation> validationViolations = attributeValidationReport.getAttributeValidationViolations(); Set<String> suggestedValues = attributeValidationReport.getSuggestedValues(); if (CollectionUtils.isEmpty(validationViolations)) { <START> return Optional.empty(); <END> } result.addViolations(validationViolations); if (CollectionUtils.isNotEmpty(suggestedValues)) { result.addSuggestedValues(suggestedValues); } } return Optional.of(result); }</code><technical_language>Thinking this logic this is right do. This return empty report for attribute if of individual reports passes (by returning violations). validating individually, other reports for failed values in list, right</technical_language>

Target:
private Optional<AttributeValidationReport> generateValidationReports( List<AttributeValidationReport> validationReportList) { if (CollectionUtils.isEmpty(validationReportList)) { return Optional.empty(); } AttributeValidationReportImpl result = new AttributeValidationReportImpl(); for (AttributeValidationReport attributeValidationReport : validationReportList) { Set<ValidationViolation> validationViolations = attributeValidationReport.getAttributeValidationViolations(); Set<String> suggestedValues = attributeValidationReport.getSuggestedValues(); result.addViolations(validationViolations); if (CollectionUtils.isNotEmpty(suggestedValues)) { result.addSuggestedValues(suggestedValues); } } return Optional.of(result); }
Source:
<code>public boolean rewritePre(Mutable<ILogicalOperator> opRef, IOptimizationContext context) throws AlgebricksException { <START> opRef.getValue().getOperatorTag(); <END> if (hasRun && !firstOpRef.equals(opRef)) { return false; } else { firstOpRef = opRef; } boolean modified = false; boolean modified_last_pass; do { usedVariables.clear(); modified_last_pass = rewritePreTrackingUsedVariables(opRef, context); if (modified_last_pass) { modified = modified_last_pass; } } while (modified_last_pass); hasRun = true; return modified; }</code><technical_language>remove</technical_language>

Target:
public boolean rewritePre(Mutable<ILogicalOperator> opRef, IOptimizationContext context) throws AlgebricksException { if (hasRun && !firstOpRef.equals(opRef)) { return false; } else { firstOpRef = opRef; } boolean modified = false; boolean modified_last_pass; do { usedVariables.clear(); modified_last_pass = rewritePreTrackingUsedVariables(opRef, context); if (modified_last_pass) { modified = modified_last_pass; } } while (modified_last_pass); hasRun = true; return modified; }
Source:
<code>public ProjectApi create(ProjectInput in) throws RestApiException { try { if (name == null) { throw new <START> RestApiException("Project already exists"); <END> } if (in.name != null && !name.equals(in.name)) { throw new RestApiException("name must match input.name"); } createProjectFactory.get().create(name) .apply(TopLevelResource.INSTANCE, in); return projectApi.create(projects.parse(name)); } catch (BadRequestException | UnprocessableEntityException | ResourceConflictException | ResourceNotFoundException | ProjectCreationFailedException | IOException e) { throw new RestApiException("Cannot create project", e); } }</code><technical_language>this a ResourceConflictException</technical_language>

Target:
public ProjectApi create(ProjectInput in) throws RestApiException { try { if (name == null) { throw new ResourceConflictException("Project already exists"); } if (in.name != null && !name.equals(in.name)) { throw new RestApiException("name must match input.name"); } createProjectFactory.get().create(name) .apply(TopLevelResource.INSTANCE, in); return projectApi.create(projects.parse(name)); } catch (BadRequestException | UnprocessableEntityException | ResourceNotFoundException | ProjectCreationFailedException | IOException e) { throw new RestApiException("Cannot create project", e); } }
Source:
<code>public List<String> getParameterDefinitionNames() { return new AbstractList<String>() { public String get(int index) { <START> if (parameterDefinitions != null && parameterDefinitions.get(index) != null) { <END> return parameterDefinitions.get(index).getName(); } else { return ""; } } public int size() { if (parameterDefinitions != null) { return parameterDefinitions.size(); } else { return 0; } } }; }</code><technical_language>This null check required anymore</technical_language>

Target:
public List<String> getParameterDefinitionNames() { return new AbstractList<String>() { public String get(int index) { return parameterDefinitions.get(index).getName(); } public int size() { return parameterDefinitions.size(); } }; }
Source:
<code>private static Set<String> getGroupKeys(List<VariableReferenceExpression> groupingKeys) { Set<String> groupKeySet = new HashSet<>(); <START> for (VariableReferenceExpression groupingKey : groupingKeys) { <END> groupKeySet.add(groupingKey.getName()); } return groupKeySet; }</code><technical_language>a helpful helper function.</technical_language>

Target:
private static Set<String> getGroupKeys(List<VariableReferenceExpression> groupingKeys) { Set<String> groupKeySet = new HashSet<>(); groupingKeys.forEach(groupingKey -> groupKeySet.add(groupingKey.getName())); return groupKeySet; }
Source:
<code>private boolean isConstructor(TypeSet types) { <START> boolean isUnknown = types.contains(Kind.UNKNOWN); <END> boolean isConstructor = true; Type type = types.getType(); if (type != null) { if (type.callability().equals(Callability.NON_CALLABLE)) { isConstructor = false; } else if (considerJSDoc && type.kind().equals(Kind.FUNCTION)) { isConstructor = hasJSDocAnnotation(((FunctionType) type).functionTree()); } } return isConstructor; }</code><technical_language>@vilchik-elena this fixed (just in case missed notification for it)</technical_language>

Target:
private boolean isConstructor(TypeSet types) { boolean isConstructor = true; Type type = types.getUniqueKnownType(); if (type != null) { if (type.callability().equals(Callability.NON_CALLABLE)) { isConstructor = false; } else if (considerJSDoc && type.kind().equals(Kind.FUNCTION)) { isConstructor = hasJSDocAnnotation(((FunctionType) type).functionTree()); } } return isConstructor; }
Source:
<code>public ValidationResult(VdcBllMessages message, String... variableReplacements) { if (message == null) { throw new IllegalArgumentException("message must not be null"); } this.message = message; <START> this.variableReplacements = variableReplacements == null <END> ? null : Collections.unmodifiableList(Arrays.asList(variableReplacements)); }</code><technical_language>I more readable if written as: if (variableReplacements != null) { this.variableReplacements = Collections.unmodifiableList(Arrays.asList(variableReplacements)); }</technical_language>

Target:
public ValidationResult(VdcBllMessages message, String... variableReplacements) { if (message == null) { throw new IllegalArgumentException("message must not be null"); } this.message = message; if (variableReplacements != null) { this.variableReplacements = Collections.unmodifiableList(Arrays.asList(variableReplacements)); } }
Source:
<code>public AddProblemFactChangesCommand() { <START> super(); <END> }</code><technical_language>need call super explicitly. construction implicitly starts a super() call (unless a this() call another construction)</technical_language>

Target:
public AddProblemFactChangesCommand() { }
Source:
<code>public void installMaven() { <START> if (!new File(System.getProperty("user.home") + "\\apache-maven-" + mvnVersion).exists()) { <END> String downloadPath = System.getProperty("user.home") + "\\mvn_setup.zip"; download("<LINK_0>" + mvnVersion + "-bin.zip", downloadPath); unzipFile(downloadPath, System.getProperty("user.home")); } mvnCommand = System.getProperty("user.home") + "\\apache-maven-" + mvnVersion + "\\bin\\mvn" + addSystemEnding(); }</code><technical_language>please do install home, meaningful location in ${karaf.data}</technical_language>

Target:
public void installMaven() throws Exception { File tmp = File.createTempFile("mvn_setup", "zip"); List<?> mirrors = getListOfMirrors(); for (int i = 0; i < mirrors.size(); i++) { if (download(String.valueOf(mirrors.get(i)) + "apache-maven-" + readMvnVersionFromPropFile() + "-bin.zip", tmp.getAbsolutePath())) { break; } if (i == mirrors.size() - 1) { log.error("No valid mirror found!"); } } if (mirrors.size() != 0) { unzipFile(tmp.getAbsolutePath(), System.getProperty("karaf.data")); } }
Source:
<code><START> protected Name decomposeName(CompositeName compositeName) throws NamingException { <END> if (compositeName.isEmpty()) { return new SimpleName(); } final NameParser parser = getNativeNameParser(); final Name name = parser.parse(compositeName.get(0)); if(name.isEmpty())name.add(""); for (int i = 1; i < compositeName.size(); i ++) { final String part = compositeName.get(i); final Name parsed = parser.parse(part); if (parsed.isEmpty()) parsed.add(""); name.addAll(parsed); } return name; }</code><technical_language>If this method is available, line 332 return parser.parse("") instead of new SimpleName(); I _think_. This is in event a class form is context default</technical_language>

Target:
protected Name decomposeName(CompositeName compositeName) throws NamingException { final NameParser parser = getNativeNameParser(); if (compositeName.isEmpty()) { return parser.parse(""); } final Name name = parser.parse(compositeName.get(0)); if(name.isEmpty())name.add(""); for (int i = 1; i < compositeName.size(); i ++) { final String part = compositeName.get(i); final Name parsed = parser.parse(part); if (parsed.isEmpty()) parsed.add(""); name.addAll(parsed); } return name; }
Source:
<code>public CompletableFuture<YarnWorkerNode> requestResource(TaskExecutorProcessSpec taskExecutorProcessSpec) { final Optional<Resource> containerResourceOptional = getContainerResource(taskExecutorProcessSpec); final CompletableFuture<YarnWorkerNode> requestResourceFuture = new CompletableFuture<>(); if (containerResourceOptional.isPresent()) { resourceManagerClient.addContainerRequest(getContainerRequest(containerResourceOptional.get())); resourceManagerClient.setHeartbeatInterval(containerRequestHeartbeatIntervalMillis); <START> requestResourceFutures.computeIfAbsent(taskExecutorProcessSpec, ignore -> new ArrayList<>()).add(requestResourceFuture); <END> log.info("Requesting new TaskExecutor container with resource {}.", taskExecutorProcessSpec); } else { requestResourceFuture.completeExceptionally( new ResourceManagerException(String.format("Could not compute the container Resource from the given TaskExecutorProcessSpec %s.", taskExecutorProcessSpec))); } return requestResourceFuture; }</code><technical_language>replace ArrayList LinkedList? I change type of requestResourceFutures Map<TaskExecutorProcessSpec, Queue<CompletableFuture<YarnWorkerNode>>></technical_language>

Target:
public CompletableFuture<YarnWorkerNode> requestResource(TaskExecutorProcessSpec taskExecutorProcessSpec) { final Optional<Resource> containerResourceOptional = getContainerResource(taskExecutorProcessSpec); final CompletableFuture<YarnWorkerNode> requestResourceFuture = new CompletableFuture<>(); if (containerResourceOptional.isPresent()) { resourceManagerClient.addContainerRequest(getContainerRequest(containerResourceOptional.get())); resourceManagerClient.setHeartbeatInterval(containerRequestHeartbeatIntervalMillis); requestResourceFutures.computeIfAbsent(taskExecutorProcessSpec, ignore -> new LinkedList<>()).add(requestResourceFuture); log.info("Requesting new TaskExecutor container with resource {}.", taskExecutorProcessSpec); } else { requestResourceFuture.completeExceptionally( new ResourceManagerException(String.format("Could not compute the container Resource from the given TaskExecutorProcessSpec %s.", taskExecutorProcessSpec))); } return requestResourceFuture; }
Source:
<code>public void init(TableDefinition tableDefinition, StreamEventFactory storeEventPool, StreamEventCloner storeEventCloner, ConfigReader configReader, SiddhiAppContext siddhiAppContext, RecordTableHandler recordTableHandler) { if (recordTableHandler != null) { recordTableHandler.init(tableDefinition, new RecordTableHandlerCallback(this), siddhiAppContext); } this.recordTableHandler = recordTableHandler; this.storeEventPool = storeEventPool; init(tableDefinition, configReader); <START> init(tableDefinition, siddhiAppContext, storeEventCloner, configReader); <END> }</code><technical_language>rename 2nd init? This is init thing</technical_language>

Target:
public void init(TableDefinition tableDefinition, StreamEventFactory storeEventPool, StreamEventCloner storeEventCloner, ConfigReader configReader, SiddhiAppContext siddhiAppContext, RecordTableHandler recordTableHandler) { if (recordTableHandler != null) { recordTableHandler.init(tableDefinition, new RecordTableHandlerCallback(this), siddhiAppContext); } this.recordTableHandler = recordTableHandler; this.storeEventPool = storeEventPool; init(tableDefinition, configReader); initCache(tableDefinition, siddhiAppContext, storeEventCloner, configReader); }
Source:
<code>public void setDependencies(List<DependencyNode> dependencies) { if (dependencies == null) { this.dependencies = Collections.emptyList(); <START> this.allDependencies = Collections.emptySet(); <END> } else { this.dependencies = dependencies; Set<String> allDependencies = new HashSet<>(); dependencies.forEach(dependencyNode -> { allDependencies.add(dependencyNode.artifactId); allDependencies.addAll(dependencyNode.allDependencies); }); this.allDependencies = allDependencies; } }</code><technical_language>Move initialisations class level constructer null check else logic</technical_language>

Target:
public void setDependencies(List<DependencyNode> dependencies) { if (dependencies == null) { return; } this.dependencies = dependencies; Set<String> allDependencies = new HashSet<>(); dependencies.forEach(dependencyNode -> { allDependencies.add(dependencyNode.artifactId); allDependencies.addAll(dependencyNode.allDependencies); }); this.allDependencies = allDependencies; }
Source:
<code>public void execute(IProgressMonitor monitor) throws CoreException { SubMonitor progress = SubMonitor.convert(monitor, CoreText.IgnoreOperation_taskName, paths.size()); try { for (IPath path : paths) { if (monitor.isCanceled()) { break; } if (RepositoryUtil.canBeAutoIgnored(path)) { addIgnore(progress.newChild(1), path); } <START> progress.worked(1); <END> } } catch (CoreException e) { throw e; } catch (Exception e) { throw new CoreException(Activator.error( CoreText.IgnoreOperation_error, e)); } }</code><technical_language>Needs in else-clause, count (newChild() worked()) reach 100% path</technical_language>

Target:
public void execute(IProgressMonitor monitor) throws CoreException { SubMonitor progress = SubMonitor.convert(monitor, CoreText.IgnoreOperation_taskName, paths.size()); try { for (IPath path : paths) { if (monitor.isCanceled()) { break; } if (RepositoryUtil.canBeAutoIgnored(path)) { addIgnore(progress.newChild(1), path); } else { progress.worked(1); } } } catch (CoreException e) { throw e; } catch (Exception e) { throw new CoreException(Activator.error( CoreText.IgnoreOperation_error, e)); } }
Source:
<code>public static void main(String[] args) throws ParseException, IOException { Options options = new Options(); options.addOption("i", true, "Jupyter notebook file"); options.addOption("o", true, "Zeppelin note file. Default: note.json"); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args); if (!cmd.hasOption("i")) { new HelpFormatter().printHelp("java " + JupyterUtil.class.getName(), options); System.exit(1); } Path jupyterPath = Paths.get(cmd.getOptionValue("i")); Path zeppelinPath = Paths.get(cmd.hasOption("o") ? cmd.getOptionValue("o") : "note.json"); Note note = new JupyterUtil() <START> .getNote(new BufferedReader(new FileReader(jupyterPath.toFile())), "python", "md"); <END> try (FileWriter fw = new FileWriter(zeppelinPath.toFile())) { new GsonBuilder().setPrettyPrinting().create() .toJson(note, fw); } }</code><technical_language>possibly need later, jupyter is python - running R kernel for example, other kernel Spark/Scala etc</technical_language>

Target:
public static void main(String[] args) throws ParseException, IOException { Options options = new Options(); options.addOption("i", true, "Jupyter notebook file"); options.addOption("o", true, "Zeppelin note file. Default: note.json"); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args); if (!cmd.hasOption("i")) { new HelpFormatter().printHelp("java " + JupyterUtil.class.getName(), options); System.exit(1); } Path jupyterPath = Paths.get(cmd.getOptionValue("i")); Path zeppelinPath = Paths.get(cmd.hasOption("o") ? cmd.getOptionValue("o") : "note.json"); try (BufferedReader in = new BufferedReader(new FileReader(jupyterPath.toFile())); FileWriter fw = new FileWriter(zeppelinPath.toFile())) { Note note = new JupyterUtil().getNote(in, "python", "md"); Gson gson = new GsonBuilder().setPrettyPrinting().create(); gson.toJson(note, fw); } }
Source:
<code>public IndexingConfigurationBuilder index(Index index) { <START> if (index != Index.NONE) enabled(true); <END> attributes.attribute(INDEX).set(index); return this; }</code><technical_language>conditional wrong. This enabled(index !=null && index != Index.NON);</technical_language>

Target:
public IndexingConfigurationBuilder index(Index index) { enabled(index != null && index != Index.NONE); attributes.attribute(INDEX).set(index); return this; }
Source:
<code>public final void setInput(final IWorkbenchPart part, final ISelection selection) { if (selection instanceof IStructuredSelection && ((IStructuredSelection) selection).getFirstElement() instanceof EObject) { final EObject selectedElement = (EObject) ((IStructuredSelection) selection).getFirstElement(); final Registry registry = ComposedAdapterFactory.Descriptor.Registry.INSTANCE; <START> final Collection<Object> types = new ArrayList<>(); <END> types.add(selectedElement.eClass().getEPackage()); types.add(IItemPropertySource.class); final Descriptor descriptor = registry.getDescriptor(types); final AdapterFactory adapterFactory = descriptor.createAdapterFactory(); this.page.setPropertySourceProvider(new AdapterFactoryContentProvider(adapterFactory) { @Override protected IPropertySource createPropertySource(final Object object, final IItemPropertySource itemPropertySource) { return GMFDocumentStructureTemplateSection.this.createPropertySource(object, itemPropertySource); } }); } else { this.page.setPropertySourceProvider(null); } super.setInput(part, selection); }</code><technical_language>If 2 types, add size constructor</technical_language>

Target:
public final void setInput(final IWorkbenchPart part, final ISelection selection) { if (selection instanceof IStructuredSelection && ((IStructuredSelection) selection).getFirstElement() instanceof EObject) { final EObject selectedElement = (EObject) ((IStructuredSelection) selection).getFirstElement(); final Registry registry = ComposedAdapterFactory.Descriptor.Registry.INSTANCE; final Collection<Object> types = new ArrayList<>(2); types.add(selectedElement.eClass().getEPackage()); types.add(IItemPropertySource.class); final Descriptor descriptor = registry.getDescriptor(types); final AdapterFactory adapterFactory = descriptor.createAdapterFactory(); this.page.setPropertySourceProvider(new AdapterFactoryContentProvider(adapterFactory) { @Override protected IPropertySource createPropertySource(final Object object, final IItemPropertySource itemPropertySource) { return GMFDocumentStructureTemplateSection.this.createPropertySource(object, itemPropertySource); } }); } else { this.page.setPropertySourceProvider(null); } super.setInput(part, selection); }