auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private int readHighTagNumber() throws BerDataValueFormatException { int b; int result = 0; do { if (!mBuf.hasRemaining()) { throw new BerDataValueFormatException("Truncated tag number"); } b = mBuf.get(); result <<= 7; result += b & 0x7f; <START> if (result < 0) { <END> throw new BerDataValueFormatException("Tag number too large"); } } while ((b & 0x80) != 0); return result; }</code><technical_language>< 0 a great overflow check, more explicit</technical_language>

Target:
private int readHighTagNumber() throws BerDataValueFormatException { int b; int result = 0; do { if (!mBuf.hasRemaining()) { throw new BerDataValueFormatException("Truncated tag number"); } b = mBuf.get(); if (result > Integer.MAX_VALUE >>> 7) { throw new BerDataValueFormatException("Tag number too large"); } result <<= 7; result |= b & 0x7f; } while ((b & 0x80) != 0); return result; }
Source:
<code>protected void initialize() { super.initialize(); useStagingView.setPropertyChangeListener(new IPropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent event) { if (FieldEditor.VALUE.equals(event.getProperty())) { autoStage.setEnabled( ((Boolean) event.getNewValue()).booleanValue(), <START> getFieldEditorParent()); <END> } } }); }</code><technical_language>this generalGroup now</technical_language>

Target:
protected void initialize() { super.initialize(); useStagingView.setPropertyChangeListener(new IPropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent event) { if (FieldEditor.VALUE.equals(event.getProperty())) { autoStage.setEnabled( ((Boolean) event.getNewValue()).booleanValue(), generalGroup); } } }); }
Source:
<code>private boolean shouldDump(Path previousDumpPath) throws IOException { if (previousDumpPath == null) { return true; } else { FileSystem fs = previousDumpPath.getFileSystem(conf); <START> if (fs.exists(previousDumpPath)) { <END> FileStatus[] latestUpdateStatuses = fs.listStatus(previousDumpPath); for (FileStatus status : latestUpdateStatuses) { if (status.getPath().getName().equalsIgnoreCase(ReplUtils.LOAD_ACKNOWLEDGEMENT)) { return true; } } } } return false; }</code><technical_language>return fs.exists(new Path(previousDumpPath, ReplUtils.LOAD_ACKNOWLEDGEMENT));</technical_language>

Target:
private boolean shouldDump(Path previousDumpPath) throws IOException { if (previousDumpPath == null) { return true; } else { FileSystem fs = previousDumpPath.getFileSystem(conf); return fs.exists(new Path(previousDumpPath, ReplUtils.LOAD_ACKNOWLEDGEMENT)); } }
Source:
<code>public void traverseImpl(Collection<? extends T> roots, TraverserVisitor<? super T> visitor) { assertNotNull(roots); assertNotNull(visitor); DefaultTraverserContext<T> rootContext = newRootContext(rootVars); <START> ForkJoinPool.commonPool().invoke(new CountedCompleter<Void>() { <END> @Override public void compute() { setPendingCount(roots.size()); for (T root : roots) { DefaultTraverserContext context = newContext(root, rootContext, null); EnterAction enterAction = new EnterAction(this, context, visitor); enterAction.fork(); } tryComplete(); } }); }</code><technical_language>I ForkJoinPool a parameter. default commonPool() is this is making a threading decision behalf of consuming code. Lets allow people it. threads in a pool is application concern, a library concern</technical_language>

Target:
public void traverseImpl(Collection<? extends T> roots, TraverserVisitor<? super T> visitor) { assertNotNull(roots); assertNotNull(visitor); DefaultTraverserContext<T> rootContext = newRootContext(rootVars); forkJoinPool.invoke(new CountedCompleter<Void>() { @Override public void compute() { setPendingCount(roots.size()); for (T root : roots) { DefaultTraverserContext context = newContext(root, rootContext, null); EnterAction enterAction = new EnterAction(this, context, visitor); enterAction.fork(); } tryComplete(); } }); }
Source:
<code>public String processElement(ParserContext context, Element element) { <START> String message = $(element).text(); <END> if (StringUtils.isBlank(message)) { throw new WindupException("Error, 'tag' element must not be blank"); } return message; }</code><technical_language>In this case, please consider if this applied in other *Handler classes, i avoid $ build objects for XML use, instead, String message = element.getTextContent(); get value</technical_language>

