auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private Optional<String> getNextMetric() { final String next; <START> if (_setIterator == null) { <END> _setIterator = _metricsSet.iterator(); } if (_setIterator.hasNext()) { next = _setIterator.next(); _setIterator.remove(); } else { next = null; } return Optional.ofNullable(next); }</code><technical_language>protect calls this if _metricsSet is null return absent</technical_language>

Target:
private Optional<String> getNextMetric() { final String next; if (_setIterator.hasNext()) { next = _setIterator.next(); _setIterator.remove(); } else { next = null; } return Optional.ofNullable(next); }
Source:
<code>public void setUp() throws Exception { super.setUp(); CountDownLatch listenLatch = new CountDownLatch(1); httpServer = new HttpServerImpl((VertxInternal) vertx, new HttpServerOptions()) { @Override protected void onChannelInitialized(Channel ch) { <START> ch.pipeline().addFirst(new ResetLatchCountDown()).addLast(new ThrowableRecorder()); <END> } }.requestHandler(request -> {}).listen(8080, onSuccess(server -> listenLatch.countDown())); awaitLatch(listenLatch); }</code><technical_language>test mess Netty pipeline</technical_language>

Target:
public void setUp() throws Exception { super.setUp(); CountDownLatch listenLatch = new CountDownLatch(1); httpServer = vertx.createHttpServer() .requestHandler(request -> {}) .listen(8080, onSuccess(server -> listenLatch.countDown())); ((HttpServerImpl) httpServer).setConnectionExceptionHandler(t -> { caught.set(t); resetLatch.countDown(); }); awaitLatch(listenLatch); }
Source:
<code>public DocumentModel defaultCreateFolder(CoreSession documentManager, String fullname, String path, String containerTypeName, boolean checkAllowedSubTypes, boolean overwrite) { String title = FileManagerUtils.fetchFileName(fullname); if (overwrite) { DocumentModel docModel = FileManagerUtils.getExistingDocByTitle(documentManager, path, title); if (docModel != null) { return docModel; } } PathRef containerRef = new PathRef(path); if (!documentManager.hasPermission(containerRef, SecurityConstants.READ_PROPERTIES) || !documentManager.hasPermission(containerRef, SecurityConstants.ADD_CHILDREN)) { throw new DocumentSecurityException("Not enough rights to create folder"); } DocumentModel container = documentManager.getDocument(containerRef); TypeManager typeService = Framework.getService(TypeManager.class); <START> if (checkAllowedSubTypes && !typeService.isAllowedSubType(containerTypeName, container.getType(), container)) { <END> return null; } PathSegmentService pss = Framework.getService(PathSegmentService.class); DocumentModel docModel = documentManager.createDocumentModel(containerTypeName); docModel.setProperty("dublincore", "title", title); docModel.setPathInfo(path, pss.generatePathSegment(docModel)); docModel = documentManager.createDocument(docModel); documentManager.save(); log.debug("Created container: with type {}", docModel::getName, () -> containerTypeName); return docModel; }</code><technical_language>Framework.getService(TypeManager.class) Framework.getService(MimetypeRegistry.class)</technical_language>

Target:
public DocumentModel defaultCreateFolder(CoreSession documentManager, String fullname, String path, String containerTypeName, boolean checkAllowedSubTypes, boolean overwrite) { String title = FileManagerUtils.fetchFileName(fullname); if (overwrite) { DocumentModel docModel = FileManagerUtils.getExistingDocByTitle(documentManager, path, title); if (docModel != null) { return docModel; } } PathRef containerRef = new PathRef(path); if (!documentManager.hasPermission(containerRef, SecurityConstants.READ_PROPERTIES) || !documentManager.hasPermission(containerRef, SecurityConstants.ADD_CHILDREN)) { throw new DocumentSecurityException("Not enough rights to create folder"); } DocumentModel container = documentManager.getDocument(containerRef); if (checkAllowedSubTypes && !Framework.getService(TypeManager.class) .isAllowedSubType(containerTypeName, container.getType(), container)) { return null; } PathSegmentService pss = Framework.getService(PathSegmentService.class); DocumentModel docModel = documentManager.createDocumentModel(containerTypeName); docModel.setProperty("dublincore", "title", title); docModel.setPathInfo(path, pss.generatePathSegment(docModel)); docModel = documentManager.createDocument(docModel); documentManager.save(); log.debug("Created container: with type {}", docModel::getName, () -> containerTypeName); return docModel; }
Source:
<code>public Response start(Action action) { RunVmParams params; VdcActionType actionType; if (action.isSetVm()) { VM vm = action.getVm(); validateEnums(VM.class, vm); actionType = VdcActionType.RunVmOnce; params = createRunVmOnceParams(vm); } else { actionType = VdcActionType.RunVm; params = new RunVmParams(guid); } if (action.isSetPause() && action.isPause()) { params.setRunAndPause(true); } <START> if (Boolean.TRUE.equals(action.isUseSysprep())) { <END> params.setInitializationType(InitializationType.Sysprep); }else if (Boolean.TRUE.equals(action.isUseCloudInit())) { params.setInitializationType(InitializationType.CloudInit); } else { params.setInitializationType(InitializationType.None); } return doAction(actionType, params, action); }</code><technical_language>Consider "isSet..." "is..." method, in rest of method: if (action.isSetUseSysprep() && action.isUseSysprep()) { ... }</technical_language>

