auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void toggle() { enabled = !enabled; <START> System.out.println("Players location: " + Players.getMyPlayer().getLocation()); <END> }</code><technical_language>add plane? System.out.println("Plane: " + Game.getPlane());</technical_language>

Target:
public void toggle() { enabled = !enabled; System.out.println("Location: " + Players.getMyPlayer().getLocation()); System.out.println("Plane: " + Game.getPlane()); }
Source:
<code>protected void processIncoming() throws IOException, ClientConnectionException { if (this.ibuff == null) { int read = readBuffer(headerBuffer); if (read <= 0) { return; } this.message = getMessage(headerBuffer, read); int contentLength = this.message.getContentLength(); if (contentLength == -1) { emitOnMessageReceived(this.message); return; } <START> int length = this.message.getContent().getBytes(UTF8).length; <END> if (contentLength == length - 1) { emitOnMessageReceived(this.message); return; } else if (contentLength > length) { this.ibuff = ByteBuffer.allocate(contentLength - length + 1); } else { String content = this.message.getContent(); this.message.withContent(content.substring(0, contentLength)); emitOnMessageReceived(this.message); headerBuffer.put(content.substring(contentLength).getBytes(UTF8)); } } readBuffer(this.ibuff); String additionalContent = new String(this.ibuff.array(), UTF8); int length = this.message.getContent().getBytes(UTF8).length + additionalContent.getBytes(UTF8).length; if (this.message.getContentLength() != length - 1) { return; } this.message.withAdditionalContent(additionalContent); emitOnMessageReceived(this.message); }</code><technical_language>content needs saved a buffer a separate counter of data read. Converted UTF8 is guaranteed byte count</technical_language>

Target:
protected void processIncoming() throws IOException, ClientConnectionException { if (this.ibuff == null) { int read = readBuffer(headerBuffer); if (read <= 0) { return; } this.message = getMessage(headerBuffer, read); int contentLength = this.message.getContentLength(); if (contentLength == -1) { emitOnMessageReceived(this.message); return; } int length = this.message.getContent().length; if (contentLength == length - 1) { emitOnMessageReceived(this.message); return; } else if (contentLength > length) { this.ibuff = ByteBuffer.allocate(contentLength - length + 1); } else { byte[] content = this.message.getContent(); this.message.withContent(Arrays.copyOfRange(content, 0, contentLength)); emitOnMessageReceived(this.message); headerBuffer.put(Arrays.copyOfRange(content, contentLength, content.length)); } } readBuffer(this.ibuff); byte[] additionalContent = this.ibuff.array(); int length = this.message.getContent().length + additionalContent.length; if (this.message.getContentLength() != length - 1) { return; } this.message.withAdditionalContent(additionalContent); emitOnMessageReceived(this.message); }
Source:
<code>private void install(Path binaryPath) { try { <START> platformService.setUnixExecutableBit(binaryPath); <END> } catch (IOException e) { logger.warn("Unix execute bit could not be set", e); } String command = binaryPath.toAbsolutePath().toString(); try { logger.info("Starting installer at {}", command); new ProcessBuilder(command).inheritIO().start(); } catch (IOException e) { logger.warn("Installation could not be started", e); } }</code><technical_language>Formatting</technical_language>

Target:
void install(Path binaryPath) { try { platformService.setUnixExecutableAndWritableBits(binaryPath); } catch (IOException e) { logger.warn("Unix execute bit could not be set", e); } String command = binaryPath.toAbsolutePath().toString(); try { logger.info("Starting installer at {}", command); new ProcessBuilder(command).inheritIO().start(); } catch (IOException e) { logger.warn("Installation could not be started", e); } }
Source:
<code>CredentialInformation(String connectionString) { if (CoreUtils.isNullOrEmpty(connectionString)) { <START> throw new IllegalArgumentException("'Connection string' cannot be null or empty."); <END> } String[] args = connectionString.split(";"); if (args.length < 3) { throw new IllegalArgumentException("invalid connection string segment count"); } URL baseUri = null; String id = null; byte[] secret = null; for (String arg : args) { String segment = arg.trim(); String lowerCase = segment.toLowerCase(Locale.US); if (lowerCase.startsWith(ENDPOINT)) { try { baseUri = new URL(segment.substring(ENDPOINT.length())); } catch (MalformedURLException ex) { throw new IllegalArgumentException(ex); } } else if (lowerCase.startsWith(ID)) { id = segment.substring(ID.length()); } else if (lowerCase.startsWith(SECRET)) { String secretBase64 = segment.substring(SECRET.length()); secret = Base64.getDecoder().decode(secretBase64); } } this.baseUri = baseUri; this.id = id; this.secret = secret; if (this.baseUri == null || this.id == null || this.secret == null) { throw new IllegalArgumentException("Could not parse 'connectionString'." + " Expected format: 'endpoint={endpoint};id={id};secret={secret}'. Actual:" + connectionString); } }</code><technical_language>"'connectionString' null empty."</technical_language>

Target:
CredentialInformation(String connectionString) { if (CoreUtils.isNullOrEmpty(connectionString)) { throw new IllegalArgumentException("'connectionString' cannot be null or empty."); } String[] args = connectionString.split(";"); if (args.length < 3) { throw new IllegalArgumentException("invalid connection string segment count"); } URL baseUri = null; String id = null; byte[] secret = null; for (String arg : args) { String segment = arg.trim(); String lowerCase = segment.toLowerCase(Locale.US); if (lowerCase.startsWith(ENDPOINT)) { try { baseUri = new URL(segment.substring(ENDPOINT.length())); } catch (MalformedURLException ex) { throw new IllegalArgumentException(ex); } } else if (lowerCase.startsWith(ID)) { id = segment.substring(ID.length()); } else if (lowerCase.startsWith(SECRET)) { String secretBase64 = segment.substring(SECRET.length()); secret = Base64.getDecoder().decode(secretBase64); } } this.baseUri = baseUri; this.id = id; this.secret = secret; if (this.baseUri == null || this.id == null || this.secret == null) { throw new IllegalArgumentException("Could not parse 'connectionString'." + " Expected format: 'endpoint={endpoint};id={id};secret={secret}'. Actual:" + connectionString); } }
Source:
<code>public void testUndefined() { foldSame("var x = undefined"); foldSame("function f(f) {var undefined=2;var x = undefined;}"); enableNormalize(); fold("var x = undefined", "var x=void 0"); foldSame( "var undefined = 1;" + "function f() {var undefined=2;var x = undefined;}"); foldSame("function f(undefined) {}"); foldSame("try catch(undefined) {}"); foldSame("for (undefined in {}) {}"); foldSame("undefined++;"); disableNormalize(); <START> foldSame("undefined += undefined;"); <END> }</code><technical_language>result change</technical_language>