Target:
public String processElement(ParserContext context, Element element) { String content = element.getTextContent(); if (StringUtils.isBlank(content)) { throw new WindupException("Error, 'tag' element must not be blank"); } return content; }
Source:
<code>public void run() { final Thread workerThread = Thread.currentThread(); final String oldName = workerThread.getName(); try { workerThread.setName("IOHub#" + _id + ": Worker[channel:" + key.channel() + "] / " + oldName); listener.ready((ops & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT, (ops & SelectionKey.OP_CONNECT) == SelectionKey.OP_CONNECT, (ops & SelectionKey.OP_READ) == SelectionKey.OP_READ, (ops & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE); } catch (Throwable e) { if (LOGGER.isLoggable(Level.SEVERE)) { LogRecord record = new LogRecord(Level.SEVERE, "[{0}] Listener {1} propagated an uncaught {2}"); record.setThrown(e); record.setParameters(new Object[]{workerThread.getName(), listener, e.getClass().getSimpleName()}); LOGGER.log(record); <START> } <END> } finally { workerThread.setName(oldName); } }</code><technical_language>rethrow. suppresses <code>Error</code>s, supposed fatal</technical_language>

Target:
public void run() { final Thread workerThread = Thread.currentThread(); final String oldName = workerThread.getName(); try { workerThread.setName("IOHub#" + _id + ": Worker[channel:" + key.channel() + "] / " + oldName); listener.ready((ops & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT, (ops & SelectionKey.OP_CONNECT) == SelectionKey.OP_CONNECT, (ops & SelectionKey.OP_READ) == SelectionKey.OP_READ, (ops & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE); } catch (Throwable e) { if (LOGGER.isLoggable(Level.SEVERE)) { LogRecord record = new LogRecord(Level.SEVERE, "[{0}] Listener {1} propagated an uncaught {2}"); record.setThrown(e); record.setParameters(new Object[]{workerThread.getName(), listener, e.getClass().getSimpleName()}); LOGGER.log(record); } if (e instanceof Error) { throw (Error)e; } } finally { workerThread.setName(oldName); } }
Source:
<code>private boolean isQuotableParam(String name){ boolean isQuotableParameter = false; SipContext context = SipApplicationSessionCreationThreadLocal.lookupContext(); if (context != null){ <START> Object object = context.getServletContext().getAttribute("org.restcomm.servlets.sip.QUOTABLE_PARAMETER"); <END> if (object != null){ String quotableParameters = object.toString(); if (!quotableParameters.isEmpty()){ String[] parameters = quotableParameters.split(","); for (int i = 0; i < parameters.length; i++){ if (parameters[i].trim().equalsIgnoreCase(name)){ isQuotableParameter = true; break; } } } } } return isQuotableParameter; }</code><technical_language>build a default for this attribute, including attributes SIP RFCs? set defalt SipStandardContext.prepareServletContext I noticed read initParam prepareServletContext, set this attribute. do String parsing there?, add a List<String> instead. this prevent parsing everytime a setParameter is invoked service</technical_language>

Target:
private boolean isQuotableParam(String name){ boolean isQuotableParameter = false; SipContext context = SipApplicationSessionCreationThreadLocal.lookupContext(); if (context != null){ List<String> params = (List<String>)context.getServletContext().getAttribute("org.restcomm.servlets.sip.QUOTABLE_PARAMETER"); for (String param : params){ if (param.equalsIgnoreCase(name)){ isQuotableParameter = true; break; } } } return isQuotableParameter; }
Source:
<code><START> protected void onDestroy() { <END> super.onDestroy(); Toaster.iToast(this, "Destroying MusicLibrary Service"); Intent intent = new Intent(this, MusicLibraryService.class); stopService(intent); }</code><technical_language>Hardcoded toast text :baby:</technical_language>

Target:
protected void onDestroy() { super.onDestroy(); Intent intent = new Intent(this, MusicLibraryService.class); stopService(intent); }
Source:
<code>public MongoDbMetadataStore(MongoTemplate template, String collectionName) { this.template = template; <START> this.collectionName = (StringUtils.hasText(collectionName)) ? collectionName <END> : DEFAULT_COLLECTION_NAME; }</code><technical_language>vise versa: ctor collectionName this DEFAULT_COLLECTION_NAME. Assert.hasText(collectionName); Assert.notNull(template); error message warn end-user wrong actions</technical_language>

Target:
public MongoDbMetadataStore(MongoTemplate template, String collectionName) { Assert.notNull(template, "'template' must not be null."); Assert.hasText(collectionName, "'collectionName' must not be empty."); this.template = template; this.collectionName = collectionName; operations = template.scriptOps(); operations.register(new NamedMongoScript(PUT_IF_ABSENT, buildQuery())); }
Source:
<code>public void testConstraintOnPrivateGetterReturnsConstraintViolation() { Validator validator = getValidator(); <START> LocalDate[][] testData = { { LocalDate.MAX, LocalDate.MIN }, { LocalDate.now( ZoneId.systemDefault() ), null }, { null, null } }; <END> for ( LocalDate[] dates : testData ) { Set<ConstraintViolation<Project>> constraintViolations = validator.validate( new Project( dates[0], dates[1] ) ); assertNumberOfViolations( constraintViolations, 1 ); assertCorrectConstraintTypes( constraintViolations, AssertTrue.class ); assertCorrectPropertyPaths( constraintViolations, "startBeforeEnd" ); } }</code><technical_language>a bit sceptic this type of changes. @gunnarmorling this? worried occurrences more frustrating write new tests</technical_language>

Target:
public void testConstraintOnPrivateGetterReturnsConstraintViolation() { Validator validator = getValidator(); LocalDate[][] testData = { { LocalDate.MAX, LocalDate.MIN }, { LocalDate.now(), null }, { null, null } }; for ( LocalDate[] dates : testData ) { Set<ConstraintViolation<Project>> constraintViolations = validator.validate( new Project( dates[0], dates[1] ) ); assertNumberOfViolations( constraintViolations, 1 ); assertCorrectConstraintTypes( constraintViolations, AssertTrue.class ); assertCorrectPropertyPaths( constraintViolations, "startBeforeEnd" ); } }
Source:
<code>private void updateState() { Optional<EclipseProjectBinding> projectBinding = getProjectConfig().getProjectBinding(); if (projectBinding.isPresent()) { boundDetails <START> .setText("Bound to the project '" + projectBinding.get().projectKey() + "' on server '" + serverName(projectBinding.get().connectionId()) + "'"); <END> bindLink.setText("<a>Update project binding</a>"); } else { bindLink.setText("<a>Bind this Eclipse project to a SonarQube project</a>"); boundDetails.setText(""); } if (projectBinding.isPresent() && !SonarLintCorePlugin.getServersManager().forProject(getProject()).isPresent()) { addServerLink.setText("<a>Connect to SonarQube server '" + projectBinding.get().connectionId() + "'</a>"); addServerLink.setVisible(true); } else { addServerLink.setVisible(false); } container.layout(true, true); }</code><technical_language>suggestion .setText("Bound project '" + projectBinding.get().projectKey() + "' connection '" + serverName(projectBinding.get().connectionId()) + "'");</technical_language>

Target:
private void updateState() { Optional<EclipseProjectBinding> projectBinding = getProjectConfig().getProjectBinding(); if (projectBinding.isPresent()) { boundDetails .setText("Bound to the project '" + projectBinding.get().projectKey() + "' on connection '" + serverName(projectBinding.get().connectionId()) + "'"); bindLink.setText("<a>Update project binding</a>"); } else { bindLink.setText("<a>Bind this Eclipse project to SonarQube/SonarCloud...</a>"); boundDetails.setText(""); } if (projectBinding.isPresent() && !SonarLintCorePlugin.getServersManager().resolveBinding(getProject()).isPresent()) { addServerLink.setText("<a>Re-create SonarQube/SonarCloud connection '" + projectBinding.get().connectionId() + "'</a>"); addServerLink.setVisible(true); } else { addServerLink.setVisible(false); } container.layout(true, true); }
Source:
<code><START> PageFileFooterReader( <END> FSDataInputStream inputStream, long fileSize) throws IOException { requireNonNull(inputStream, "inputStream is null"); if (fileSize >= SIZE_OF_LONG) { inputStream.readFully(fileSize - SIZE_OF_LONG, readBuffer.array()); long footerStart = readBuffer.order(LITTLE_ENDIAN).getLong(0); long footerSize = fileSize - footerStart; stripeOffsets = new long[toIntExact(footerSize / SIZE_OF_LONG)]; for (int i = 0; i < stripeOffsets.length; i++) { inputStream.readFully(footerStart + SIZE_OF_LONG * i, readBuffer.array()); stripeOffsets[i] = readBuffer.order(LITTLE_ENDIAN).getLong(0); } } }</code><technical_language>public</technical_language>

Target:
public PageFileFooterReader( FSDataInputStream inputStream, long fileSize) throws IOException { checkArgument(fileSize >= FOOTER_LENGTH_IN_BYTES, "Malformed PageFile format, footer length is missing."); requireNonNull(inputStream, "inputStream is null"); ImmutableList.Builder<Long> stripeOffsetsBuilder = ImmutableList.builder(); byte[] buffer = new byte[toIntExact(min(fileSize, ESTIMATED_FOOTER_SIZE))]; inputStream.readFully(fileSize - buffer.length, buffer); int footerSize = Slices.wrappedBuffer(buffer, buffer.length - FOOTER_LENGTH_IN_BYTES, FOOTER_LENGTH_IN_BYTES).getInt(0); footerOffset = fileSize - footerSize; if (footerOffset < 0) { throw new IOException("Malformed PageFile format, incorrect footer length."); } else if (footerOffset > 0) { if (footerSize > buffer.length) { buffer = new byte[footerSize]; inputStream.readFully(footerOffset, buffer); } SliceInput sliceInput = Slices.wrappedBuffer(buffer, buffer.length - footerSize, footerSize - FOOTER_LENGTH_IN_BYTES).getInput(); while (sliceInput.isReadable()) { stripeOffsetsBuilder.add(sliceInput.readLong()); } } else { } stripeOffsets = stripeOffsetsBuilder.build(); }
Source:
<code>protected void checkGetPreconditions(TableReference tableRef) { markTableAsInvolvedInThisTransaction(tableRef); if (transactionReadTimeoutMillis != null && System.currentTimeMillis() - timeCreated > transactionReadTimeoutMillis) { throw new TransactionFailedRetriableException("Transaction timed out."); } Preconditions.checkArgument(allowHiddenTableAccess || !AtlasDbConstants.hiddenTables.contains(tableRef)); <START> ensureUncommitted(); <END> }</code><technical_language>This a good behavior change, affect big internal product. Especially serializable transactions in mix, allow reads commit step</technical_language>

Target:
protected void checkGetPreconditions(TableReference tableRef) { markTableAsInvolvedInThisTransaction(tableRef); if (transactionReadTimeoutMillis != null && System.currentTimeMillis() - timeCreated > transactionReadTimeoutMillis) { throw new TransactionFailedRetriableException("Transaction timed out."); } Preconditions.checkArgument(allowHiddenTableAccess || !AtlasDbConstants.hiddenTables.contains(tableRef)); if (!(state.get() == State.UNCOMMITTED || state.get() == State.COMMITTING)) { throw new CommittedTransactionException(); } }
Source:
<code>public static Boolean isNonEmpty(byte bytes) { Boolean cond = bytes != null && bytes.length > 0; <START> assertTrue("bytes are non empty", cond); <END> return cond; }</code><technical_language>1. Please _byte[]_ (no space) 2. Please _org.apache.sshd.common.util.NumberUtils.isEmpty(bytes)_</technical_language>

Target:
public static Boolean isNonEmpty(byte[] bytes) { Boolean cond = !NumberUtils.isEmpty(bytes); assertTrue("bytes are non empty", cond); return cond; }
Source:
<code>public void shouldHtmlEncodeXmlDirectives() { String html = "<html><head></head><body><table>" + <START> "<tr><td>&lt;!==&gt;&lt;!==&gt;Hmailserver service shutdown:</td><td>&lt;!==&gt;&lt;!==&gt;Ok</td></tr>" + <END> "</table></body></html>"; assertEquals("<html><head></head><body><table><tbody>" + "<tr><td>&lt;!==&gt;&lt;!==&gt;Hmailserver service shutdown:</td><td>&lt;!==&gt;&lt;!==&gt;Ok</td></tr>" + "</tbody></table></body></html>", htmlSanitizer.sanitize(html)); }</code><technical_language>input is encoded. wanted test</technical_language>

Target:
public void shouldHtmlEncodeXmlDirectives() { String html = "<html><head></head><body><table>" + "<tr><td><!==><!==>Hmailserver service shutdown:</td><td><!==><!==>Ok</td></tr>" + "</table></body></html>"; String result = htmlSanitizer.sanitize(html); assertEquals("<html><head></head><body><table><tbody>" + "<tr><td>&lt;!==&gt;&lt;!==&gt;Hmailserver service shutdown:</td><td>&lt;!==&gt;&lt;!==&gt;Ok</td></tr>" + "</tbody></table></body></html>", result); }
Source:
<code>public String getBasePositionName() { final Asterism a = _targetEnv.getAsterism(); <START> if (a instanceof GhostAsterism) { <END> if (a instanceof GhostAsterism.DualTarget || ((GhostAsterism)a).base().isDefined()) { return SPCoordinates.Name(); } } return _targetEnv.getPrimaryTargetFromAsterism().getName(); }</code><technical_language>Do need external check? internal check is needed? collapse a single condition</technical_language>

Target:
public String getBasePositionName() { return _targetEnv.getSlewPositionObjectFromAsterism().getName(); }
Source:
<code>public ErrorMessage convert(DBObject source) { Map<String, Object> headers = MongoDbMessageStore.this.converter.normalizeHeaders((Map<String, Object>) source.get("headers")); Object payload = this.deserializingConverter.convert((byte[]) source.get("payload")); ErrorMessage message = new ErrorMessage((Throwable) payload, headers); Map<String, Object> innerMap = (Map<String, Object>) new DirectFieldAccessor(message.getHeaders()).getPropertyValue("headers"); innerMap.put(MessageHeaders.ID, headers.get(MessageHeaders.ID)); <START> innerMap.put(MessageHeaders.TIMESTAMP, headers.get(MessageHeaders.TIMESTAMP)); <END> return message; }</code><technical_language>refactor this common code a method</technical_language>

Target:
public ErrorMessage convert(DBObject source) { @SuppressWarnings("unchecked") Map<String, Object> headers = MongoDbMessageStore.this.converter.normalizeHeaders((Map<String, Object>) source.get("headers")); Object payload = this.deserializingConverter.convert((byte[]) source.get("payload")); ErrorMessage message = new ErrorMessage((Throwable) payload, headers); enhanceHeaders(message.getHeaders(), headers); return message; }
Source:
<code>private void createSortable(AnnotationNode annotation, ClassNode classNode) { List<String> includes = getMemberStringList(annotation, "includes"); List<String> excludes = getMemberStringList(annotation, "excludes"); <START> boolean reversed = getMemberBoolValue(annotation, "reversed"); <END> if (!checkIncludeExcludeUndefinedAware(annotation, excludes, includes, MY_TYPE_NAME)) return; if (!checkPropertyList(classNode, includes, "includes", annotation, MY_TYPE_NAME, false)) return; if (!checkPropertyList(classNode, excludes, "excludes", annotation, MY_TYPE_NAME, false)) return; if (classNode.isInterface()) { addError(MY_TYPE_NAME + " cannot be applied to interface " + classNode.getName(), annotation); } List<PropertyNode> properties = findProperties(annotation, classNode, includes, excludes); implementComparable(classNode); classNode.addMethod(new MethodNode( "compareTo", ACC_PUBLIC, ClassHelper.int_TYPE, params(param(newClass(classNode), OTHER)), ClassNode.EMPTY_ARRAY, createCompareToMethodBody(properties, reversed) )); for (PropertyNode property : properties) { createComparatorFor(classNode, property, reversed); } new VariableScopeVisitor(sourceUnit, true).visitClass(classNode); }</code><technical_language>boolean reversed = memberHasValue(annotation, "reversed", true);</technical_language>

Target:
private void createSortable(AnnotationNode annotation, ClassNode classNode) { List<String> includes = getMemberStringList(annotation, "includes"); List<String> excludes = getMemberStringList(annotation, "excludes"); boolean reversed = memberHasValue(annotation, "reversed", true); if (!checkIncludeExcludeUndefinedAware(annotation, excludes, includes, MY_TYPE_NAME)) return; if (!checkPropertyList(classNode, includes, "includes", annotation, MY_TYPE_NAME, false)) return; if (!checkPropertyList(classNode, excludes, "excludes", annotation, MY_TYPE_NAME, false)) return; if (classNode.isInterface()) { addError(MY_TYPE_NAME + " cannot be applied to interface " + classNode.getName(), annotation); } List<PropertyNode> properties = findProperties(annotation, classNode, includes, excludes); implementComparable(classNode); classNode.addMethod(new MethodNode( "compareTo", ACC_PUBLIC, ClassHelper.int_TYPE, params(param(newClass(classNode), OTHER)), ClassNode.EMPTY_ARRAY, createCompareToMethodBody(properties, reversed) )); for (PropertyNode property : properties) { createComparatorFor(classNode, property, reversed); } new VariableScopeVisitor(sourceUnit, true).visitClass(classNode); }
Source:
<code>public void validateItemType(Item item, String bindingConfig) throws BindingConfigParseException { if (!((item instanceof SwitchItem) || (item instanceof ContactItem))) { <START> logger.error("Item '" + item.getName() + "' is of type '" + item.getClass().getSimpleName() + <END> "' while only 'Switch' or 'Contact' types are allowed"); throw new BindingConfigParseException("Item '" + item.getName() + "' is of type '" + item.getClass().getSimpleName() + "' while only 'Switch' or 'Contact' types are allowed"); } }</code><technical_language>parameterized logging instead of string concatenation</technical_language>

Target:
public void validateItemType(Item item, String bindingConfig) throws BindingConfigParseException { if (!((item instanceof SwitchItem) || (item instanceof ContactItem))) { String message = "Item '" + item.getName() + "' is of type '" + item.getClass().getSimpleName() + "' "; message = message + "while only 'Switch' or 'Contact' types are allowed"; logger.error("{}", message); throw new BindingConfigParseException(message); } }
Source:
<code>private void newImport(List fileHierarchy, String value, Int2 valuePos, int num) throws TemplateSyntaxException { boolean isMetamodelImport = parseMetamodelImport(value, valuePos, num); if (scriptContext == null || scriptContext.getMaxLevel() == -1 || fileHierarchy.size() < scriptContext.getMaxLevel()) { if (!isMetamodelImport) { if (file != null) { boolean service = false; boolean specificExists = false; try { addImportForJavaService(file, value); service = true; } catch (final JavaServiceNotFoundException e) { } <START> if (!service) { <END> final String[] specificExtensions = getSpecificImportExtensions(); for (String specificExtension : specificExtensions) { final File specificFile = resolveScriptFile(file, value, specificExtension); if (specificFile != null && specificFile.exists()) { IScript genSpecific = this; do { if (genSpecific.getFile() != null && genSpecific.getFile().equals(specificFile)) { throw new TemplateSyntaxException(AcceleoGenMessages.getString("TemplateSyntaxError.RecursiveImport"), this, valuePos); } genSpecific = genSpecific.getSpecific(); } while (genSpecific != null); try { if (!tryOptimizedImport(fileHierarchy, specificFile)) { final SpecificScript newImport = createSpecificImport(specificFile); newImport.setInitProfiling(initProfiling); newImport.reset(new ArrayList(fileHierarchy)); newImport.setSpecific(this); addImport(newImport); } } catch (final TemplateSyntaxExceptions e) { String message = AcceleoGenMessages.getString("SpecificScript.ErroneousTemplate"); if (e.getProblems().size() == 1) { message += " : " + ((TemplateSyntaxException) e.getProblems().get(0)).getMessage(); } throw new TemplateSyntaxException(message, this, valuePos); } specificExists = true; } } } if (!service && !specificExists) { throw new TemplateSyntaxException(AcceleoGenMessages.getString("TemplateSyntaxError.UnresolvedImport", new Object[] { value, }), this, valuePos); } } } } }</code><technical_language>a specialist query legacy I is a change of behavior: If is a java service specific script name, specific script is longer imported</technical_language>

Target:
protected void newImport(List fileHierarchy, String value, Int2 valuePos, int num) throws TemplateSyntaxException { boolean isMetamodelImport = parseMetamodelImport(value, valuePos, num); if (scriptContext == null || scriptContext.getMaxLevel() == -1 || fileHierarchy.size() < scriptContext.getMaxLevel()) { if (!isMetamodelImport) { if (file != null) { boolean service = false; boolean specificExists = false; if (useSpecificImportsFirst()) { specificExists = newImportFromSpecificImports(fileHierarchy, value, valuePos, num); service = newImportFromJavaServices(value); } else { service = newImportFromJavaServices(value); if (!service) { specificExists = newImportFromSpecificImports(fileHierarchy, value, valuePos, num); } } if (!service && !specificExists) { throw new TemplateSyntaxException(AcceleoGenMessages.getString("TemplateSyntaxError.UnresolvedImport", new Object[] { value, }), this, valuePos); } } } } }
Source:
<code><START> public static IndexedTypesSet fromClasses(Class<?>... classes) { <END> if ( classes == null || classes.length == 0 ) { return empty(); } else if ( classes.length == 1 ) { return fromClass( classes[0] ); } else { HashSet<IndexedTypeIdentifier> set = new HashSet<>(); for ( Class<?> c : classes ) { set.add( new PojoIndexedTypeIdentifier( c ) ); } return new HashSetIndexedTypesSet( set ); } }</code><technical_language>I guess a definite convention for kind of utils? In java 8 put main utilities in interface (java.util.stream.Collector.of(Supplier<A>, BiConsumer<A, T>, BinaryOperator<A>, Function<A, R>, Characteristics...)) more specific in a separate utility class (java.util.stream.Collectors.toList()). In some cases put of utility methods in interface ( (java.util.stream.Stream for instance). wondering put of utility methods in interface..</technical_language>

Target:
public static IndexedTypeSet fromClasses(Class<?>... classes) { if ( classes == null || classes.length == 0 ) { return empty(); } else if ( classes.length == 1 ) { return fromClass( classes[0] ); } else { return Arrays.stream( classes ).map( PojoIndexedTypeIdentifier::new ).collect( streamCollector() ); } }
Source:
<code>protected void checkPathLegal(Path targetPath) { <START> if (!context.entityClass.getSimpleName().equals(targetPath.getSegment().getElementType().getSimpleName())) { <END> throw new IllegalArgumentException("Current position in the inventory traversal expects entities of type " + context.entityClass.getSimpleName() + " which is incompatible with the provided path: " + targetPath); } }</code><technical_language>if I string matching here. creating some helper in inventory API, InventoryPaths, convert this in slightly efficient manner? a toSegmentType(Class) method some IdentityHashMap (or a series of ifs) toEntityType(SegmentType) Entity.entityTypeFromSegmentType()? a dedicate method for this - InventoryPaths.representsSegmentType(Class, SegmentType) a switch equality comparison a class (which is reference equality quick)</technical_language>

Target:
protected void checkPathLegal(Path targetPath) { if (!Entity.segmentTypeFromType(context.entityClass).equals(targetPath.getSegment().getElementType())) { throw new IllegalArgumentException("Current position in the inventory traversal expects entities of type " + context.entityClass.getSimpleName() + " which is incompatible with the provided path: " + targetPath); } }
Source:
<code>public Concrete.Expression visitApplyHole(Concrete.ApplyHoleExpression expr, Void params) { <START> myErrorReporter.report(new GeneralError(GeneralError.Level.ERROR, "`__` not allowed here")); <END> return super.visitApplyHole(expr, params); }</code><technical_language>is TypecheckingError this stage</technical_language>

Target:
public Concrete.Expression visitApplyHole(Concrete.ApplyHoleExpression expr, Void params) { return expr; }
Source:
<code>public RESTHttpServerController(OMElement element) { super(element); packageName = SynapseTestUtils.getParameter(element, SampleConfigConstants.TAG_BE_SERVER_CONF_REST_PACKAGE_NAME, null); port = Integer.parseInt(SynapseTestUtils.getParameter(element, <START> SampleConfigConstants.TAG_BE_SERVER_CONF_REST_HTTP_PORT, "9000")); <END> ResourceConfig rc = new ResourceConfig().packages(packageName); try { webServer = GrizzlyHttpServerFactory.createHttpServer(getBaseURI(port), rc, false); } catch (Exception e) { log.error(e); } }</code><technical_language>move this a constant in this class "9000"</technical_language>

Target:
public RESTHttpServerController(OMElement element) { super(element); packageName = SynapseTestUtils.getParameter(element, SampleConfigConstants.TAG_BE_SERVER_CONF_REST_PACKAGE_NAME, null); port = Integer.parseInt(SynapseTestUtils.getParameter(element, SampleConfigConstants.TAG_BE_SERVER_CONF_REST_HTTP_PORT, DEFAULT_PORT)); ResourceConfig rc = new ResourceConfig().packages(packageName); try { webServer = GrizzlyHttpServerFactory.createHttpServer(getBaseURI(port), rc, false); } catch (Exception e) { log.error(e); } }
Source:
<code>protected String usage() { final StringBuilder usage = new StringBuilder(); usage.append("Available commands"); if (!getName().isEmpty()) { usage.append(" of "); usage.append(getName()); } usage.append(" are:\n"); usage.append("\n"); int maxLength = -1; for (String name : commands.keySet()) { maxLength = Math.max(maxLength, name.length()); } String format = "%-" + maxLength + "s %s"; for (String name : Sets.newTreeSet(commands.keySet())) { <START> final Command cmd = commands.get(name).get(); <END> usage.append(" "); if (cmd instanceof BaseCommand) { BaseCommand bc = (BaseCommand)cmd; String descr = bc.getDescription(); if (name.equals("plugin")) { descr = "Install, reload, remove and list plugins"; } usage.append(String.format(format, name, descr)); } else { usage.append(name); } usage.append("\n"); } usage.append("\n"); usage.append("See '"); if (getName().indexOf(' ') < 0) { usage.append(getName()); usage.append(' '); } usage.append("COMMAND --help' for more information.\n"); usage.append("\n"); return usage.toString(); }</code><technical_language>I OK making Command instance here. work, some commands assumptions in injection fail build here. worst wrap this catch a ProvisionException handle gracefully. best, find another provide description. a runtime annotation Class implementation extract part of Guice binding</technical_language>

Target:
protected String usage() { final StringBuilder usage = new StringBuilder(); usage.append("Available commands"); if (!getName().isEmpty()) { usage.append(" of "); usage.append(getName()); } usage.append(" are:\n"); usage.append("\n"); int maxLength = -1; for (String name : commands.keySet()) { maxLength = Math.max(maxLength, name.length()); } String format = "%-" + maxLength + "s %s"; for (String name : Sets.newTreeSet(commands.keySet())) { final Command cmd = commands.get(name).get(); usage.append(" "); if (cmd instanceof BaseCommand) { BaseCommand bc = (BaseCommand)cmd; usage.append(String.format(format, name, bc.getDescription())); } else { usage.append(name); } usage.append("\n"); } usage.append("\n"); usage.append("See '"); if (getName().indexOf(' ') < 0) { usage.append(getName()); usage.append(' '); } usage.append("COMMAND --help' for more information.\n"); usage.append("\n"); return usage.toString(); }
Source:
<code>public void evalGroups(final MutableTupleBuffer state, final int col) throws DbException { IntIterator iter = buffer.keySet().intIterator(); while (iter.hasNext()) { int key = iter.next(); pyWorker.sendNumTuples(buffer.get(key).numTuples()); for (TupleBatch tb : buffer.get(key).getAll()) { for (int tup = 0; tup < tb.numTuples(); tup++) { for (int i = 0; i < tb.numColumns(); ++i) { writeToStream(tb, tup, i); } } } ColumnBuilder<?> output = ColumnFactory.allocateColumn(outputType); <START> readFromStream(null, output); <END> if (output.size() > 1) { throw new RuntimeException("PythonUDFEvaluator cannot be multivalued for Aggregate"); } for (int i = 0; i < output.size(); ++i) { state.replace(col, key, output, i); } } }</code><technical_language>readFromStream() a ColumnBuilder return built Column? I idea of keeping a mutable object immutable, measurable overhead</technical_language>

Target:
public void evalGroups(final MutableTupleBuffer state, final int col) throws DbException { IntIterator keyIter = groups.keySet().intIterator(); while (keyIter.hasNext()) { int key = keyIter.next(); pyWorker.sendNumTuples(groups.get(key).size()); IntIterator rowIter = groups.get(key).intIterator(); while (rowIter.hasNext()) { int row = rowIter.next(); for (int i = 0; i < buffer.numColumns(); ++i) { writeToStream(buffer, row, i); } } ColumnBuilder<?> output = ColumnFactory.allocateColumn(outputType); readFromStream(null, output); if (output.size() > 1) { throw new RuntimeException("PythonUDFEvaluator cannot be multivalued for Aggregate"); } for (int i = 0; i < output.size(); ++i) { state.replace(col, key, output, i); } } }
Source:
<code>private void addOrUpdateSnapshotsConfig(Guid clusterId, GlusterSnapshotConfigInfo configInfo) { try (EngineLock lock = acquireEntityLock(clusterId)) { addOrUpdateClusterConfig(clusterId, "snap-max-hard-limit", configInfo.getSystemSnapMaxHardLimit() .toString()); addOrUpdateClusterConfig(clusterId, "snap-max-soft-limit", configInfo.getSystemSoftLimitPcnt()); <START> addOrUpdateClusterConfig(clusterId, "auto-delete", configInfo.isAutoDeleteEnabled() ? "enable" : "disable"); <END> } List<GlusterSnapshotConfigInfo.VolumeSnapshotConfigInfo> volumeConfigs = configInfo.getVolumeConfigList(); for (GlusterSnapshotConfigInfo.VolumeSnapshotConfigInfo volumeConfig : volumeConfigs) { GlusterVolumeEntity volume = getGlusterVolumeDao().getByName(clusterId, volumeConfig.getVolumeName()); try (EngineLock lock = acquireEntityLock(volume.getId())) { addOrUpdateVolumeConfig(clusterId, volume.getId(), "snap-max-hard-limit", volumeConfig.getVolumeSnapMaxHardLimit().toString()); } } }</code><technical_language>avoid hard-coding config options? work new options introduced</technical_language>

Target:
private void addOrUpdateSnapshotsConfig(Guid clusterId, GlusterSnapshotConfigInfo configInfo) { try (EngineLock lock = acquireEntityLock(clusterId)) { for (String key : configInfo.getClusterConfigOptions().keySet()) { String value = configInfo.getClusterConfigOptions().get(key); if (value != null) { addOrUpdateClusterConfig(clusterId, key, value); } } } Map<String, Map<String, String>> volumeConfigs = configInfo.getVolumeConfigOptions(); for (String key : volumeConfigs.keySet()) { GlusterVolumeEntity volume = getGlusterVolumeDao().getByName(clusterId, key); try (EngineLock lock = acquireEntityLock(volume.getId())) { Map<String, String> volumeConfig = volumeConfigs.get(key); if (volumeConfig != null) { for (String configKey : volumeConfig.keySet()) { String value = volumeConfig.get(configKey); if (value != null) { addOrUpdateVolumeConfig(clusterId, volume.getId(), configKey, value); } } } } } }
Source:
<code>public Collection<SlotKey> getChildrenKeys(Granularity destGranularity) { if (!getGranularity().isCoarser(destGranularity)) { <START> throw new IllegalArgumentException("Current granularity must be coarser than the destination granularity"); <END> } List<SlotKey> result = new ArrayList<SlotKey>(); for(SlotKey slotKey: this.getChildrenKeys()) { if (slotKey.getGranularity().equals(destGranularity)) { result.add(slotKey); } } return Collections.unmodifiableList(result); }</code><technical_language>print 2 granularities involved in Exception msg</technical_language>

Target:
public Collection<SlotKey> getChildrenKeys(Granularity destGranularity) { if (!getGranularity().isCoarser(destGranularity)) { throw new IllegalArgumentException(String.format("Current granularity [%s] must be coarser than the destination granularity [%s]", getGranularity(), destGranularity)); } List<SlotKey> result = new ArrayList<SlotKey>(); for(SlotKey slotKey: this.getChildrenKeys()) { if (slotKey.getGranularity().equals(destGranularity)) { result.add(slotKey); } } return Collections.unmodifiableList(result); }
Source:
<code>public GridTableViewerComposite build() { final GridTableViewerComposite viewerComposite = new GridTableViewerComposite(getComposite(), getSwtStyleBits(), getInput(), getCustomization(), getTitle(), getTooltip()); <START> TableConfigurationUtil.setTableConfiguration(viewerComposite, getCustomization().getTableConfiguration()); <END> return viewerComposite; }</code><technical_language>move out? composite set config itself</technical_language>

Target:
public GridTableViewerComposite build() { return new GridTableViewerComposite(getComposite(), getSwtStyleBits(), getInput(), getCustomization(), getTitle(), getTooltip()); }
Source:
<code>protected <T> T deserialize(byte[] data, Class<T> klass, String path) { try { return objectMapper.readValue(data, klass); } catch (JsonParseException jpe) { try { LOG.error("Invalid Json at path {}: {}", path, new String(data, StandardCharsets.UTF_8), jpe); } catch (Exception e) { <START> LOG.error("Could not parse valid json at path {}", path, e); <END> } throw Throwables.propagate(jpe); } catch (IOException e) { throw Throwables.propagate(e); } }</code><technical_language>calling readValue(), is this 2nd catch necessary</technical_language>

Target:
protected <T> T deserialize(byte[] data, Class<T> klass, String path) { try { return objectMapper.readValue(data, klass); } catch (JsonParseException jpe) { try { LOG.error("Invalid Json at path {}: {}", path, new String(data, StandardCharsets.UTF_8), jpe); } catch (Exception e) { LOG.error("Could not get raw json string at path {}", path, e); } throw Throwables.propagate(jpe); } catch (IOException e) { throw Throwables.propagate(e); } }
Source:
<code>public void test_Case_ChangesWithoutTasks() throws OseeCoreException, InterruptedException { ensurePopulated(); assert_Tasks_OriginalData(destTeamWf1_Proper); assert_Tasks_OriginalData(destTeamWf2_ChangesWithoutTasks); assert_Tasks_OriginalData(destTeamWf3_TasksWithoutChanges); runCreateTasksOperation(ver2_ChangesWithoutTasks, aia2_ChangesWithoutTasks, changeData_ChangesWithoutTasks); <START> assert_Tasks_OriginalData(destTeamWf1_Proper); <END> assert_Tasks_OriginalData(destTeamWf3_TasksWithoutChanges); cleanupAndReset(); }</code><technical_language>deletion of check intentional</technical_language>

Target:
public void test_Case_ChangesWithoutTasks() throws OseeCoreException, InterruptedException { ensurePopulated(); assert_Tasks_OriginalData(destTeamWf1_Proper); assert_Tasks_OriginalData(destTeamWf2_ChangesWithoutTasks); assert_Tasks_OriginalData(destTeamWf3_TasksWithoutChanges); runCreateTasksOperation(ver2_ChangesWithoutTasks, aia2_ChangesWithoutTasks, changeData_ChangesWithoutTasks); assert_Tasks_OriginalData(destTeamWf1_Proper); assert_Tasks_Generated(destTeamWf2_ChangesWithoutTasks); assert_Tasks_OriginalData(destTeamWf3_TasksWithoutChanges); cleanupAndReset(); }
Source:
<code>private boolean doNotReportProblems() { if (fReportingProblemsCurrent) { return fDoNotReportProblems; } fReportingProblemsCurrent = true; fDoNotReportProblems = false; if (AntUIPlugin.getDefault().getCombinedPreferenceStore().getBoolean(AntEditorPreferenceConstants.BUILDFILE_IGNORE_ALL)) { fDoNotReportProblems = true; return fDoNotReportProblems; } String buildFileNames = AntUIPlugin.getDefault().getCombinedPreferenceStore().getString(AntEditorPreferenceConstants.BUILDFILE_NAMES_TO_IGNORE); if (buildFileNames.length() > 0) { String editedFileName = getEditedFile().getName(); for (String <START> string : <END> AntUtil.parseString(buildFileNames, ",")) { if (string.trim().equals(editedFileName)) { fDoNotReportProblems = true; return fDoNotReportProblems; } } } return fDoNotReportProblems; }</code><technical_language>rename fileName</technical_language>

Target:
private boolean doNotReportProblems() { if (fReportingProblemsCurrent) { return fDoNotReportProblems; } fReportingProblemsCurrent = true; fDoNotReportProblems = false; if (AntUIPlugin.getDefault().getCombinedPreferenceStore().getBoolean(AntEditorPreferenceConstants.BUILDFILE_IGNORE_ALL)) { fDoNotReportProblems = true; return fDoNotReportProblems; } String buildFileNames = AntUIPlugin.getDefault().getCombinedPreferenceStore().getString(AntEditorPreferenceConstants.BUILDFILE_NAMES_TO_IGNORE); if (buildFileNames.length() > 0) { String editedFileName = getEditedFile().getName(); for (String fileName : AntUtil.parseString(buildFileNames, ",")) { if (fileName.trim().equals(editedFileName)) { fDoNotReportProblems = true; return fDoNotReportProblems; } } } return fDoNotReportProblems; }
Source:
<code>public Image getScaledWebImage(URI sourceUri, double factor) throws IOException { if (!new File(sourceUri).exists()) { throw new FileNotFoundException("sourceUri must exist: " + sourceUri.getRawPath()); } if (Double.isNaN(factor)) { throw new IllegalArgumentException("factor must be a number, but was " + Double.toString(factor)); } if (factor <= 0.0) { throw new IllegalArgumentException("factor must be > 0.0, but was " + Double.toString(factor)); } File tempFile = File.createTempFile("scaledWebImage-", WEB_IMAGE_FORMAT, TMPDIR); try { <START> tempFile.deleteOnExit(); <END> ImageConverter imageConverter = new ImageConverter(sourceUri); imageConverter.addResult(tempFile.toURI()).resize(factor); logger.info("Generating scaled web image from as {}, factor {}%", sourceUri, tempFile, 100 * factor); imageConverter.run(); logger.trace("Loading {}", tempFile); Image buffer = ImageIO.read(tempFile); logger.trace("{} successfully loaded", tempFile); return buffer; } finally { logger.debug("Deleting {}", tempFile); tempFile.delete(); logger.trace("Successfully deleted {}", tempFile); } }</code><technical_language>add this deleteOnExit if delete this file in finally block</technical_language>

Target:
public Image getScaledWebImage(URI sourceUri, double factor) throws IOException { if (!new File(sourceUri).exists()) { throw new FileNotFoundException("sourceUri must exist: " + sourceUri.getRawPath()); } if (Double.isNaN(factor)) { throw new IllegalArgumentException("factor must be a number, but was " + Double.toString(factor)); } if (factor <= 0.0) { throw new IllegalArgumentException("factor must be > 0.0, but was " + Double.toString(factor)); } return summarize("scaledWebImage-", WEB_IMAGE_FORMAT, sourceUri, λ -> λ.resize(factor), "Generating scaled web image from as {}, factor {}%", 100 * factor); }
Source:
<code>public JSchFileManager(IRemoteConnection connection) { if (connection instanceof JSchConnection) try { ((JSchConnection) connection).getSftpChannel(); } catch (RemoteConnectionException e) { throw new UnsupportedOperationException(Messages.JSchConnection_Remote_host_does_not_support_sftp); <START> } <END> fConnection = connection; }</code><technical_language>I constructors throwing exceptions. I this check in getService() constructor access changed private</technical_language>

Target:
private JSchFileManager(IRemoteConnection connection) { fConnection = connection; }
Source:
<code>public SearchData(String text, String title, String content, String wikiType, String wikiOwner, String pageId) { <START> this.text = org.exoplatform.wiki.utils.Utils.escapeIllegalCharacterInQuery(text); <END> this.title = title; this.content = content; this.wikiType = wikiType; this.wikiOwner = Utils.validateWikiOwner(wikiType, wikiOwner); this.pageId = pageId; if (PortalConfig.USER_TYPE.equals(wikiType)) { NodeHierarchyCreator nodeHierachyCreator = (NodeHierarchyCreator) ExoContainerContext.getCurrentContainer() .getComponentInstanceOfType(NodeHierarchyCreator.class); try { if (wikiOwner != null && wikiOwner.length() > 0) { Node userNode = nodeHierachyCreator.getUserApplicationNode(CommonUtils.createSystemProvider(), wikiOwner); USER_PATH = userNode.getPath() + "/" + WikiNodeType.Definition.WIKI_APPLICATION + "/"; } } catch (Exception e) { if (e instanceof PathNotFoundException) throw new NoSuchNodeException(e); else throw new UndeclaredRepositoryException(e.getMessage()); } } }</code><technical_language>class is imported line 29. Shoul invoke simply Utils.escapeIllegalCharacterInQuery(text)</technical_language>

Target:
public SearchData(String text, String title, String content, String wikiType, String wikiOwner, String pageId) { this.text = Utils.escapeIllegalCharacterInQuery(text); this.title = title; this.content = content; this.wikiType = wikiType; this.wikiOwner = Utils.validateWikiOwner(wikiType, wikiOwner); this.pageId = pageId; if (PortalConfig.USER_TYPE.equals(wikiType)) { NodeHierarchyCreator nodeHierachyCreator = (NodeHierarchyCreator) ExoContainerContext.getCurrentContainer() .getComponentInstanceOfType(NodeHierarchyCreator.class); try { if (wikiOwner != null && wikiOwner.length() > 0) { Node userNode = nodeHierachyCreator.getUserApplicationNode(CommonUtils.createSystemProvider(), wikiOwner); USER_PATH = userNode.getPath() + "/" + WikiNodeType.Definition.WIKI_APPLICATION + "/"; } } catch (Exception e) { if (e instanceof PathNotFoundException) throw new NoSuchNodeException(e); else throw new UndeclaredRepositoryException(e.getMessage()); } } }
Source:
<code>private Object convertValue(Object value, Type type) { if (value == null) { return null; } if (BOOLEAN.equals(type) || Varchars.isVarcharType(type)) { return value; } if (BIGINT.equals(type)) { return ((Number) value).longValue(); } if (INTEGER.equals(type)) { return ((Number) value).intValue(); } if (DOUBLE.equals(type)) { return ((Number) value).doubleValue(); } if (DATE.equals(type)) { return value; } <START> throw new IllegalArgumentException("unhandled type: " + type); <END> }</code><technical_language>Unhandled</technical_language>

Target:
private Object convertValue(Object value, Type type) { if (value == null) { return null; } if (BOOLEAN.equals(type) || DATE.equals(type) || Varchars.isVarcharType(type)) { return value; } if (BIGINT.equals(type)) { return ((Number) value).longValue(); } if (INTEGER.equals(type)) { return ((Number) value).intValue(); } if (DOUBLE.equals(type)) { return ((Number) value).doubleValue(); } throw new IllegalArgumentException("Unhandled type: " + type); }
Source:
<code>public void setUp() throws IOException { project = createProject(); ArrayList<UserVariable> allVariables = new ArrayList<>(); sprite1.getUserVariables().addAll(generateUserVariables("S1_Variable:", 3)); allVariables.addAll(sprite1.getUserVariables()); sprite2.getUserVariables().addAll(generateUserVariables("S2_Variable:", 3)); allVariables.addAll(sprite2.getUserVariables()); sprite3.getUserVariables().addAll(generateUserVariables("S3_Variable:", 3)); allVariables.addAll(sprite3.getUserVariables()); <START> project.getUserVariables().addAll(generateUserVariables("S3_Variable:", 3)); <END> allVariables.addAll(project.getUserVariables()); accessor = new DeviceVariableAccessor(directory); HashMap<UUID, Object> map = new HashMap<>(); for (UserVariable userVariable: allVariables) { map.put(userVariable.getDeviceValueKey(), userVariable.getValue()); } accessor.writeMapToJson(map); }</code><technical_language>check name</technical_language>

Target:
public void setUp() throws IOException { project = createProject(); ArrayList<UserVariable> allVariables = new ArrayList<>(); sprite1.getUserVariables().add(sprite1UserVariable); allVariables.addAll(sprite1.getUserVariables()); sprite2.getUserVariables().add(sprite2UserVariable); allVariables.addAll(sprite2.getUserVariables()); project.getUserVariables().add(globalUserVariable); allVariables.addAll(project.getUserVariables()); accessor = new DeviceVariableAccessor(directory); HashMap<UUID, Object> map = new HashMap<>(); for (UserVariable userVariable: allVariables) { map.put(userVariable.getDeviceValueKey(), userVariable.getValue()); } accessor.writeMapToJson(map); }