Target:
public Response start(Action action) { RunVmParams params; VdcActionType actionType; if (action.isSetVm()) { VM vm = action.getVm(); validateEnums(VM.class, vm); actionType = VdcActionType.RunVmOnce; params = createRunVmOnceParams(vm); } else { actionType = VdcActionType.RunVm; params = new RunVmParams(guid); } if (action.isSetPause() && action.isPause()) { params.setRunAndPause(true); } boolean useSysprep = action.isSetUseSysprep() && action.isUseSysprep(); boolean useCloudInit = action.isSetUseCloudInit() && action.isUseCloudInit(); if (useSysprep && useCloudInit) { Fault fault = new Fault(); fault.setReason( localize( Messages.CANT_USE_SYSPREP_AND_CLUD_INIT_SIMULTANEOUSLY ) ); return Response.status(Response.Status.CONFLICT) .entity(fault) .build(); } if (useSysprep) { params.setInitializationType(InitializationType.Sysprep); } else if (useCloudInit) { params.setInitializationType(InitializationType.CloudInit); } else { params.setInitializationType(InitializationType.None); } return doAction(actionType, params, action); }
Source:
<code>public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.mItem_create_new_client: setActionBarTitle(R.string.create_client); openCreateClient(); break; case R.id.mItem_create_new_center: setActionBarTitle(R.string.create_center); openCreateCenter(); break; case R.id.mItem_create_new_group: openCreateGroup(); setActionBarTitle(R.string.create_group); break; case R.id.logout: <START> final AlertDialog.Builder builder = new AlertDialog.Builder(this); <END> builder.setMessage(R.string.dialog_action_logout_confirmation) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { logout(); } }).show(); break; default: break; } return super.onOptionsItemSelected(item); }</code><technical_language>@pranavgupta1234, Please this [MaterialDialog](<LINK_0> class</technical_language>

Target:
public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.mItem_create_new_client: setActionBarTitle(R.string.create_client); openCreateClient(); break; case R.id.mItem_create_new_center: setActionBarTitle(R.string.create_center); openCreateCenter(); break; case R.id.mItem_create_new_group: openCreateGroup(); setActionBarTitle(R.string.create_group); break; case R.id.logout: new MaterialDialog.Builder().init(DashboardActivity.this) .setMessage(R.string.dialog_action_logout_confirmation) .setCancelable(true) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }) .createMaterialDialog() .show(); break; default: break; } return super.onOptionsItemSelected(item); }
Source:
<code>private void invokeHostUpgrade(CommandBase<?> command, UpgradeHostParameters parameters) { <START> stopGlusterServices(parameters.getVdsId()); <END> commandCoordinatorUtil.executeAsyncCommand(ActionType.UpgradeHostInternal, createUpgradeParameters(parameters), command.cloneContextAndDetachFromParent()); }</code><technical_language>expected achieve transition of host maintenance mode ? meaning, do need explicit call for stopping gluster services</technical_language>

Target:
private void invokeHostUpgrade(CommandBase<?> command, UpgradeHostParameters parameters) { boolean returnValue = resourceManager.runVdsCommand(VDSCommandType.GlusterServersList, new VdsIdVDSCommandParametersBase(parameters.getVdsId())).getSucceeded(); if (returnValue) { stopGlusterServices(parameters.getVdsId()); } commandCoordinatorUtil.executeAsyncCommand(ActionType.UpgradeHostInternal, createUpgradeParameters(parameters), command.cloneContextAndDetachFromParent()); }
Source:
<code><START> public String getNeworkOrigin(final String ip) { <END> final String sanitizedIp = sanitizeIp(ip); if (sanitizedIp != null) { if (isLabsHost(sanitizedIp)) { return ORIGIN_LABS; } else if (isTrustedProxy(sanitizedIp)) { return ORIGIN_INTERNAL; } } return ORIGIN_EXTERNAL; }</code><technical_language>I defining enum more sense do string constants arround</technical_language>

Target:
public NetworkOrigin getNeworkOrigin(final String ip) { final String sanitizedIp = sanitizeIp(ip); if (sanitizedIp != null) { if (isLabsHost(sanitizedIp)) { return NetworkOrigin.LABS; } else if (isTrustedProxy(sanitizedIp)) { return NetworkOrigin.INTERNAL; } } return NetworkOrigin.EXTERNAL; }
Source:
<code>public Object getPropertyValue(Object id) { if (sfName.equals(id)) { return getName(); } if (sfPath.equals(id)) { return getPath().toString(); } if (sfLocation.equals(id)) { return getLocation().toString(); } if (sfIsLinked.equals(id)) { return Boolean.valueOf(getResource().isLinked()).toString(); } if (sfEventType.equals(id)) { if (fTraceTypeId != null) { IConfigurationElement ce = sfTraceTypeAttributes.get(fTraceTypeId); return (ce != null) ? (getCategory(ce) + " : " + ce.getAttribute(TmfTraceType.NAME_ATTR)) : ""; } } Map<String, String> envVariables = getEnvVariables(); <START> if (envVariables != null && envVariables.isEmpty()) { <END> String value = envVariables.get(id); if (value != null) { return value; } } return null; }</code><technical_language>2nd check !envVariables.isEmpty() (negate!)</technical_language>

Target:
public Object getPropertyValue(Object id) { if (sfName.equals(id)) { return getName(); } if (sfPath.equals(id)) { return getPath().toString(); } if (sfLocation.equals(id)) { return getLocation().toString(); } if (sfIsLinked.equals(id)) { return Boolean.valueOf(getResource().isLinked()).toString(); } if (sfEventType.equals(id)) { if (fTraceTypeId != null) { IConfigurationElement ce = sfTraceTypeAttributes.get(fTraceTypeId); return (ce != null) ? (getCategory(ce) + " : " + ce.getAttribute(TmfTraceType.NAME_ATTR)) : ""; } } Map<String, String> envVariables = getEnvVariables(); if (envVariables != null && !envVariables.isEmpty()) { String value = envVariables.get(id); if (value != null) { return value; } } return null; }
Source:
<code><START> public int runEmpiOnTargetType(String theTargetType, String theCriteria) { <END> resolveTargetTypeOrThrowException(theTargetType); SearchParameterMap spMap = getSearchParameterMapFromCriteria(theTargetType, theCriteria); spMap.setLoadSynchronousUpTo(QUEUE_ADDING_PAGE_SIZE); int total = 0; ISearchBuilder mySearchBuilder = mySearchBuilderFactory.newSearchBuilder(myDaoRegistry.getResourceDao(theTargetType), theTargetType, Patient.class); SearchRuntimeDetails searchRuntimeDetails = new SearchRuntimeDetails(null, UUID.randomUUID().toString()); try (IResultIterator query = mySearchBuilder.createQuery(spMap, searchRuntimeDetails, null, RequestPartitionId.defaultPartition())) { Collection<ResourcePersistentId> pidsToSubmit = new ArrayList<>(); List<IBaseResource> resourceToBeSubmitted = new ArrayList<>(); while (query.hasNext()) { pidsToSubmit.add(query.next()); if (pidsToSubmit.size() == QUEUE_ADDING_PAGE_SIZE || !query.hasNext()) { total = loadResourcesAndSubmitToEmpi(total, mySearchBuilder, pidsToSubmit, resourceToBeSubmitted); resourceToBeSubmitted.clear(); } } } catch (IOException theE) { throw new InternalErrorException("Failure while attempting to query resources for " + ProviderConstants.OPERATION_EMPI_BATCH_RUN, theE); } return total; }</code><technical_language>above, recommend long int</technical_language>