Target:
public void testUndefined() { foldSame("var x = undefined"); foldSame("function f(f) {var undefined=2;var x = undefined;}"); enableNormalize(); fold("var x = undefined", "var x=void 0"); foldSame( "var undefined = 1;" + "function f() {var undefined=2;var x = undefined;}"); foldSame("function f(undefined) {}"); foldSame("try catch(undefined) {}"); foldSame("for (undefined in {}) {}"); foldSame("undefined++;"); disableNormalize(); foldSame("undefined += undefined;"); enableNormalize(); fold("undefined += undefined;", "undefined = void 0 + void 0;"); }
Source:
<code>private void importDocuments(YamlNode imdgRoot) throws Exception { YamlMapping rootAsMapping = asMapping(imdgRoot); YamlSequence importSeq = rootAsMapping.childAsSequence(ConfigSections.IMPORT.name); if (importSeq == null || importSeq.childCount() == 0) { return; } for (YamlNode importNode : importSeq.children()) { String resource = asScalar(importNode).nodeValue(); URL url = ConfigLoader.locateConfig(resource); if (url == null) { throw new InvalidConfigurationException("Failed to load resource: " + resource); } if (!currentlyImportedFiles.add(url.getPath())) { <START> throw new InvalidConfigurationException("Cyclic loading of resource '" + url.getPath() + "' detected!"); <END> } YamlNode rootLoaded; try { rootLoaded = YamlLoader.load(url.openStream()); } catch (Exception ex) { throw new InvalidConfigurationException("Loading YAML document from resource " + url.getPath() + " failed", ex); } YamlNode imdgRootLoaded = asMapping(rootLoaded).child(ConfigSections.HAZELCAST.name().toLowerCase()); replaceVariables(asW3cNode(imdgRootLoaded)); importDocuments(imdgRootLoaded); merge(imdgRootLoaded, imdgRoot); } ((MutableYamlMapping) rootAsMapping).removeChild(ConfigSections.IMPORT.name); }</code><technical_language>rephrase error message slightly, exception duplicate imports, necessarily cyclic</technical_language>

Target:
private void importDocuments(YamlNode imdgRoot) throws Exception { YamlMapping rootAsMapping = asMapping(imdgRoot); YamlSequence importSeq = rootAsMapping.childAsSequence(ConfigSections.IMPORT.name); if (importSeq == null || importSeq.childCount() == 0) { return; } for (YamlNode importNode : importSeq.children()) { String resource = asScalar(importNode).nodeValue(); URL url = ConfigLoader.locateConfig(resource); if (url == null) { throw new InvalidConfigurationException("Failed to load resource: " + resource); } if (!currentlyImportedFiles.add(url.getPath())) { throw new InvalidConfigurationException("Resource '" + url.getPath() + "' is already loaded! This can be due to" + " duplicate or cyclic imports."); } YamlNode rootLoaded; try { rootLoaded = YamlLoader.load(url.openStream()); } catch (Exception ex) { throw new InvalidConfigurationException("Loading YAML document from resource " + url.getPath() + " failed", ex); } YamlNode imdgRootLoaded = asMapping(rootLoaded).child(ConfigSections.HAZELCAST.name.toLowerCase()); if (imdgRootLoaded == null) { return; } replaceVariables(asW3cNode(imdgRootLoaded)); importDocuments(imdgRootLoaded); merge(imdgRootLoaded, imdgRoot); } ((MutableYamlMapping) rootAsMapping).removeChild(ConfigSections.IMPORT.name); }
Source:
<code>private static void checkSelfReference(@NotNull GoReferenceExpression o, PsiElement definition, AnnotationHolder holder) { GoExpression value = null; if (definition instanceof GoVarDefinition) { value = ((GoVarDefinition)definition).getValue(); } else if (definition instanceof GoConstDefinition) { value = ((GoConstDefinition)definition).getValue(); } if (value == null) return; PsiElement element = PsiTreeUtil.getTopmostParentOfType(o, GoExpression.class); <START> if (element == null) return; <END> if (value.equals(element)) holder.createErrorAnnotation(o, "Cyclic definition detected"); }</code><technical_language>This check is redundant. checked != null, value.equals(null) false</technical_language>

Target:
private static void checkSelfReference(@NotNull GoReferenceExpression o, PsiElement definition, AnnotationHolder holder) { GoExpression value = null; if (definition instanceof GoVarDefinition) { value = ((GoVarDefinition)definition).getValue(); } else if (definition instanceof GoConstDefinition) { value = ((GoConstDefinition)definition).getValue(); } if (value != null && value.equals(PsiTreeUtil.getTopmostParentOfType(o, GoExpression.class))) { holder.createErrorAnnotation(o, "Cyclic definition detected"); } }
Source:
<code>public D save(D definition) { Assert.notNull(definition, "Definition may not be null"); String name = definition.getName(); String def = definition.getDefinition(); validateBeforeSave(name, def); if(!ComposedJobUtil.isComposedJobDefinition(def)){ <START> List<ModuleDescriptor> moduleDescriptors = moduleDescriptors = <END> parser.parse(name, def, definitionKind); List<ModuleDefinition> moduleDefinitions = createModuleDefinitions(moduleDescriptors); if (!moduleDefinitions.isEmpty()) { definition.setModuleDefinitions(moduleDefinitions); } } D savedDefinition = repository.save(definition); return afterSave(savedDefinition); }</code><technical_language>typo</technical_language>