Target:
public long runEmpiOnTargetType(String theTargetType, String theCriteria) { resolveTargetTypeOrThrowException(theTargetType); SearchParameterMap spMap = myEmpiSearchParamSvc.getSearchParameterMapFromCriteria(theTargetType, theCriteria); spMap.setLoadSynchronousUpTo(BUFFER_SIZE); ISearchBuilder searchBuilder = myEmpiSearchParamSvc.generateSearchBuilderForType(theTargetType); return submitAllMatchingResourcesToEmpiChannel(spMap, searchBuilder); }
Source:
<code>public String getDisplayName() { <START> return "Set build status on Github commit"; <END> }</code><technical_language>case: GitHub</technical_language>

Target:
public String getDisplayName() { return "Set build status on GitHub commit"; }
Source:
<code>public void handleCommand(ChannelUID channelUID, Command command) { if (active) { if (command instanceof RefreshType) { logger.debug("Refreshing channel {}", channelUID); coapClient.asyncGet(this); return; } switch (channelUID.getId()) { case CHANNEL_POWER: <START> setState(((OnOffType) command)); <END> break; default: logger.error("Unknown channel UID {}", channelUID); } } }</code><technical_language>if accidentally sends incompatible type this channel? run a ClassCastException, you</technical_language>

Target:
public void handleCommand(ChannelUID channelUID, Command command) { if (active) { if (command instanceof RefreshType) { logger.debug("Refreshing channel {}", channelUID); coapClient.asyncGet(this); return; } switch (channelUID.getId()) { case CHANNEL_POWER: if (command instanceof OnOffType) { setState(((OnOffType) command)); } else { logger.debug("Cannot handle command '{}' for channel '{}'", command, CHANNEL_POWER); } break; default: logger.error("Unknown channel UID {}", channelUID); } } }
Source:
<code>private void processFlagFile(PrintStream err) throws CmdLineException, IOException { Path flagFile = Paths.get(flags.flagFile); <START> BufferedReader buffer = java.nio.file.Files.newBufferedReader(flagFile); <END> StringBuilder builder = new StringBuilder(); List<String> tokens = new ArrayList<String>(); boolean quoted = false; boolean escaped = false; int c; while ((c = buffer.read()) != -1) { if (c == 32 || c == 9 || c == 10 || c == 13) { if (quoted) { builder.append((char) c); } else if (builder.length() != 0) { tokens.add(builder.toString()); builder.setLength(0); } } else if (c == 34) { if (escaped) { if (quoted) { builder.setCharAt(builder.length()-1, (char) c); } else { builder.append((char) c); } } else { quoted = !quoted; } } else { builder.append((char) c); } escaped = c == 92; } buffer.close(); if (builder.length() != 0) { tokens.add(builder.toString()); } tokens = processArgs(tokens.toArray(new String[tokens.size()])); List<GuardLevel> previous = new ArrayList<>(Flags.guardLevels); Flags.guardLevels.clear(); flags.parse(tokens); Flags.guardLevels.addAll(previous); if (!flags.flagFile.isEmpty()) { err.println("ERROR - Arguments in the file cannot contain " + "--flagfile option."); isConfigValid = false; } }</code><technical_language>newBufferedReader requires a charset: java.nio.file.Files.newBufferedReader(flagFile, UTF_8); Also, new line need wrapped lines (longer 80 chars). wrapped "=" characters new line indented spaces</technical_language>

Target:
private void processFlagFile(PrintStream err) throws CmdLineException, IOException { Path flagFile = Paths.get(flags.flagFile); BufferedReader buffer = java.nio.file.Files.newBufferedReader(flagFile, UTF_8); StringBuilder builder = new StringBuilder(); List<String> tokens = new ArrayList<String>(); boolean quoted = false; boolean escaped = false; int c; while ((c = buffer.read()) != -1) { if (c == 32 || c == 9 || c == 10 || c == 13) { if (quoted) { builder.append((char) c); } else if (builder.length() != 0) { tokens.add(builder.toString()); builder.setLength(0); } } else if (c == 34) { if (escaped) { if (quoted) { builder.setCharAt(builder.length()-1, (char) c); } else { builder.append((char) c); } } else { quoted = !quoted; } } else { builder.append((char) c); } escaped = c == 92; } buffer.close(); if (builder.length() != 0) { tokens.add(builder.toString()); } flags.flagFile = ""; tokens = processArgs(tokens.toArray(new String[tokens.size()])); List<GuardLevel> previous = new ArrayList<>(Flags.guardLevels); Flags.guardLevels.clear(); flags.parse(tokens); Flags.guardLevels.addAll(previous); if (!flags.flagFile.isEmpty()) { err.println("ERROR - Arguments in the file cannot contain " + "--flagfile option."); isConfigValid = false; } }
Source:
<code>protected void autoLoad() { if (SessionContext.isLoggedIn() && (entryId != 0 || (className != null && classPK != 0))) { load(); } else { loadFile(); <START> } <END> }</code><technical_language>fileEntry != null check</technical_language>

Target:
protected void autoLoad() { if (SessionContext.isLoggedIn() && (entryId != 0 || (className != null && classPK != 0))) { load(); } else if (fileEntry != null) { loadFile(); } }
Source:
<code>private void finalizeFile( File file, File processFile ) throws IOException { if ( isKeepBackup() && !isDryRun() ) { File backupFile = FileUtil.getBackupFile( file ); if ( backupFile.exists() ) { FileUtil.deleteFile( backupFile ); } if ( isVerbose() ) { LOG.debug( " - backup original file {}", file ); } FileUtil.renameFile( file, backupFile ); } if ( isDryRun() ) { FileUtil.deleteFile( processFile ); } else { try { FileUtil.renameFile( processFile, file ); } catch ( IOException e ) { <START> LOG.warn( e.getMessage(), e ); <END> } } }</code><technical_language>want stacktrace here, far</technical_language>

Target:
private void finalizeFile( File file, File processFile ) throws IOException { if ( isKeepBackup() && !isDryRun() ) { File backupFile = FileUtil.getBackupFile( file ); if ( backupFile.exists() ) { FileUtil.deleteFile( backupFile ); } LOG.debug( " - backup original file {}", file ); FileUtil.renameFile( file, backupFile ); } if ( isDryRun() ) { FileUtil.deleteFile( processFile ); } else { try { FileUtil.renameFile( processFile, file ); } catch ( IOException e ) { LOG.warn( e.getMessage(), e ); } } }
Source:
<code>public ScalarFunctionImplementation specialize(BoundVariables boundVariables, int arity, TypeManager typeManager, FunctionRegistry functionRegistry) { checkArgument(arity == 1, "Expected arity to be 1"); Type type = boundVariables.getTypeVariable("T"); <START> RowType rowType = (RowType) type; <END> checkCondition(canCastFromJson(rowType), INVALID_CAST_ARGUMENT, "Cannot cast JSON to %s", rowType); List<RowField> rowFields = rowType.getFields(); BlockBuilderAppender[] fieldAppenders = new BlockBuilderAppender[rowFields.size()]; for (int i = 0; i < fieldAppenders.length; i++) { fieldAppenders[i] = createBlockBuilderAppender(rowFields.get(i).getType()); } MethodHandle methodHandle = METHOD_HANDLE.bindTo(rowType).bindTo(fieldAppenders).bindTo(getFieldNameToIndex(rowFields)).bindTo(getFieldNames(rowFields)); return new ScalarFunctionImplementation(true, ImmutableList.of(false), methodHandle, isDeterministic()); }</code><technical_language>inline variable type</technical_language>

Target:
public ScalarFunctionImplementation specialize(BoundVariables boundVariables, int arity, TypeManager typeManager, FunctionRegistry functionRegistry) { checkArgument(arity == 1, "Expected arity to be 1"); RowType rowType = (RowType) boundVariables.getTypeVariable("T"); checkCondition(canCastFromJson(rowType), INVALID_CAST_ARGUMENT, "Cannot cast JSON to %s", rowType); List<RowField> rowFields = rowType.getFields(); BlockBuilderAppender[] fieldAppenders = rowFields.stream() .map(rowField -> createBlockBuilderAppender(rowField.getType())) .toArray(BlockBuilderAppender[]::new); MethodHandle methodHandle = METHOD_HANDLE.bindTo(rowType).bindTo(fieldAppenders).bindTo(getFieldNameToIndex(rowFields)); return new ScalarFunctionImplementation(true, ImmutableList.of(false), methodHandle, isDeterministic()); }
Source:
<code>public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } <START> if (getClass() != obj.getClass()) { <END> return false; } SubjectEntity other = (SubjectEntity) obj; return ObjectUtils.objectsEqual(entityId, other.entityId) && ObjectUtils.objectsEqual(entityType, other.entityType); }</code><technical_language>this is a bit problematic, if compare SubjectEntity CommandAssociatedEntity, if represent entity, this fail due class types. Please consider instanceof instead of class comparison</technical_language>

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof SubjectEntity)) { return false; } SubjectEntity other = (SubjectEntity) obj; return Objects.equals(entityId, other.entityId) && Objects.equals(entityType, other.entityType); }
Source:
<code>boolean canCollapse() { boolean isAnnotatedNoCollapse = docInfo == null ? false : docInfo.isNoCollapse(); if (!isAnnotatedNoCollapse) { Ref ref = this.getDeclaration(); if (ref != null && ref.node != null) { JSDocInfo info = NodeUtil.getBestJSDocInfo(ref.node); if (info != null) { isAnnotatedNoCollapse = info.isNoCollapse(); } } } return !inExterns && !isGetOrSetDefinition() && !isAnnotatedNoCollapse && (declaredType || (parent == null || parent.canCollapseUnannotatedChildNames()) && <START> (globalSets > 0 || localSets > 0) && localSetsWithNoCollapse <= 0 && <END> deleteProps == 0); }</code><technical_language>localSetsWithNoCollapse negative</technical_language>

Target:
boolean canCollapse() { return !inExterns && !isGetOrSetDefinition() && !isCollapsingExplicitlyDenied() && (declaredType || (parent == null || parent.canCollapseUnannotatedChildNames()) && (globalSets > 0 || localSets > 0) && localSetsWithNoCollapse == 0 && deleteProps == 0); }
Source:
<code>public void testFullListOfTypes() { List<String> testData = new ArrayList<>(); testData.add("org.test.Person"); testData.add("java.util.List"); getListObjectThenOnFulfilledCallbackFn(simpleDataTypes, new ListBoxValues("Custom", "Edit", null)).onInvoke(testData); assertEquals("org.test.Person", getMapDataTypeNamesToDisplayNames().get("Person [org.test]")); assertEquals("java.util.List", getMapDataTypeNamesToDisplayNames().get("List [java.util]")); <START> getMapDataTypeNamesToDisplayNames().remove("Person [org.test]"); <END> getMapDataTypeNamesToDisplayNames().remove("List [java.util]"); }</code><technical_language>is this clean necessary? I suggest sharing variables tests, need clean up. JVM do for :)</technical_language>