Target:
public D save(D definition) { Assert.notNull(definition, "Definition may not be null"); String name = definition.getName(); String def = definition.getDefinition(); validateBeforeSave(name, def); if(!ComposedJobUtil.isComposedJobDefinition(def)){ List<ModuleDescriptor> moduleDescriptors = parser.parse(name, def, definitionKind); List<ModuleDefinition> moduleDefinitions = createModuleDefinitions(moduleDescriptors); if (!moduleDefinitions.isEmpty()) { definition.setModuleDefinitions(moduleDefinitions); } } D savedDefinition = repository.save(definition); return afterSave(savedDefinition); }
Source:
<code>public void testFromInPredicateWithCastsAndNulls() { <START> Expression originalExpression = new InPredicate( <END> C_BIGINT.toSymbolReference(), new InListExpression(ImmutableList.of(cast(toExpression(null, SMALLINT), BIGINT)))); ExtractionResult result = fromPredicate(originalExpression); assertEquals(result.getRemainingExpression(), TRUE_LITERAL); assertEquals(result.getTupleDomain(), TupleDomain.none()); originalExpression = not(new InPredicate( cast(C_SMALLINT, BIGINT), new InListExpression(ImmutableList.of(toExpression(null, BIGINT))))); result = fromPredicate(originalExpression); assertEquals(result.getRemainingExpression(), not(equal(cast(C_SMALLINT, BIGINT), toExpression(null, BIGINT)))); assertEquals(result.getTupleDomain(), TupleDomain.all()); originalExpression = new InPredicate( C_BIGINT.toSymbolReference(), new InListExpression(ImmutableList.of(cast(toExpression(null, SMALLINT), BIGINT), toExpression(1L, BIGINT)))); result = fromPredicate(originalExpression); assertEquals(result.getRemainingExpression(), TRUE_LITERAL); assertEquals(result.getTupleDomain(), withColumnDomains(ImmutableMap.of(C_BIGINT, Domain.create(ValueSet.ofRanges(Range.equal(BIGINT, 1L)), false)))); originalExpression = not(new InPredicate( C_BIGINT.toSymbolReference(), new InListExpression(ImmutableList.of(cast(toExpression(null, SMALLINT), BIGINT), toExpression(1L, SMALLINT))))); result = fromPredicate(originalExpression); assertEquals(result.getRemainingExpression(), TRUE_LITERAL); assertEquals(result.getTupleDomain(), TupleDomain.none()); }</code><technical_language>building methods in testInPredicateWithNull, e.g: isNotNull(in(C_BIGINT, Arrays.asList(1L, 2L, null)));</technical_language>

Target:
public void testFromInPredicateWithCastsAndNulls() { assertPredicateIsAlwaysFalse(new InPredicate( C_BIGINT.toSymbolReference(), new InListExpression(ImmutableList.of(cast(toExpression(null, SMALLINT), BIGINT))))); Expression originalExpression = not(new InPredicate( cast(C_SMALLINT, BIGINT), new InListExpression(ImmutableList.of(toExpression(null, BIGINT))))); ExtractionResult result = fromPredicate(originalExpression); assertEquals(result.getRemainingExpression(), not(equal(cast(C_SMALLINT, BIGINT), toExpression(null, BIGINT)))); assertEquals(result.getTupleDomain(), TupleDomain.all()); originalExpression = new InPredicate( C_BIGINT.toSymbolReference(), new InListExpression(ImmutableList.of(cast(toExpression(null, SMALLINT), BIGINT), toExpression(1L, BIGINT)))); result = fromPredicate(originalExpression); assertEquals(result.getRemainingExpression(), TRUE_LITERAL); assertEquals(result.getTupleDomain(), withColumnDomains(ImmutableMap.of(C_BIGINT, Domain.create(ValueSet.ofRanges(Range.equal(BIGINT, 1L)), false)))); assertPredicateIsAlwaysFalse(not(new InPredicate( C_BIGINT.toSymbolReference(), new InListExpression(ImmutableList.of(cast(toExpression(null, SMALLINT), BIGINT), toExpression(1L, SMALLINT)))))); }
Source:
<code>public void process(QueryEnded event) { if (event.getCurrentValue() == QueryStatus.Status.CLOSED) { return; } QueryContext queryContext = queryService.getQueryContext(event.getQueryHandle()); if (queryContext == null) { LOG.warn("Could not find the context for " + event.getQueryHandle() + " for event:" + event.getCurrentValue() + ". No email generated"); return; } boolean whetherMailNotify = Boolean.parseBoolean(queryContext.getConf().get(GrillConfConstants.GRILL_WHETHER_MAIL_NOTIFY, GrillConfConstants.GRILL_WHETHER_MAIL_NOTIFY_DEFAULT)); if(!whetherMailNotify){ return; } String queryName = queryContext.getQueryName(); queryName = queryName == null ? "" : queryName; String mailSubject = "Query " + queryName + " " + queryContext.getStatus().getStatus() + ": " + event.getQueryHandle(); String mailMessage = createMailMessage(queryContext); <START> String to = queryContext.getSubmittedUser() + "@" + conf.get(GrillConfConstants.GRILL_SERVER_DOMAIN); <END> String cc = queryContext.getConf().get(GrillConfConstants.GRILL_QUERY_RESULT_EMAIL_CC, GrillConfConstants.GRILL_QUERY_RESULT_DEFAULT_EMAIL_CC); LOG.info("Sending completion email for query handle: " + event.getQueryHandle()); sendMail(host, port, from, to, cc, mailSubject, mailMessage, mailSmtpTimeout, mailSmtpConnectionTimeout); }</code><technical_language>Add a method in GrillService get server domain it. conf server conf, query conf</technical_language>