Target:
public void testFullListOfTypes() { List<String> testData = new ArrayList<>(); testData.add("org.test.Person"); testData.add("net.second.Test"); getListObjectThenOnFulfilledCallbackFn(simpleDataTypes, new ListBoxValues("Custom", "Edit", null)).onInvoke(testData); assertEquals("org.test.Person", getMapDataTypeNamesToDisplayNames().get("Person [org.test]")); assertEquals("net.second.Test", getMapDataTypeNamesToDisplayNames().get("Test [net.second]")); }
Source:
<code>private Map<String, Collection<ICodeSystemVersion>> getExistingVersions() { final Map<String, Collection<ICodeSystemVersion>> versionsMap = Maps.newHashMap(); final IPublishOperationConfiguration configuration = ConfigurationThreadLocal.getConfiguration(); for (final String toolingId : configuration.getToolingIds()) { <START> final String shortName = ConfigurationThreadLocal.getConfiguration().getCodeSystemShortName(); <END> final String repositoryUuid = CodeSystemUtils.getRepositoryUuid(toolingId); final Collection<ICodeSystemVersion> versions = new CodeSystemRequests(repositoryUuid) .prepareSearchCodeSystemVersion() .setCodeSystemShortName(shortName) .build(IBranchPath.MAIN_BRANCH) .executeSync(getEventBus()) .getVersions(); versionsMap.put(toolingId, versions); } return versionsMap; }</code><technical_language>This breaks cross repository versioning process (like SDD versioning). Remove shortName filter code system version search request get existing versions "tooling"</technical_language>

Target:
private Map<String, Collection<ICodeSystemVersion>> getExistingVersions() { final Map<String, Collection<ICodeSystemVersion>> existingVersions = Maps.newHashMap(); final IPublishOperationConfiguration configuration = ConfigurationThreadLocal.getConfiguration(); for (final String toolingId : configuration.getToolingIds()) { final String shortName = ConfigurationThreadLocal.getConfiguration().getCodeSystemShortName(); final String repositoryUuid = CodeSystemUtils.getRepositoryUuid(toolingId); final CodeSystemVersionSearchRequestBuilder requestBuilder = new CodeSystemRequests(repositoryUuid) .prepareSearchCodeSystemVersion(); if (toolingId.equals(configuration.getPrimaryToolingId())) { requestBuilder.setCodeSystemShortName(shortName); } final List<ICodeSystemVersion> versions = requestBuilder .build(IBranchPath.MAIN_BRANCH) .executeSync(getEventBus()) .getItems(); existingVersions.put(toolingId, versions); } return existingVersions; }
Source:
<code>public void onMessage(NodeRegistrationContainerReport nodeRegistrationContainerReport, EventPublisher publisher) { if (chillModeManager.getInChillMode()) { if (validate()) { <START> chillModeManager.validateChillModeExitRules(publisher); <END> return; } } else { return; } process(nodeRegistrationContainerReport); if(chillModeManager.getInChillMode()) { SCMChillModeManager.getLogger().info( "SCM in chill mode. % containers have at least one" + " reported replica.", (containerWithMinReplicas.get() / maxContainer) * 100); } if (validate()) { chillModeManager.validateChillModeExitRules(publisher); return; } }</code><technical_language>validation add new report data threshold</technical_language>

Target:
public void onMessage(NodeRegistrationContainerReport nodeRegistrationContainerReport, EventPublisher publisher) { if (chillModeManager.getInChillMode()) { if (validate()) { return; } process(nodeRegistrationContainerReport); if (chillModeManager.getInChillMode()) { SCMChillModeManager.getLogger().info( "SCM in chill mode. % containers have at least one" + " reported replica.", (containerWithMinReplicas.get() / maxContainer) * 100); } if (validate()) { chillModeManager.validateChillModeExitRules(publisher); } } }
Source:
<code>public TextAnnotationMapDBHandler(String dbFile) { try { db = DBMaker.fileDB(dbFile).closeOnJvmShutdown().make(); } catch (DBException e) { logger.warn("mapdb couldn't instantiate db using file '{}': check error and either remove lock, " + "repair file, or delete file.", dbFile); e.printStackTrace(); <START> System.err.println("mapdb couldn't instantiate db using file '" + dbFile + <END> "': check error and either remove lock, repair file, or delete file."); throw e; } }</code><technical_language>keeping System.err.println logger.warn</technical_language>

Target:
public TextAnnotationMapDBHandler(String dbFile) { try { db = DBMaker.fileDB(dbFile).closeOnJvmShutdown().make(); } catch (DBException e) { e.printStackTrace(); System.err.println("mapdb couldn't instantiate db using file '" + dbFile + "': check error and either remove lock, repair file, or delete file."); throw e; } }
Source:
<code>public static boolean validateTemplateString(String template) { template = template.trim(); if (template.equals("ID")) { return true; } else if (template.equals("LABEL")) { return true; } else if (template.equals("TYPE")) { return true; } else if (template.equals("CLASS_TYPE")) { return true; } else if (template.matches("^(>?C|>{0,2}A[LTI]?|>?P|>?D|>?I|>?R|>?DT) .*")) { return true; } else if (template.startsWith("PROPERTY_TYPE")) { return true; } else if (template.startsWith("CHARACTERISTIC")) { return true; } else if (template.startsWith("INDIVIDUAL_TYPE")) { return true; } else { <START> return template.matches("^(SC|EC|DC|SP|EP|DP|IP|NI|SI|DI|CI|PI|RI|II).*"); <END> } }</code><technical_language>Listing options explicitly is more clear. some of a space, a not. way, this overlaps previous regex. complete regex</technical_language>

Target:
public static boolean validateTemplateString(String template) { template = template.trim(); if (template.equals("ID")) { return true; } else if (template.equals("LABEL")) { return true; } else if (template.equals("TYPE")) { return true; } else if (template.equals("CLASS_TYPE")) { return true; } else if (template.equals("PROPERTY_TYPE")) { return true; } else if (template.equals("DOMAIN")) { return true; } else if (template.equals("RANGE")) { return true; } else if (template.matches("^CHARACTERISTIC( SPLIT=.+)?$")) { return true; } else if (template.matches("^INDIVIDUAL_TYPE( SPLIT=.+)?$")) { return true; } else if (template.matches("^>{0,2}A[LTI]? .*")) { return true; } else if (template.matches("^>?(C .*|CI.?|[SED]C .*)")) { return true; } else if (template.matches("^(P .*|PI.?|[SEDI]P .*)")) { return true; } else return template.matches("^(I .*|II.?|[SD]I .*)"); }
Source:
<code>private void checkDeployedProject(String projectName) { ServersView2 serversView = new ServersView2(); serversView.open(); ServerModule module = serversView.getServer(FULL_SERVER_NAME) .getModule(new RegexMatcher(".*" + projectName + ".*")); new WaitUntil(new ServerModuleHasState(module, ServerState.STARTED), TimePeriod.getCustom(30)); ModuleLabel moduleLabel = module.getLabel(); ServerState moduleState = moduleLabel.getState(); <START> assertTrue("Module has not been started!", moduleState == ServerState.STARTED); <END> }</code><technical_language>lines of definitions necessary? shorter module.getLabel().getState() in assert</technical_language>