Target:
public void process(QueryEnded event) { if (event.getCurrentValue() == QueryStatus.Status.CLOSED) { return; } QueryContext queryContext = queryService.getQueryContext(event.getQueryHandle()); if (queryContext == null) { LOG.warn("Could not find the context for " + event.getQueryHandle() + " for event:" + event.getCurrentValue() + ". No email generated"); return; } boolean whetherMailNotify = Boolean.parseBoolean(queryContext.getConf().get(GrillConfConstants.GRILL_WHETHER_MAIL_NOTIFY, GrillConfConstants.GRILL_WHETHER_MAIL_NOTIFY_DEFAULT)); if(!whetherMailNotify){ return; } String queryName = queryContext.getQueryName(); queryName = queryName == null ? "" : queryName; String mailSubject = "Query " + queryName + " " + queryContext.getStatus().getStatus() + ": " + event.getQueryHandle(); String mailMessage = createMailMessage(queryContext); String to = queryContext.getSubmittedUser() + "@" + queryService.getServerDomain(); String cc = queryContext.getConf().get(GrillConfConstants.GRILL_QUERY_RESULT_EMAIL_CC, GrillConfConstants.GRILL_QUERY_RESULT_DEFAULT_EMAIL_CC); LOG.info("Sending completion email for query handle: " + event.getQueryHandle()); sendMail(host, port, from, to, cc, mailSubject, mailMessage, mailSmtpTimeout, mailSmtpConnectionTimeout); }
Source:
<code><START> public Uri getContentUri() { <END> return generateContentUri(UploadModel.context,getMediaUri().getPath()); }</code><technical_language>This is required. Instead of generating content uri here, simply pass UploadItem UploadableFile</technical_language>

Target:
public Uri getContentUri() { return originalContentUri; }
Source:
<code>public void onManagementStopped(ManagementTransitionInfo info) { synchronized (this) { if (managementContext == null && nonDeploymentManagementContext.getMode() == NonDeploymentManagementContext.NonDeploymentManagementContextMode.MANAGEMENT_STOPPED) { return; <START> } <END> if (managementContext != info.getManagementContext()) { throw new IllegalStateException("Has different management context: "+managementContext+"; expected "+info.getManagementContext()); } getSubscriptionContext().unsubscribeAll(); entityChangeListener = EntityChangeListener.NOOP; managementContextUsable.set(false); currentlyDeployed.set(false); executionContext = null; subscriptionContext = null; } entity.invalidateReferences(); synchronized (this) { managementContext = null; nonDeploymentManagementContext.setMode(NonDeploymentManagementContext.NonDeploymentManagementContextMode.MANAGEMENT_STOPPED); } }</code><technical_language>Worth a static import, of class least</technical_language>