Target:
private void checkDeployedProject(String projectName) { ServersView2 serversView = new ServersView2(); serversView.open(); ServerModule module = serversView.getServer(FULL_SERVER_NAME) .getModule(new RegexMatcher(".*" + projectName + ".*")); new WaitUntil(new ServerModuleHasState(module, ServerState.STARTED), TimePeriod.getCustom(30)); ModuleLabel moduleLabel = module.getLabel(); assertTrue("Module has not been started!", moduleLabel.getState() == ServerState.STARTED); }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); userManager = new UserManager(this); if (userManager.getActiveUser() == null) { promptForUserInformation(); } else { loadData(); } <START> filteredListModel = new ListModel<ExpenseClaim>("filtered_List", getApplicationContext()); <END> filteredTagsList = new ArrayList<Tag>(); getListView().setOnItemLongClickListener(new LongClickDeleteListener(this, new LongClickDeleteListener.OnDeleteListener() { @Override public void onDelete(int position) { showDeleteAlertDialog(position); } @Override public boolean shouldDelete(int position) { return true; } })); }</code><technical_language>pass this for context</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); userManager = new UserManager(this); if (userManager.getActiveUser() == null) { promptForUserInformation(); } else { loadData(); } getListView().setOnItemLongClickListener(new LongClickDeleteListener(this, new LongClickDeleteListener.OnDeleteListener() { @Override public void onDelete(int position) { showDeleteAlertDialog(position); } @Override public boolean shouldDelete(int position) { return true; } })); }
Source:
<code>public MutationPlan compile(final CreateFunctionStatement create) throws SQLException { if(create.isReplace()) { throw new SQLFeatureNotSupportedException(); } final PhoenixConnection connection = statement.getConnection(); PhoenixConnection connectionToBe = connection; Scan scan = new Scan(); <START> final StatementContext context = new StatementContext(statement, FromCompiler.EMPTY_TABLE_RESOLVER, scan, new SequenceManager(statement)); <END> final MetaDataClient client = new MetaDataClient(connectionToBe); return new MutationPlan() { @Override public ParameterMetaData getParameterMetaData() { return context.getBindManager().getParameterMetaData(); } @Override public MutationState execute() throws SQLException { try { return client.createFunction(create); } finally { if (client.getConnection() != connection) { client.getConnection().close(); } } } @Override public ExplainPlan getExplainPlan() throws SQLException { return new ExplainPlan(Collections.singletonList("CREATE FUNCTION")); } @Override public PhoenixConnection getConnection() { return connection; } @Override public StatementContext getContext() { return context; } }; }</code><technical_language>Minor nit: other constructor public StatementContext(PhoenixStatement statement)</technical_language>

Target:
public MutationPlan compile(final CreateFunctionStatement create) throws SQLException { final PhoenixConnection connection = statement.getConnection(); PhoenixConnection connectionToBe = connection; final StatementContext context = new StatementContext(statement); final MetaDataClient client = new MetaDataClient(connectionToBe); return new MutationPlan() { @Override public ParameterMetaData getParameterMetaData() { return context.getBindManager().getParameterMetaData(); } @Override public MutationState execute() throws SQLException { try { return client.createFunction(create); } finally { if (client.getConnection() != connection) { client.getConnection().close(); } } } @Override public ExplainPlan getExplainPlan() throws SQLException { return new ExplainPlan(Collections.singletonList("CREATE FUNCTION")); } @Override public PhoenixConnection getConnection() { return connection; } @Override public StatementContext getContext() { return context; } }; }
Source:
<code>private boolean calculateConditions(Rule rule) { List<Condition> conditions = ((RuntimeRule) rule).getConditions(); if (conditions.size() == 0) { return true; } <START> for (Iterator< Condition>it = conditions.iterator(); it.hasNext();) { <END> RuntimeCondition c = (RuntimeCondition) it.next(); ConditionHandler tHandler = c.getModuleHandler(); Map<String, Object> context = getContext(rule.getUID(), c.getConnections()); if (!tHandler.isSatisfied(context)) { logger.debug("The condition '{}' of rule '{}' is unsatisfied.", new Object[] { c.getId(), rule.getUID() }); return false; } } return true; }</code><technical_language>incorrect space @</technical_language>

Target:
private boolean calculateConditions(Rule rule) { List<Condition> conditions = ((RuntimeRule) rule).getConditions(); if (conditions.size() == 0) { return true; } RuleStatus ruleStatus = null; for (Iterator< Condition>it = conditions.iterator(); it.hasNext();) { ruleStatus = getRuleStatus(rule.getUID()); if (ruleStatus != RuleStatus.RUNNING) { return false; } RuntimeCondition c = (RuntimeCondition) it.next(); ConditionHandler tHandler = c.getModuleHandler(); Map<String, Object> context = getContext(rule.getUID(), c.getConnections()); if (!tHandler.isSatisfied(context)) { logger.debug("The condition '{}' of rule '{}' is unsatisfied.", new Object[] { c.getId(), rule.getUID() }); return false; } } return true; }
Source:
<code>public void concatMapRangeAsyncLoopIssue2876() { <START> final long durationSeconds = 10; <END> final long startTime = System.currentTimeMillis(); for (int i = 0;; i++) { if (System.currentTimeMillis()-startTime > TimeUnit.SECONDS.toMillis(durationSeconds)) return; if (i % 1000 == 0) { System.out.println("concatMapRangeAsyncLoop > " + i); } TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); Observable.range(0, 1000) .concatMap(new Func1<Integer, Observable<Integer>>() { @Override public Observable<Integer> call(Integer t) { return Observable.from(Arrays.asList(t)); } }) .observeOn(Schedulers.computation()).subscribe(ts); ts.awaitTerminalEvent(2500, TimeUnit.MILLISECONDS); ts.assertTerminalEvent(); ts.assertNoErrors(); assertEquals(1000, ts.getOnNextEvents().size()); assertEquals((Integer)999, ts.getOnNextEvents().get(999)); } }</code><technical_language>change this 2 seconds</technical_language>