Target:
public void onManagementStopped(ManagementTransitionInfo info) { synchronized (this) { if (managementContext == null && nonDeploymentManagementContext.getMode() == NonDeploymentManagementContextMode.MANAGEMENT_STOPPED) { return; } if (managementContext != info.getManagementContext()) { throw new IllegalStateException("Has different management context: "+managementContext+"; expected "+info.getManagementContext()); } getSubscriptionContext().unsubscribeAll(); entityChangeListener = EntityChangeListener.NOOP; managementContextUsable.set(false); currentlyDeployed.set(false); executionContext = null; subscriptionContext = null; } entity.invalidateReferences(); synchronized (this) { managementContext = null; nonDeploymentManagementContext.setMode(NonDeploymentManagementContextMode.MANAGEMENT_STOPPED); } }
Source:
<code>private static List<ApplicationTracer> getTracers() { if (tracers == null) { synchronized (ApplicationTracer.class) { <START> if (tracers == null) { <END> List<ApplicationTracer> t = new ArrayList<>(); for (ApplicationTracer tracer : ServiceLoader.load(EvaluationTrace.ApplicationTracer.class, Stapler.getCurrent().getWebApp().getClassLoader())) { try { t.add(tracer); } catch (Exception e) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Exception thrown when notifying tracer", e); } } } tracers = t; } } } return tracers; }</code><technical_language>Double-checked locking. Delete outer null check</technical_language>

Target:
private static List<ApplicationTracer> getTracers() { synchronized (ApplicationTracer.class) { if (tracers == null) { List<ApplicationTracer> t = new ArrayList<>(); for (ApplicationTracer tracer : ServiceLoader.load(EvaluationTrace.ApplicationTracer.class, Stapler.getCurrent().getWebApp().getClassLoader())) { try { t.add(tracer); } catch (Exception e) { if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Exception thrown when notifying tracer", e); } } } tracers = t; } } return tracers; }
Source:
<code>public void writeProjectOutput(MemoryFileSystem trgMfs, ResultsImpl messages) { MemoryFileSystem srcMfs = new MemoryFileSystem(); ModelWriter modelWriter = new ModelWriter(); List<String> modelFiles = new ArrayList<>(); for (ModelBuilderImpl modelBuilder : modelBuilders) { final ModelWriter.Result result = modelWriter.writeModel( srcMfs, modelBuilder.getPackageModels() ); modelFiles.addAll(result.getModelFiles()); final String[] sources = result.getSources(); if(sources.length != 0) { CompilationResult res = getCompiler().compile(sources, srcMfs, trgMfs, getClassLoader()); <START> ClassLoader byteClassLoader = trgMfs.memoryClassLoader(getClassLoader()); <END> for (PackageModel pm : modelBuilder.getPackageModels()) { pm.validateConsequence(byteClassLoader, messages); } Stream.of(res.getErrors()).collect(groupingBy(CompilationProblem::getFileName)) .forEach( (name, errors) -> { errors.forEach( messages::addMessage ); File srcFile = srcMfs.getFile( name ); if ( srcFile instanceof MemoryFile ) { String src = new String ( srcMfs.getFileContents( ( MemoryFile ) srcFile ) ); messages.addMessage( Message.Level.ERROR, name, "Java source of " + name + " in error:\n" + src); } } ); for (CompilationProblem problem : res.getWarnings()) { messages.addMessage(problem); } } } modelWriter.writeModelFile(modelFiles, trgMfs); }</code><technical_language>If understanding correctly creating this ClassLoader of fact validate not. Generating ClassLoader populating generated classes is a time consuming task done strictly necessary, In biggest part of cases I expect (hope) mvel consequences this ClassLoader is useless</technical_language>

Target:
public void writeProjectOutput(MemoryFileSystem trgMfs, ResultsImpl messages) { MemoryFileSystem srcMfs = new MemoryFileSystem(); ModelWriter modelWriter = new ModelWriter(); List<String> modelFiles = new ArrayList<>(); for (ModelBuilderImpl modelBuilder : modelBuilders) { final ModelWriter.Result result = modelWriter.writeModel( srcMfs, modelBuilder.getPackageModels() ); modelFiles.addAll(result.getModelFiles()); final String[] sources = result.getSources(); if(sources.length != 0) { CompilationResult res = getCompiler().compile(sources, srcMfs, trgMfs, getClassLoader()); for (PackageModel pm : modelBuilder.getPackageModels()) { pm.validateConsequence(getClassLoader(), trgMfs, messages); } Stream.of(res.getErrors()).collect(groupingBy(CompilationProblem::getFileName)) .forEach( (name, errors) -> { errors.forEach( messages::addMessage ); File srcFile = srcMfs.getFile( name ); if ( srcFile instanceof MemoryFile ) { String src = new String ( srcMfs.getFileContents( ( MemoryFile ) srcFile ) ); messages.addMessage( Message.Level.ERROR, name, "Java source of " + name + " in error:\n" + src); } } ); for (CompilationProblem problem : res.getWarnings()) { messages.addMessage(problem); } } } modelWriter.writeModelFile(modelFiles, trgMfs); }
Source:
<code>private PartitionInfo makePartitionInfo(String name, int id) { PartitionInfo pi = <START> mock(PartitionInfo.class); <END> when(pi.partition()).thenReturn(id); when(pi.topic()).thenReturn(name); return pi; }</code><technical_language>Do need mock PartitionInfo? a simple DTO..</technical_language>

Target:
private PartitionInfo makePartitionInfo(String name, int id) { return new PartitionInfo(name, id, null, null, null); }
Source:
<code>public void testDecompression() throws OrcCorruptionException { byte[] sourceBytes = generateRandomBytes(); byte[] compressedBytes = new byte[1024 * 1024]; int size = compressor.compress(sourceBytes, 0, sourceBytes.length, compressedBytes, 0, compressedBytes.length); <START> int outputSize = decompressor.decompress(compressedBytes, 0, size, <END> new OrcDecompressor.OutputBuffer() { @Override public byte[] initialize(int size) { return new byte[size]; } @Override public byte[] grow(int size) { throw new RuntimeException(); } }); Assert.assertEquals(outputSize, sourceBytes.length); }</code><technical_language>param line</technical_language>

Target:
public void testDecompression() throws OrcCorruptionException { byte[] sourceBytes = generateRandomBytes(); byte[] compressedBytes = new byte[1024 * 1024]; int size = compressor.compress(sourceBytes, 0, sourceBytes.length, compressedBytes, 0, compressedBytes.length); byte[] output = new byte[sourceBytes.length]; int outputSize = decompressor.decompress( compressedBytes, 0, size, new OrcDecompressor.OutputBuffer() { @Override public byte[] initialize(int size) { return output; } @Override public byte[] grow(int size) { throw new RuntimeException(); } }); Assert.assertEquals(outputSize, sourceBytes.length); Assert.assertEquals(output, sourceBytes); }
Source:
<code>public Iterator<SpreadsheetRecord> iterator() { <START> final Iterator<CSVRecord> iterator = myParser.iterator(); <END> return new Iterator<SpreadsheetRecord>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public SpreadsheetRecord next() { return new CsvRecordImpl(iterator.next()); } @Override public void remove() { throw new UnsupportedOperationException(); } }; }</code><technical_language>Iterators.transform Guava</technical_language>

Target:
public Iterator<SpreadsheetRecord> iterator() { return Iterators.transform(myParser.iterator(), CsvRecordImpl::new); }
Source:
<code>public <T extends NodeProperty> T getNodeProperty(Class<T> clazz) { <START> for (NodeProperty p: getNodeProperties()) { <END> if (clazz.isInstance(p)) return clazz.cast(p); } return null; }</code><technical_language>This cycle confusing brackets. please add brackets if properly tabulate bracket</technical_language>

Target:
public <T extends NodeProperty> T getNodeProperty(Class<T> clazz) { for (NodeProperty p: getNodeProperties()) { if (clazz.isInstance(p)) { return clazz.cast(p); } } return null; }
Source:
<code>public ResponseEntity<String> browse() { try { Map<String,SortedSet<String>> storages = new HashMap<>(); storages.put("storages", new TreeSet<String>(configurationManager.getConfiguration() .getStorages().keySet())); <START> return ResponseEntity.ok(new ObjectMapper().writeValueAsString(storages)); <END> } catch (Exception e) { logger.error(e.getMessage(), e); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body(String.format("{ 'error': '%s' }", e.getMessage())); } }</code><technical_language>new ObjectMapper() Please DI custom object mapper instead of creating new one: @Inject private ObjectMapper objectMapper;</technical_language>

Target:
public ResponseEntity<String> browse() { try { Map<String,SortedSet<String>> storages = new HashMap<>(); storages.put("storages", new TreeSet<String>(configurationManager.getConfiguration() .getStorages() .keySet())); return ResponseEntity.ok(objectMapper.writer().writeValueAsString(storages)); } catch (Exception e) { logger.error(e.getMessage(), e); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body(String.format("{ 'error': '%s' }", e.getMessage())); } }
Source:
<code>private String removeBearerPrefix(String rawHeader) { if (StringUtils.isEmpty(rawHeader)) return null; <START> return rawHeader.replaceFirst("bearer ", ""); <END> }</code><technical_language>This is assuming cased header value, is true a safe assumption in future</technical_language>

Target:
String removeBearerPrefix(String rawHeader) { if (StringUtils.isEmpty(rawHeader)) { warn().log("cannot remove Bearer prefix from null value"); return null; } String token = rawHeader.replaceFirst(BEARER_PREFIX_UC, "").trim(); info().log("bearer prefix removed from service auth header"); return token; }
Source:
<code>private void commonTestPart(final URL url, final String possibleCausingIssues) throws Exception { final String responseBody = HttpRequest.get(url + "index.jsp", 10, TimeUnit.SECONDS); Assert.assertThat("Unexpected EL evaluation for ${Boolean.TRUE}; " + possibleCausingIssues, responseBody, CoreMatchers.containsString("Boolean.TRUE: --- " + Boolean.TRUE + " ---")); Assert.assertThat("Unexpected EL evaluation for ${Integer.MAX_VALUE}; " + possibleCausingIssues, responseBody, CoreMatchers.containsString("Integer.MAX_VALUE: --- " + Integer.MAX_VALUE + " ---")); Assert.assertThat("Unexpected EL evaluation for ${DummyConstants.FOO}; " + possibleCausingIssues, responseBody, CoreMatchers.containsString("DummyConstants.FOO: --- " + DummyConstants.FOO + " ---")); Assert.assertThat("Unexpected EL evaluation for ${DummyEnum.VALUE}; " + possibleCausingIssues, responseBody, <START> CoreMatchers.containsString("DummyEnum.VALUE: --- " + DummyEnum.VALUE + " ---")); <END> }</code><technical_language>Is a reason for this change? addition of CoreMatchers instead of String.contains()</technical_language>

Target:
private void commonTestPart(final URL url, final String possibleCausingIssues) throws Exception { final String responseBody = HttpRequest.get(url + "index.jsp", 10, TimeUnit.SECONDS); Assert.assertTrue("Unexpected EL evaluation for ${Boolean.TRUE}; " + possibleCausingIssues, responseBody.contains("Boolean.TRUE: --- " + Boolean.TRUE + " ---")); Assert.assertTrue("Unexpected EL evaluation for ${Integer.MAX_VALUE}; " + possibleCausingIssues, responseBody.contains("Integer.MAX_VALUE: --- " + Integer.MAX_VALUE + " ---")); Assert.assertTrue("Unexpected EL evaluation for ${DummyConstants.FOO}; " + possibleCausingIssues, responseBody.contains("DummyConstants.FOO: --- " + DummyConstants.FOO + " ---")); Assert.assertTrue("Unexpected EL evaluation for ${DummyEnum.VALUE}; " + possibleCausingIssues, responseBody.contains("DummyEnum.VALUE: --- " + DummyEnum.VALUE + " ---")); }
Source:
<code>private void processSnapshotTransferEndMarker(LogReplicationEntry message) { snapshotWriter.snapshotTransferDone(message); <START> completeSnapshotApply(message); <END> }</code><technical_language>is this complete startSnapshotApply? semantic of method changed, revisit messages method</technical_language>

Target:
private void processSnapshotTransferEndMarker(LogReplicationEntry message) { snapshotWriter.setSnapshotTransferDoneAndStartApply(message); completeSnapshotApply(message); }
Source:
<code>private void sendMergedEmail(final ReplaceResult result) { if (result != null && result.mergedIntoRef != null) { workQueue.getDefaultQueue() .submit(requestScopePropagator.wrap(new Runnable() { @Override public void run() { try { final MergedSender cm = mergedSenderFactory.create(result.change); cm.setFrom(currentUser.getAccountId()); cm.setPatchSet(result.patchSet, result.info); cm.send(); } catch (EmailException e) { final PatchSet.Id psi = result.patchSet.getId(); log.error("Cannot send email for submitted patch set " + psi, e); } } @Override public String toString() { <START> return "send email for submitted patch set"; <END> } })); try { hooks.doChangeMergedHook(result.change, currentUser.getAccount(), result.patchSet, db); } catch (OrmException err) { log.error("Cannot open change: " + result.change.getChangeId(), err); } } }</code><technical_language>"send-email merged"</technical_language>

Target:
private void sendMergedEmail(final ReplaceResult result) { if (result != null && result.mergedIntoRef != null) { workQueue.getDefaultQueue() .submit(requestScopePropagator.wrap(new Runnable() { @Override public void run() { try { final MergedSender cm = mergedSenderFactory.create(result.change); cm.setFrom(currentUser.getAccountId()); cm.setPatchSet(result.patchSet, result.info); cm.send(); } catch (EmailException e) { final PatchSet.Id psi = result.patchSet.getId(); log.error("Cannot send email for submitted patch set " + psi, e); } } @Override public String toString() { return "send-email merged"; } })); try { hooks.doChangeMergedHook(result.change, currentUser.getAccount(), result.patchSet, db); } catch (OrmException err) { log.error("Cannot open change: " + result.change.getChangeId(), err); } } }
Source:
<code>public boolean equals(final Object o) { if (!super.equals(o)) { return false; } <START> final ArrayOfDoublesSketchToEstimateAndBoundsPostAggregator that = (ArrayOfDoublesSketchToEstimateAndBoundsPostAggregator) o; <END> if (numStdDevs != that.numStdDevs) { return false; } return true; }</code><technical_language>Add instanceof check</technical_language>

Target:
public boolean equals(final Object o) { if (!super.equals(o)) { return false; } if (!(o instanceof ArrayOfDoublesSketchToEstimateAndBoundsPostAggregator)) { return false; } final ArrayOfDoublesSketchToEstimateAndBoundsPostAggregator that = (ArrayOfDoublesSketchToEstimateAndBoundsPostAggregator) o; if (numStdDevs != that.numStdDevs) { return false; } return true; }
Source:
<code>private void stageLicenseFile(Configuration config) { String path = null; try { path = config.m_voltdbRoot.getCanonicalPath(); } catch (IOException e) { VoltDB.crashLocalVoltDB("Unable to get voltdbroot path", false, e); } File destF = new VoltFile(path, Constants.LICENSE_FILE_NAME); if (config.m_forceVoltdbCreate && destF.exists()) { destF.delete(); } if (config.m_pathToLicense != null) { File licenseF = new VoltFile(config.m_pathToLicense); try { Files.copy(licenseF, destF); <START> hostLog.info("Archive license file to VoltDB root directory: " + destF.getAbsolutePath()); <END> } catch (IOException e) { VoltDB.crashLocalVoltDB("Unable to stage license file to " + path, false, e); } } }</code><technical_language>Nit: "Archive license file..." is imperative, telling do something. "License file archived to..." is a report done. "Archived" a odd me, putting a copy use. Do "archive" elsewhere? If not, I suggest "copied". "staged", in error message</technical_language>

Target:
private void stageLicenseFile(Configuration config) { if (!MiscUtils.isPro()) { return; } String path = null; try { path = config.m_voltdbRoot.getCanonicalPath(); } catch (IOException e) { VoltDB.crashLocalVoltDB("Unable to get voltdbroot path", false, e); } File destF = new VoltFile(path, Constants.LICENSE_FILE_NAME); if (config.m_forceVoltdbCreate && destF.exists()) { destF.delete(); } if (config.m_pathToLicense != null) { File licenseF = new File(config.m_pathToLicense); try { Files.copy(licenseF, destF); hostLog.info("License file is copied to VoltDB root directory: " + destF.getAbsolutePath()); } catch (IOException e) { VoltDB.crashLocalVoltDB("Unable to copy license file to " + path, false, e); } } }
Source:
<code>public LoginResponse login(@Valid @RequestBody LoginRequest login, HttpServletRequest request) { if (login == null) { throw new MissingValueException("login", "request"); } if (isUser2fa()) { <START> throw new LoginMethodDisabledException(); <END> } return runAsSystem(() -> { UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(login.getUsername(), login.getPassword()); authToken.setDetails(new WebAuthenticationDetails(request)); Authentication authentication = authenticationManager.authenticate(authToken); if (!authentication.isAuthenticated()) { throw new UnknownUsernamePasswordException(); } User user = dataService.findOne(USER, new QueryImpl<User>().eq(UserMetaData.USERNAME, authentication.getName()), User.class); if (user.isChangePassword()) { throw new ChangePasswordException(); } SecurityContextHolder.getContext().setAuthentication(authentication); String token = tokenService.generateAndStoreToken(authentication.getName(), "REST API login"); return new LoginResponse(token, user.getUsername(), user.getFirstName(), user.getLastName()); }); }</code><technical_language>Exception name match this specific case + message</technical_language>

Target:
public LoginResponse login(@Valid @RequestBody LoginRequest login, HttpServletRequest request) { if (isUser2fa()) { throw new LoginDisabledTwoFactorAuthenticationException(); } return runAsSystem(() -> { UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(login.getUsername(), login.getPassword()); authToken.setDetails(new WebAuthenticationDetails(request)); Authentication authentication = authenticationManager.authenticate(authToken); if (!authentication.isAuthenticated()) { throw new UnknownUsernamePasswordException(); } User user = dataService.findOne(USER, new QueryImpl<User>().eq(UserMetaData.USERNAME, authentication.getName()), User.class); if (user.isChangePassword()) { throw new ChangePasswordException(); } SecurityContextHolder.getContext().setAuthentication(authentication); String token = tokenService.generateAndStoreToken(authentication.getName(), "REST API login"); return new LoginResponse(token, user.getUsername(), user.getFirstName(), user.getLastName()); }); }
Source:
<code>public void starOrganization(@ApiParam(hidden = true) @Auth User user, @ApiParam(value = "Organization to star.", required = true) @PathParam("organizationId") Long organizationId, @ApiParam(value = "StarRequest to star an organization for a user", required = true) StarRequest request) { Organization organization = organizationDAO.findApprovedById(organizationId); <START> boolean isOrgApproved = isOrganizationApproved(organizationId); <END> throwErrorIfOrganizationNotFound(isOrgApproved); Set<User> starredUsers = organization.getStarredUsers(); if (!starredUsers.contains(user)) { organization.addStarredUser(user); } else { throw new CustomWebApplicationException( "You cannot star the organization " + organization.getName() + " because you have already starred it.", HttpStatus.SC_BAD_REQUEST); } }</code><technical_language>organization line 309. isOrganizationApproved is potentially another DB call, is expensive (potentially Hibernate cache it). get rid of this line do throwErrorIfOrganizationNotFound(organization != null) noticed, more common pattern is check..., consider renaming throwErrorIfOrganizationNotFound checkOrganization, crucial</technical_language>

Target:
public void starOrganization(@ApiParam(hidden = true) @Auth User user, @ApiParam(value = "Organization to star.", required = true) @PathParam("organizationId") Long organizationId, @ApiParam(value = "StarRequest to star an organization for a user", required = true) StarRequest request) { Organization organization = organizationDAO.findApprovedById(organizationId); checkOrganization(organization); Set<User> starredUsers = organization.getStarredUsers(); if (!starredUsers.contains(user)) { organization.addStarredUser(user); } else { throw new CustomWebApplicationException( "You cannot star the organization " + organization.getName() + " because you have already starred it.", HttpStatus.SC_BAD_REQUEST); } }
Source:
<code>public boolean equals(Object o) { if (this == o) { return true; } <START> if (o instanceof AbstractTreeNode) { <END> AbstractTreeNode other = (AbstractTreeNode)o; return Objects.equals(parent, other.parent) && Objects.equals(getId(), other.getId()); } return false; }</code><technical_language>I re-work this code. Need move code if block</technical_language>

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof AbstractTreeNode)) { return false; } AbstractTreeNode other = (AbstractTreeNode)o; return Objects.equals(parent, other.parent) && Objects.equals(getId(), other.getId()); }
Source:
<code>public void shutdown() { if (mergeExecutor != null) { <START> mergeExecutor.shutdownNow(); <END> } }</code><technical_language>shutting Executor, explicitly set null is more friendly GC</technical_language>

Target:
public void shutdown() { if (mergeExecutor != null) { mergeExecutor.shutdownNow(); mergeExecutor = null; } }
Source:
<code>public Map<String, String> importFrom(@Context UriInfo uriInfo, MultipartFormDataInput input) throws IOException { this.auth.requireManage(); Map<String, List<InputPart>> formDataMap = input.getFormDataMap(); String providerId = formDataMap.get("providerId").get(0).getBodyAsString(); InputPart file = formDataMap.get("file").get(0); InputStream inputStream = file.getBody(InputStream.class, null); IdentityProviderFactory providerFactory = getProviderFactorytById(providerId); Map<String, String> config = providerFactory.parseConfig(inputStream); <START> adminEvent.realm(realm).operation(OperationType.ACTION).resourcePath(providerFactory, uriInfo.getPath()).representation(config).success(); <END> return config; }</code><technical_language>here. This is a CREATE. ACTION is creating, updating deleting a resource. For example push before, send user password reset</technical_language>

Target:
public Map<String, String> importFrom(@Context UriInfo uriInfo, MultipartFormDataInput input) throws IOException { this.auth.requireManage(); Map<String, List<InputPart>> formDataMap = input.getFormDataMap(); String providerId = formDataMap.get("providerId").get(0).getBodyAsString(); InputPart file = formDataMap.get("file").get(0); InputStream inputStream = file.getBody(InputStream.class, null); IdentityProviderFactory providerFactory = getProviderFactorytById(providerId); Map<String, String> config = providerFactory.parseConfig(inputStream); adminEvent.operation(OperationType.CREATE).resourcePath(providerFactory, uriInfo.getPath()).representation(config).success(); return config; }
Source:
<code>public CloudStack(Collection<Group> groups, Network network, Image image, Map<String, String> parameters, Tags tags, String template, InstanceAuthentication instanceAuthentication, String loginUserName, String publicKey, SpiFileSystem fileSystem) { this.groups = ImmutableList.copyOf(groups); this.network = network; this.image = image; this.parameters = ImmutableMap.copyOf(parameters); <START> this.tags = tags; <END> this.template = template; this.instanceAuthentication = instanceAuthentication; this.loginUserName = loginUserName; this.publicKey = publicKey; this.fileSystem = Optional.ofNullable(fileSystem); }</code><technical_language>copy of tags copy constructor</technical_language>

Target:
public CloudStack(Collection<Group> groups, Network network, Image image, Map<String, String> parameters, Tags tags, String template, InstanceAuthentication instanceAuthentication, String loginUserName, String publicKey, SpiFileSystem fileSystem) { this.groups = ImmutableList.copyOf(groups); this.network = network; this.image = image; this.parameters = ImmutableMap.copyOf(parameters); this.tags = new Tags(tags); this.template = template; this.instanceAuthentication = instanceAuthentication; this.loginUserName = loginUserName; this.publicKey = publicKey; this.fileSystem = Optional.ofNullable(fileSystem); }
Source:
<code><START> public synchronized void flush(String source) { <END> pendingFutures.clear(); }</code><technical_language>I suggest call super.flush() here</technical_language>

Target:
public synchronized void flush(String source) { super.flush(source); }
Source:
<code>public VMListReturnForXmlRpc getExternalVmList(String uri, String username, String password, List<String> vmsNames) { <START> JsonRpcRequest request; <END> if(vmsNames == null) { request = new RequestBuilder("Host.getExternalVMs") .withParameter("uri", uri) .withParameter("username", username) .withParameter("password", password) .build(); } else { request = new RequestBuilder("Host.getExternalVMs") .withParameter("uri", uri) .withParameter("username", username) .withParameter("password", password) .withParameter("vm_names", vmsNames) .build(); } Map<String, Object> response = new FutureMap(this.client, request).withResponseKey("vmList") .withResponseType(Object[].class); return new VMListReturnForXmlRpc(response); }</code><technical_language>this simplified like: RequestBuilder requestBuilder = new RequestBuilder("Host.getExternalVMs") .withParameter("uri", uri) .withParameter("username", username) .withParameter("password", password); if(vmsNames != null) { requestBuilder.withParameter("vm_names", vmsNames); } JsonRpcRequest request = requestBuilder.build();</technical_language>

Target:
public VMListReturnForXmlRpc getExternalVmList(String uri, String username, String password, List<String> vmsNames) { RequestBuilder requestBuilder = new RequestBuilder("Host.getExternalVMs") .withParameter("uri", uri) .withParameter("username", username) .withParameter("password", password) .withOptionalParameterAsList("vm_names", vmsNames); JsonRpcRequest request = requestBuilder.build(); Map<String, Object> response = new FutureMap(this.client, request).withResponseKey("vmList") .withResponseType(Object[].class); return new VMListReturnForXmlRpc(response); }
Source:
<code>public Cloud(String url) throws MalformedURLException { URL u = new URL(url); this.scheme = u.getProtocol(); this.host = u.getHost(); <START> this.port = u.getPort() == -1 ? u.getDefaultPort() : u.getPort(); <END> String path = u.getPath(); this.pathPrefix = path.endsWith("/") ? path.substring(0, path.length() - 1) : path; }</code><technical_language>change "== -1" "< 0"</technical_language>

Target:
public Cloud(String url) throws MalformedURLException { URL u = new URL(url); this.scheme = u.getProtocol(); this.host = u.getHost(); this.port = u.getPort() < 0 ? u.getDefaultPort() : u.getPort(); String path = u.getPath(); this.pathPrefix = path.endsWith("/") ? path.substring(0, path.length() - 1) : path; }
Source:
<code><START> private List<ApplicabilityToken> getStoredApplicabilities() { <END> List<ApplicabilityToken> appls = new LinkedList<>(); appls.addAll(AtsClientService.getApplicabilityEndpoint( AtsClientService.get().getAtsBranch()).getApplicabilityReferenceTokens(workItem.getStoreObject())); return appls; }</code><technical_language>getApplicabilityReferenceTokens returns a list? need add another list</technical_language>

Target:
private List<ApplicabilityToken> getStoredApplicabilities() { return AtsClientService.getApplicabilityEndpoint( AtsClientService.get().getAtsBranch()).getApplicabilityReferenceTokens(workItem.getStoreObject()); }
Source:
<code>private static String formatLocalDateTime(LocalDateTime localDateTime, String pattern) { if (localDateTime == null) { return ""; } String processedPattern; if (localDateTime.getHour() == 12 && localDateTime.getMinute() == 0) { processedPattern = pattern.replace("a", "'NOON'"); } else { <START> processedPattern = pattern; <END> } DateTimeFormatter formatter = DateTimeFormatter.ofPattern(processedPattern); return localDateTime.format(formatter); }</code><technical_language>eliminate this else branch initializing processedPattern pattern</technical_language>

Target:
private static String formatLocalDateTime(LocalDateTime localDateTime, String pattern) { if (localDateTime == null) { return ""; } String processedPattern = pattern; if (localDateTime.getHour() == 12 && localDateTime.getMinute() == 0) { processedPattern = pattern.replace("a", "'NOON'"); } DateTimeFormatter formatter = DateTimeFormatter.ofPattern(processedPattern); return localDateTime.format(formatter); }