Target:
public void concatMapRangeAsyncLoopIssue2876() { final long durationSeconds = 2; final long startTime = System.currentTimeMillis(); for (int i = 0;; i++) { if (System.currentTimeMillis()-startTime > TimeUnit.SECONDS.toMillis(durationSeconds)) return; if (i % 1000 == 0) { System.out.println("concatMapRangeAsyncLoop > " + i); } TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); Observable.range(0, 1000) .concatMap(new Func1<Integer, Observable<Integer>>() { @Override public Observable<Integer> call(Integer t) { return Observable.from(Arrays.asList(t)); } }) .observeOn(Schedulers.computation()).subscribe(ts); ts.awaitTerminalEvent(2500, TimeUnit.MILLISECONDS); ts.assertTerminalEvent(); ts.assertNoErrors(); assertEquals(1000, ts.getOnNextEvents().size()); assertEquals((Integer)999, ts.getOnNextEvents().get(999)); } }
Source:
<code>public B handler(ChannelHandler handler) { ObjectUtil.checkNotNull(handler, "handler"); <START> this.handler = handler; <END> return self(); }</code><technical_language>merge lines</technical_language>

Target:
public B handler(ChannelHandler handler) { this.handler = ObjectUtil.checkNotNull(handler, "handler"); return self(); }
Source:
<code>public void open() { try { if (!mDevice.isScreenOn()) { mDevice.wakeUp(); } } catch (RemoteException e) { throw new RuntimeException("Could not unlock the device.", e); } if (mDevice.hasObject(By.res("com.android.systemui", "keyguard_bottom_area"))) { mDevice.pressMenu(); mDevice.waitForIdle(); } String pkg = getPackage(); long launchInitiationTimeMs = System.currentTimeMillis(); <START> registerWatcher( <END> AppIsNotRespondingWatcher.class.getSimpleName(), new AppIsNotRespondingWatcher(InstrumentationRegistry.getInstrumentation())); if (mFavorShellCommands) { String output = null; try { Intent intent = mInstrumentation .getContext() .getPackageManager() .getLaunchIntentForPackage(pkg); mInstrumentation.getContext().startActivity(intent); Log.i(LOG_TAG, String.format("Sent command to launch: %s", pkg)); } catch (ActivityNotFoundException e) { removeWatcher(AppIsNotRespondingWatcher.class.getSimpleName()); throw new RuntimeException(String.format("Failed to find package: %s", pkg), e); } } else { String id = getLauncherName(); if (!mDevice.hasObject(By.pkg(pkg).depth(0))) { mLauncherStrategy.launch(id, pkg); Log.i(LOG_TAG, "Launched package: id=" + id + ", pkg=" + pkg); } } if (!mDevice.wait(Until.hasObject(By.pkg(pkg).depth(0)), mLaunchTimeout)) { removeWatcher(AppIsNotRespondingWatcher.class.getSimpleName()); throw new IllegalStateException( String.format( "Did not find package, %s, in foreground after %d ms.", pkg, System.currentTimeMillis() - launchInitiationTimeMs)); } removeWatcher(AppIsNotRespondingWatcher.class.getSimpleName()); }</code><technical_language>This is fine for now, love a register these. For now, move a "registerDialogWatchers" method others added modifying here</technical_language>

Target:
public void open() { try { if (!mDevice.isScreenOn()) { mDevice.wakeUp(); } } catch (RemoteException e) { throw new RuntimeException("Could not unlock the device.", e); } if (mDevice.hasObject(By.res("com.android.systemui", "keyguard_bottom_area"))) { mDevice.pressMenu(); mDevice.waitForIdle(); } String pkg = getPackage(); long launchInitiationTimeMs = System.currentTimeMillis(); registerDialogWatchers(); if (mFavorShellCommands) { String output = null; try { Intent intent = mInstrumentation .getContext() .getPackageManager() .getLaunchIntentForPackage(pkg); mInstrumentation.getContext().startActivity(intent); Log.i(LOG_TAG, String.format("Sent command to launch: %s", pkg)); } catch (ActivityNotFoundException e) { removeDialogWatchers(); throw new RuntimeException(String.format("Failed to find package: %s", pkg), e); } } else { String id = getLauncherName(); if (!mDevice.hasObject(By.pkg(pkg).depth(0))) { mLauncherStrategy.launch(id, pkg); Log.i(LOG_TAG, "Launched package: id=" + id + ", pkg=" + pkg); } } if (!mDevice.wait(Until.hasObject(By.pkg(pkg).depth(0)), mLaunchTimeout)) { removeDialogWatchers(); throw new IllegalStateException( String.format( "Did not find package, %s, in foreground after %d ms.", pkg, System.currentTimeMillis() - launchInitiationTimeMs)); } removeDialogWatchers(); }
Source:
<code>public Description matchMethod(MethodTree tree, VisitorState state) { AtomicBoolean badMethod = new AtomicBoolean(false); tree.getParameters().forEach(param1 -> { Tree outerTree = param1.getType(); tree.getParameters().forEach(param2 -> { if (!param1.equals(param2)) { Tree innerTree = param2.getType(); badMethod.set(badMethod.get() || isSubTypeOf(outerTree, innerTree, state)); } }); }); if (badMethod.get()) { return buildDescription(tree) .setMessage("Some argument types are equal or are subtypes of each other. Consider using a " <START> + "builder instead.") <END> .build(); } return Description.NO_MATCH; }</code><technical_language>put this summary @BugPattern instead</technical_language>

Target:
public Description matchMethod(MethodTree tree, VisitorState state) { AtomicBoolean badMethod = new AtomicBoolean(false); tree.getParameters().forEach(param1 -> tree.getParameters().forEach(param2 -> { if (!param1.equals(param2)) { Type outerType = getType(param1.getType(), state); Type innerType = getType(param2.getType(), state); TypesToCompare typesToCompare = ImmutableTypesToCompare.builder() .subType(outerType) .superType(innerType) .build(); badMethod.set(badMethod.get() || subTypeCheck(typesToCompare, state)); } })); if (badMethod.get()) { return buildDescription(tree).build(); } return Description.NO_MATCH; }
Source:
<code>public String toString() { StringBuilder sb = new StringBuilder(); String NEW_LINE = System.getProperty("line.separator"); sb.append(this.getClass().getName() + " Object: " + NEW_LINE); <START> sb.append(" contents {" + getResources() + "}" + NEW_LINE); <END> return sb.toString(); }</code><technical_language>+ string builder defeats purpose of class. Consider .append instead of +. A more readable version user String.format("%s contents[%s]", getClass().getName(), getResources);</technical_language>

Target:
public String toString() { return String.format("%s Object: \n contents {%s}\n", this.getClass().getName(), getResources()); }
Source:
<code>void assign(AssignableReplica assignableReplica) { if (!addToAssignmentRecord(assignableReplica, _currentAssignments)) { throw new HelixException(String <START> .format("Resource %s already has a replica from partition %s on this node", <END> assignableReplica.getResourceName(), assignableReplica.getPartitionName())); } else { if (assignableReplica.isReplicaTopState()) { addToAssignmentRecord(assignableReplica, _currentTopStateAssignments); } _totalReplicaAssignmentCount += 1; assignableReplica.getCapacity().entrySet().stream() .forEach(entry -> updateCapacityAndUtilization(entry.getKey(), entry.getValue())); } }</code><technical_language>add node information well? This assignment implementation is similar in Task Framework, I realized if do include node name, a lot of times logs a lot helpful</technical_language>

Target:
void assign(AssignableReplica assignableReplica) { if (!addToAssignmentRecord(assignableReplica, _currentAssignments)) { throw new HelixException(String .format("Resource %s already has a replica from partition %s on node %s", assignableReplica.getResourceName(), assignableReplica.getPartitionName(), getInstanceName())); } else { if (assignableReplica.isReplicaTopState()) { addToAssignmentRecord(assignableReplica, _currentTopStateAssignments); } assignableReplica.getCapacity().entrySet().stream().forEach( capacity -> updateCapacityAndUtilization(capacity.getKey(), capacity.getValue())); } }
Source:
<code>private void singleScanInternal(boolean announceUnchangedDevices) { try { Delta<UsbSerialDeviceInformation> delta = deltaUsbSerialScanner.scan(); announceAddedDevices(delta.getAdded()); announceRemovedDevices(delta.getRemoved()); if (announceUnchangedDevices) { announceAddedDevices(delta.getUnchanged()); } } catch (IOException e) { <START> logger.warn("An IOException prevented a scan for USB serial devices: {}, message {}", e.getClass(), <END> e.getMessage()); } }</code><technical_language>injecting name proper place simple-name of exception class, i.e. java ...warn("An prevented a scan for USB serial devices: {}", e.getClass().getSimpleName(), e.getMessage());</technical_language>

Target:
private void singleScanInternal(boolean announceUnchangedDevices) { try { Delta<UsbSerialDeviceInformation> delta = deltaUsbSerialScanner.scan(); announceAddedDevices(delta.getAdded()); announceRemovedDevices(delta.getRemoved()); if (announceUnchangedDevices) { announceAddedDevices(delta.getUnchanged()); } } catch (IOException e) { logger.warn("A prevented a scan for USB serial devices: {}", e.getClass().getSimpleName(), e.getMessage()); } }
Source:
<code>public Collection<TargetedResequencing> listAllTargetedResequencing() throws IOException { if (targetedResequencingStore != null) { return targetedResequencingStore.listAll(); } else { <START> throw new IOException("No securityStore available. Check that it has been declared in the Spring config."); <END> } }</code><technical_language>s/security/targedResequencing/</technical_language>

Target:
public Collection<TargetedResequencing> listAllTargetedResequencing() throws IOException { if (targetedResequencingStore != null) { return targetedResequencingStore.listAll(); } else { throw new IOException("No targetedResequencingStore available. Check that it has been declared in the Spring config."); } }
Source:
<code>static BitmapFactory.Options createBitmapOptions(Request data) { final boolean justBounds = data.hasSize(); final boolean hasConfig = data.config != null; <START> final boolean instantiate = hasConfig || justBounds; <END> final BitmapFactory.Options options = instantiate ? new BitmapFactory.Options() : null; if (justBounds) { options.inJustDecodeBounds = true; } if (hasConfig) { options.inPreferredConfig = data.config; } return options; }</code><technical_language>This is descriptive. do: java BitmapFactory.Options options = null; if (hasConfig || justBounds) { options = new.. }</technical_language>

Target:
static BitmapFactory.Options createBitmapOptions(Request data) { final boolean justBounds = data.hasSize(); final boolean hasConfig = data.config != null; BitmapFactory.Options options = null; if (justBounds || hasConfig) { options = new BitmapFactory.Options(); options.inJustDecodeBounds = justBounds; if (hasConfig) { options.inPreferredConfig = data.config; } } return options; }
Source:
<code>private static int compDigitSequence(String seq1, String seq2) { int compRes = ((Integer) Integer.parseInt(seq1)).compareTo(Integer.parseInt(seq2)); <START> return compRes != 0 ? compRes : compNonDigitSequence(seq1, seq2); <END> }</code><technical_language>easier read a positive check a negative one</technical_language>

Target:
private static int compDigitSequence(String seq1, String seq2) { int compRes = ((Integer) Integer.parseInt(seq1)).compareTo(Integer.parseInt(seq2)); return compRes == 0 ? compNonDigitSequence(seq1, seq2) : compRes; }
Source:
<code>public void testIntList() throws Exception { List<Integer> testIntList = new ArrayList<Integer>(); Arrays.stream(testInts).forEach(testIntList::add); <START> ao.insertIntList(testIntList); <END> assertThat(ao.fetchIntList()).containsExactlyElementsOf(testIntList); }</code><technical_language>Meh: Alternatively: java List<Integer> testIntList = Arrays.stream(testInts).boxed().collect(toList());</technical_language>

Target:
public void testIntList() throws Exception { List<Integer> testIntList = Arrays.stream(testInts).boxed().collect(Collectors.toList()); ao.insertIntList(testIntList); assertThat(ao.fetchIntList()).containsExactlyElementsOf(testIntList); }