auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected FileLock lock(final long lockPosition) throws Exception { long start = System.currentTimeMillis(); boolean isRecurringFailure = false; while (!interrupted) { try { FileLock lock = tryLock(lockPosition); isRecurringFailure = false; if (lock == null) { logger.debug("lock is null"); try { Thread.sleep(500); } catch (InterruptedException e) { return null; } if (lockAcquisitionTimeout != -1 && (System.currentTimeMillis() - start) > lockAcquisitionTimeout) { throw new Exception("timed out waiting for lock"); } } else { return lock; } } catch (IOException e) { logger.log(isRecurringFailure ? Logger.Level.DEBUG : Logger.Level.WARN, "Failure when accessing a lock file", e); isRecurringFailure = true; <START> Thread.sleep(LOCK_ACCESS_FAILURE_WAIT_TIME); <END> } } FileLock lock = null; do { try { lock = tryLock(lockPosition); isRecurringFailure = false; if (lock == null) { try { Thread.sleep(500); } catch (InterruptedException e1) { } } } catch (IOException e) { logger.log(isRecurringFailure ? Logger.Level.DEBUG : Logger.Level.WARN, "Failure when accessing a lock file", e); isRecurringFailure = true; Thread.sleep(LOCK_ACCESS_FAILURE_WAIT_TIME); } if (interrupted) { interrupted = false; throw new IOException("Lock was interrupted"); } } while (lock == null); return lock; }</code><technical_language>This continue attempt lock lockAcquisitionTimeout (if any): i suppose more robust if check timeout anyway. tests timeout I suppose honored</technical_language>

Target:
protected FileLock lock(final long lockPosition) throws Exception { long start = System.currentTimeMillis(); boolean isRecurringFailure = false; while (!interrupted) { try { FileLock lock = tryLock(lockPosition); isRecurringFailure = false; if (lock == null) { try { Thread.sleep(500); } catch (InterruptedException e) { return null; } if (lockAcquisitionTimeout != -1 && (System.currentTimeMillis() - start) > lockAcquisitionTimeout) { throw new ActiveMQLockAcquisitionTimeoutException("timed out waiting for lock"); } } else { return lock; } } catch (IOException e) { logger.log(isRecurringFailure ? Logger.Level.DEBUG : Logger.Level.WARN, "Failure when accessing a lock file", e); isRecurringFailure = true; long waitTime = LOCK_ACCESS_FAILURE_WAIT_TIME; if (lockAcquisitionTimeout != -1) { final long remainingTime = lockAcquisitionTimeout - (System.currentTimeMillis() - start); if (remainingTime <= 0) { throw new ActiveMQLockAcquisitionTimeoutException("timed out waiting for lock"); } waitTime = Math.min(waitTime, remainingTime); } try { Thread.sleep(waitTime); } catch (InterruptedException interrupt) { return null; } } } return null; }
Source:
<code>public Object execute() throws Exception { EventBuilder eventBuilder = new EventBuilder(EventConstants.RELOAD_IMPORT_UEI, EVENT_SOURCE); if((!Strings.isNullOrEmpty(requisition)) && (!Strings.isNullOrEmpty(type)) && requisition.contains("=")) { String url = String.format("requisition://%s?%s", type, requisition); eventBuilder.addParam("url", url); eventForwarder.sendNow(eventBuilder.getEvent()); <START> System.out.printf("Import Requisition Event sent with URL : %s \n ", url); <END> } else { System.out.printf("No valid requisition specified, It should be specified in 'name=myServer' format \n"); } return null; }</code><technical_language>suggestion System.out.printf("Requisition import triggered asynchronously for URL: %s\n", url);</technical_language>

Target:
public Object execute() throws Exception { return sendImportRequisitionEvent(eventForwarder, type, parameters, rescanExisting); }
Source:
<code>public StrangeCANSpeedControllerModeRuntimeException() { super("One of " + getName() <START> + "'s CustomSpeedControllers is a CANSpeedController with a non-zero mode. This might mess up it's .get(), so Motor cannot verify safety."); <END> }</code><technical_language>SpeedController CustomSpeedController</technical_language>

Target:
public StrangeCANSpeedControllerModeRuntimeException() { super("One of " + getName() + "'s SpeedControllers is a CANSpeedController with a non-zero mode. This might mess up it's .get(), so Motor cannot verify safety."); }
Source:
<code>public RosActivity(String notificationTicker, String notificationTitle) { super(); rosActivityComponent = new RosActivityComponent(notificationTicker, notificationTitle, this); <START> <END> }</code><technical_language>Remove blank line</technical_language>

Target:
public RosActivity(String notificationTicker, String notificationTitle) { rosActivityComponent = new RosActivityComponent(this, notificationTicker, notificationTitle, new RosActivityEventsHandler()); }
Source:
<code>public ClosableIterator<RowResult<Set<Long>>> getRangeOfTimestamps( TableReference tableRef, RangeRequest rangeRequest, long timestamp) { <START> return new RangeOfTimestampsIterator(this, tableRef, rangeRequest, timestamp); <END> }</code><technical_language>Passing in this ugly</technical_language>

Target:
public ClosableIterator<RowResult<Set<Long>>> getRangeOfTimestamps( TableReference tableRef, RangeRequest rangeRequest, long timestamp) { CandidateCellForSweepingRequest request = ImmutableCandidateCellForSweepingRequest.builder() .startRowInclusive(rangeRequest.getStartInclusive()) .maxTimestampExclusive(timestamp) .addTimestampsToIgnore() .shouldCheckIfLatestValueIsEmpty(false) .build(); return getCandidateRowsForSweeping(tableRef, request) .flatMap(rows -> rows) .map(row -> row.toRowResult()) .stopWhen(rowResult -> !rangeRequest.inRange(rowResult.getRowName())); }
Source:
<code>public synchronized void addWarnings(List<PrestoWarning> warnings) { for (; warningsSeen < warnings.size(); warningsSeen++) { <START> addWarning(warnings.get(warningsSeen)); <END> } }</code><technical_language>This method logic assume list passed in meets criteria: * list is smaller previous invocations * new warnings end of list This is error-prone hard reason API protect callers incorrectly. unclear this interacts clearWarnings method below. fundamental issue is this class state (warningsSeen) behavior occurs of it. cleaner stateless require callers pass warnings new time. Also, bug lurking here. I list obtained results.getWarnings() in resultset loop satisfies constraints</technical_language>

Target:
public synchronized void addWarnings(List<PrestoWarning> warnings) { for (PrestoWarning warning : warnings) { if (warningsSeen.add(warning.getWarningCode())) { addWarning(warning); } } }
Source:
<code>default boolean knowablySemanticallyEquivalent(VersionedInternalSchemaMetadata other) { <START> if (version() != other.version()) { <END> return false; } return underlyingData().isPresent() && other.underlyingData().isPresent() && underlyingData().get().equals(other.underlyingData().get()); }</code><technical_language>do need a null check here</technical_language>

Target:
default boolean knowablySemanticallyEquivalent(VersionedInternalSchemaMetadata other) { if (other == null || version() != other.version()) { return false; } return underlyingData().isPresent() && other.underlyingData().isPresent() && underlyingData().get().equals(other.underlyingData().get()); }
Source:
<code>public TestingService(ProjectManager projectManager, TestFrameworkRegistry frameworkRegistry, TestClasspathRegistry classpathRegistry) { this.projectManager = projectManager; this.frameworkRegistry = frameworkRegistry; this.classpathRegistry = classpathRegistry; <START> System.out.println("inititilaized TestingService"); <END> }</code><technical_language>remove</technical_language>

Target:
public TestingService(ProjectManager projectManager, TestFrameworkRegistry frameworkRegistry, TestClasspathRegistry classpathRegistry) { this.projectManager = projectManager; this.frameworkRegistry = frameworkRegistry; this.classpathRegistry = classpathRegistry; }
Source:
<code>public IToHex getInstance(DiscreteElement<?> elementType){ if(elementType instanceof EnumeratedElement){ return new EnumToHex(); } else if (elementType instanceof NumericElement<?>){ return new NumericToHex(); }else if (elementType instanceof EmptyEnum_Element){ return new EmptyEnumToHex(); }else if (elementType instanceof StringElement){ return new StringToHex(); <START> }else{ return new CharToHex(); } <END> }</code><technical_language>this else-if instead checking is a CharElement. add else case logs error returns some IToHex do conversion (like unused InaccesibleToHex)</technical_language>

Target:
public IToHex getInstance(DiscreteElement<?> elementType){ if(elementType instanceof EnumeratedElement){ return new EnumToHex(); } else if (elementType instanceof NumericElement<?>){ return new NumericToHex(); }else if (elementType instanceof EmptyEnum_Element){ return new EmptyEnumToHex(); }else if (elementType instanceof StringElement){ return new StringToHex(); }else if (elementType instanceof CharElement){ return new CharToHex(); }else{ OseeLog.log(ToHexFactory.class, Level.SEVERE, "ERROR: " + elementType.getDescriptiveName() + " was not handled correctly"); return new InaccessibleToHex(); } }
Source:
<code>private BuilderInfo findBuilderInfoFromInnerBuilderClass(TypeElement typeElement) { if (shouldIgnore( typeElement )) { return null; } List<TypeElement> types = ElementFilter.typesIn( typeElement.getEnclosedElements() ); List<BuilderInfo> builderInfo = new ArrayList<>(); types.stream() .filter( innerType -> isPossibleInnerBuilder( innerType, typeElement ) ) .forEach( innerBuilderClass -> { Collection<ExecutableElement> buildMethods = findBuildMethods( innerBuilderClass, typeElement ); if (!buildMethods.isEmpty()) { ElementFilter.constructorsIn( innerBuilderClass.getEnclosedElements() ) .stream() .filter( constructor -> constructor.getParameters().isEmpty() && constructor.getModifiers().contains( Modifier.PUBLIC ) ) .findAny() .ifPresent( defaultConstructor -> builderInfo.add( new BuilderInfo.Builder() .builderCreationMethod( defaultConstructor ) .buildMethod( buildMethods ) .build() ) ); } <START> } ); <END> if (builderInfo.size() == 1) { return builderInfo.get( 0 ); } else if (builderInfo.size() > 1) { throw new MoreThanOneBuilderCreationMethodException(typeElement.asType(), builderInfo); } return null; }</code><technical_language>refactor . I mean... complicated :) I this big stream pipeline</technical_language>

Target:
private BuilderInfo findBuilderInfoFromInnerBuilderClass(TypeElement typeElement) { if (shouldIgnore( typeElement )) { return null; } List<TypeElement> innerTypes = ElementFilter.typesIn( typeElement.getEnclosedElements() ); ExecutableElement defaultConstructor = innerTypes.stream() .filter( this::isBuilderCandidate ) .map( this::getEmptyArgPublicConstructor ) .filter( Objects::nonNull ) .findAny() .orElse( null ); if ( defaultConstructor != null ) { return new BuilderInfo.Builder() .builderCreationMethod( defaultConstructor ) .buildMethod( findBuildMethods( (TypeElement) defaultConstructor.getEnclosingElement(), typeElement ) ) .build(); } return null; }
Source:
<code>boolean verify() throws Exception; } public static boolean verify(Verifier verifier, long timeout) throws Exception { long start = System.currentTimeMillis(); do { boolean result = verifier.verify(); long now = System.currentTimeMillis(); if (result || (now - start) > timeout) { if ((now -start) > timeout && !result) { LOG.error("verifier time out, consider try longer timeout, stack trace{}", Arrays.asList(Thread.currentThread().getStackTrace())); } <START> return result; <END> } Thread.sleep(50); } while (true); }</code><technical_language>This code chaotic. Please simplify. boolean result = verifier.verify(); boolean timeout = (System.currentTimeMillis() - start) > timeout; if (result || timeout) { if (timeout) { LOG.error() } return result; }</technical_language>

Target:
boolean verify() throws Exception; } public static boolean verify(Verifier verifier, long timeout) throws Exception { long start = System.currentTimeMillis(); do { boolean result = verifier.verify(); boolean isTimedout = (System.currentTimeMillis() - start) > timeout; if (result || isTimedout) { if (isTimedout && !result) { LOG.error("verifier time out, consider try longer timeout, stack trace{}", Arrays.asList(Thread.currentThread().getStackTrace())); } return result; } Thread.sleep(50); } while (true); }
Source:
<code>private void checkManifestContent(IProject project) throws IOException { InputStream is = null; try { is = project.getFile("META-INF/MANIFEST.MF").getContents(); } catch (CoreException e) { fail("Cannot read the Manifest content"); <START> } <END> BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line = null; Boolean findJse = false; try { while ((line = reader.readLine()) != null && !findJse) { findJse = line.contains("Bundle-RequiredExecutionEnvironment:"); if (findJse) { assertEquals("The JSE name should be the name of the default environment execution.", "Bundle-RequiredExecutionEnvironment: JavaSE-" + System.getProperty("java.version").substring(0, 3), line); } } } finally { is.close(); } }</code><technical_language>is preferable : Manifest manifest = new Manifest(is); Attributes attributes = manifest.getMainAttributes(); String eeVersion = attributes.getValue("Bundle-RequiredExecutionEnvironment"); instead of a BufferedReader reads line..</technical_language>

Target:
private void checkManifestContent(IProject project) throws IOException { InputStream is = null; try { is = project.getFile("META-INF/MANIFEST.MF").getContents(); try { Manifest manifest = new Manifest(is); Attributes attributes = manifest.getMainAttributes(); String currentJseId = attributes.getValue("Bundle-RequiredExecutionEnvironment"); assertEquals("The JSE name should be the name of the default environment execution.", ViewpointSpecificationProject.getDefaultJseId(), currentJseId); } catch (IOException ex) { fail("Error while reading Bundle-RequiredExecutionEnvironment: " + ex.getMessage()); } } catch (CoreException e) { fail("Cannot read the Manifest content"); } finally { is.close(); } }
Source:
<code>protected void executeVmCommand() { lockImageInDb(); List<UpdateDiskParameters.Phase> phaseList = new ArrayList<>(); ImagesHandler.setDiskAlias(getParameters().getDiskInfo(), getVm()); if (resizeDiskImageRequested()) { phaseList.add(UpdateDiskParameters.Phase.EXTEND_DISK); } if (getOldDisk().getDiskStorageType() == DiskStorageType.IMAGE && amendDiskRequested()) { phaseList.add(UpdateDiskParameters.Phase.AMEND_DISK); } phaseList.add(UpdateDiskParameters.Phase.UPDATE_DISK); <START> getParameters().setDiskUpdatePhases(phaseList); <END> setSucceeded(true); }</code><technical_language>add persistCommandIfNeeded() parameters update</technical_language>

Target:
protected void executeVmCommand() { lockImageInDb(); List<UpdateDiskParameters.Phase> phaseList = new ArrayList<>(); ImagesHandler.setDiskAlias(getParameters().getDiskInfo(), getVm()); if (resizeDiskImageRequested()) { phaseList.add(UpdateDiskParameters.Phase.EXTEND_DISK); } if (getOldDisk().getDiskStorageType() == DiskStorageType.IMAGE && amendDiskRequested()) { phaseList.add(UpdateDiskParameters.Phase.AMEND_DISK); } phaseList.add(UpdateDiskParameters.Phase.UPDATE_DISK); getParameters().setDiskUpdatePhases(phaseList); persistCommandIfNeeded(); setSucceeded(true); }
Source:
<code>createDataStore(Class<K> keyClass, Class<T> persistentClass) throws GoraException { <START> <END> Properties properties = DataStoreFactory.createProps(); DataStore<K,T> dataStore = DataStoreFactory.createDataStore( (Class<? extends DataStore<K,T>>)dataStoreClass, keyClass, persistentClass, conf, properties); dataStores.add(dataStore); log.info("Datastore for "+persistentClass+" was added."); return dataStore; }</code><technical_language>Remove whitespace</technical_language>

Target:
createDataStore(Class<K> keyClass, Class<T> persistentClass) throws GoraException { final Properties properties = DataStoreFactory.createProps(); final DataStore<K, T> dataStore = DataStoreFactory.createDataStore( (Class<? extends DataStore<K, T>>) dataStoreClass, keyClass, persistentClass, conf, properties); dataStores.add(dataStore); log.info("Datastore for was added.", persistentClass); return dataStore; }
Source:
<code>public RowRanges visit(Not not) { throw new IllegalArgumentException( <START> "This predicate contains a not! Did you forget to run this predicate through LogicalInverseRewriter? " + not); <END> }</code><technical_language>(nit) wording of exception mislead some end users thinking forgot do in fact this is error developer's side. Instead, I suggest "Predicates a run LogicalInverseRewriter." similar</technical_language>

Target:
public RowRanges visit(Not not) { throw new IllegalArgumentException( "Predicates containing a NOT must be run through LogicalInverseRewriter. " + not); }
Source:
<code>public void configurePipeline(PipelineConfigurer pipelineConfigurer) throws IllegalArgumentException { super.configurePipeline(pipelineConfigurer); pipelineConfigurer.getStageConfigurer().setOutputSchema(outputSchema); FailureCollector collector = pipelineConfigurer.getStageConfigurer().getFailureCollector(); Schema inputSchema = pipelineConfigurer.getStageConfigurer().getInputSchema(); if (inputSchema != null) { if (inputSchema.getField(config.inputField) == null) { collector.addFailure(String.format("Field '%s' must be present in input schema.", config.inputField), null) <START> .withConfigProperty(INPUT_FIELD); <END> } else if (inputSchema.getField(config.inputField).getSchema().getType() != Schema.Type.STRING) { collector.addFailure(String.format("Field '%s' must be of type string.", config.inputField), null) .withConfigProperty(INPUT_FIELD).withInputSchemaField(config.inputField); } } }</code><technical_language>indentation (and rest of PR)</technical_language>

Target:
public void configurePipeline(PipelineConfigurer pipelineConfigurer) throws IllegalArgumentException { super.configurePipeline(pipelineConfigurer); pipelineConfigurer.getStageConfigurer().setOutputSchema(outputSchema); FailureCollector collector = pipelineConfigurer.getStageConfigurer().getFailureCollector(); Schema inputSchema = pipelineConfigurer.getStageConfigurer().getInputSchema(); if (inputSchema != null) { Schema.Field field = inputSchema.getField(config.inputField); if (field == null) { collector.addFailure(String.format("Field '%s' must be present in input schema.", config.inputField), null) .withConfigProperty(INPUT_FIELD); } else if (field.getSchema().getType() != Schema.Type.STRING) { collector.addFailure(String.format("Field '%s' must be of type string.", config.inputField), null) .withConfigProperty(INPUT_FIELD).withInputSchemaField(config.inputField); } } }
Source:
<code>private InputStreamContinuator constructContinuatorForCompatibleRequest(final HttpUriRequest request, final CloseableHttpResponse response) { if (this.maxDownloadContinuations == DOWNLOAD_CONTINUATIONS_DISABLED || !HttpGet.METHOD_NAME.equalsIgnoreCase(request.getMethod()) || !(this.connectionContext instanceof MantaApacheHttpClientContext) || !(request instanceof HttpGet)) { return null; } final HttpGet get = (HttpGet) request; final ResumableDownloadMarker marker; try { marker = validateInitialExchange( extractDownloadRequestFingerprint(get), response.getStatusLine().getStatusCode(), extractDownloadResponseFingerprint(response, true)); <START> } catch (final ProtocolException pe) { <END> return null; } try { return new ApacheHttpGetResponseEntityContentContinuator( (MantaApacheHttpClientContext) this.connectionContext, get, marker, this.maxDownloadContinuations); } catch (final ResumableDownloadException rde) { LOGGER.debug( String.format( "Expected to build a continuator but an exception occurred: %s", rde.getMessage())); } return null; }</code><technical_language>A note exception is swallowed null returned useful reader</technical_language>

Target:
private InputStreamContinuator constructContinuatorForCompatibleRequest(final HttpUriRequest request, final CloseableHttpResponse response) { if (this.maxDownloadContinuations == DOWNLOAD_CONTINUATIONS_DISABLED || !HttpGet.METHOD_NAME.equalsIgnoreCase(request.getMethod()) || !(this.connectionContext instanceof MantaApacheHttpClientContext) || !(request instanceof HttpGet)) { return null; } final HttpGet get = (HttpGet) request; final HttpDownloadContinuationMarker marker; try { marker = validateInitialExchange(extractDownloadRequestFingerprint(get), response.getStatusLine().getStatusCode(), extractDownloadResponseFingerprint(response, true)); } catch (final ProtocolException pe) { LOGGER.debug("HTTP download cannot be automatically continued: {}", pe.getMessage()); return null; } try { return new ApacheHttpGetResponseEntityContentContinuator( (MantaApacheHttpClientContext) this.connectionContext, get, marker, this.maxDownloadContinuations); } catch (final HttpDownloadContinuationException rde) { LOGGER.debug( String.format( "Expected to build a continuator but an exception occurred: %s", rde.getMessage())); } return null; }
Source:
<code>private void discoverRegistryPressed(Shell shell) { String ret = RegistryProviderModel.getDefault().getRegistryURL(pageModel.getSelectedConnection()); if( ret != null ) { registryURLObservable.setValue(ret); <START> } else { <END> MessageBox messageBox = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK); messageBox.setMessage("No registry provider found for the given connection."); int rc = messageBox.open(); } }</code><technical_language>report this UI in a more UX way: thinking reporting Info status databinding framework more user friendly</technical_language>

Target:
private void discoverRegistryPressed(Shell shell) { String ret = RegistryProviderModel.getDefault().getRegistryURL(pageModel.getSelectedConnection()); if( ret != null ) { registryURLObservable.setValue(ret); } else { MessageBox messageBox = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK); messageBox.setText("Registry URL not found"); messageBox.setMessage("No registry provider found for the given connection. If your Openshift connection is backed by a CDK or minishift installation, please ensure the CDK is running."); int rc = messageBox.open(); } }
Source:
<code>private static long getChunkCacheSize(IEclipsePreferences node) { double maxSizeMb = node.getDouble(CHUNK_CACHE_SIZE_MB, CHUNK_CACHE_SIZE_MB_DEFAULT); double maxSizePercent = node.getDouble(CHUNK_CACHE_SIZE_PERCENT, CHUNK_CACHE_SIZE_PERCENT_DEFAULT); maxSizePercent = Math.max(1.0, <START> Math.min(50.0, maxSizePercent)); <END> maxSizeMb = Math.max(maxSizeMb, 1.0); long m1= (long)(Runtime.getRuntime().maxMemory() / 100.0 * maxSizePercent); return Math.min(m1, (long)(maxSizeMb * 1024.0 * 1024.0)); }</code><technical_language>If want limit maximum percent of heap for cache, done in preference page, here</technical_language>

Target:
private static long getChunkCacheSize(IEclipsePreferences node) { double maxSizeMb = node.getDouble(CHUNK_CACHE_SIZE_MB, CHUNK_CACHE_SIZE_MB_DEFAULT); double maxSizePercent = node.getDouble(CHUNK_CACHE_SIZE_PERCENT, CHUNK_CACHE_SIZE_PERCENT_DEFAULT); maxSizePercent = Math.max(1.0, Math.min(100.0, maxSizePercent)); maxSizeMb = Math.max(maxSizeMb, 1.0); long m1= (long) (Runtime.getRuntime().maxMemory() / 100.0 * maxSizePercent); return Math.min(m1, (long) (maxSizeMb * 1024.0 * 1024.0)); }
Source:
<code>public void run(){ try{ ContextManager cm=ContextService.getFactory().newContextManager(); cm.pushContext(ec); ContextService.getFactory().setCurrentContextManager(cm); TabInfoImpl ti=coreInfo[coreCtr]; String version = catalogVersions.get(coreCtr); Properties heapProperties=new Properties(); heapProperties.setProperty("tableDisplayName", ti.getTableName()); heapProperties.setProperty("catalogVersion", version); ExecRow rowTemplate=ti.getCatalogRowFactory().makeEmptyRowForLatestVersion(); <START> long conglomerate=createConglomerate(tc,rowTemplate,heapProperties, 100); <END> ti.setHeapConglomerate(conglomerate); }catch(Exception e){ e.printStackTrace(); StringBuilder strbuf = new StringBuilder("Dictionary Table Failure - exiting "); strbuf.append(coreCtr); SanityManager.THROWASSERT(strbuf.toString()); } }</code><technical_language>a constant</technical_language>

Target:
public void run(){ try{ ContextManager cm=ContextService.getFactory().newContextManager(); cm.pushContext(ec); ContextService.getFactory().setCurrentContextManager(cm); TabInfoImpl ti=coreInfo[coreCtr]; String version = catalogVersions.get(coreCtr); Properties heapProperties=new Properties(); heapProperties.setProperty("tableDisplayName", ti.getTableName()); heapProperties.setProperty("catalogVersion", version); ExecRow rowTemplate=ti.getCatalogRowFactory().makeEmptyRowForLatestVersion(); long conglomerate=createConglomerate(tc,rowTemplate,heapProperties, Conglomerate.Priority.HIGH); ti.setHeapConglomerate(conglomerate); }catch(Exception e){ e.printStackTrace(); StringBuilder strbuf = new StringBuilder("Dictionary Table Failure - exiting "); strbuf.append(coreCtr); SanityManager.THROWASSERT(strbuf.toString()); } }
Source:
<code>private String getLegalNoticeMessage() { ClassLoader classLoader = this.getClass().getClassLoader(); InputStream stream = classLoader.getResourceAsStream(KODEBEAGLE_NOTICE_FILENAME); StringBuilder legalNoticeMessage = new StringBuilder(); BufferedReader reader = null; try { String line; reader = new BufferedReader(new InputStreamReader(stream, ESUtils.UTF_8)); while ((line = reader.readLine()) != null) { legalNoticeMessage.append(line); } } catch (IOException ioe) { ioe.printStackTrace(); } finally { try { if (reader != null) { <START> reader.close(); <END> } } catch (Throwable e) { e.printStackTrace(); } } return String.format(legalNoticeMessage.toString()); }</code><technical_language>bug ? file in issues separate out this PR</technical_language>

Target:
private String getLegalNoticeMessage() { ClassLoader classLoader = this.getClass().getClassLoader(); InputStream stream = classLoader.getResourceAsStream(KODEBEAGLE_NOTICE_FILENAME); StringBuilder legalNoticeMessage = new StringBuilder(); try { String line; BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); if (stream != null) { while ((line = reader.readLine()) != null) { legalNoticeMessage.append(line); } } } catch (IOException e) { e.printStackTrace(); } finally { try { stream.close(); } catch (Throwable e) { e.printStackTrace(); } } return String.format(legalNoticeMessage.toString()); }
Source:
<code>public static boolean isGenotypeInTransitionWithComplement(final Genotype g, final Transition transition) { Utils.nonNull(g, "Genotype cannot be null"); Utils.nonNull(transition, "Transition cannot be null"); <START> final boolean isInTransition = isGenotypeInTransition(g, transition); <END> if (isInTransition) { return true; } final Transition transitionComplement = transition.complement(); return isGenotypeInTransition(g, transitionComplement); }</code><technical_language>This more readable return isGenotypeInTransition(g, transition) || is GenotypeInTransition(g, transition.complement())</technical_language>

Target:
public static boolean isGenotypeInTransitionWithComplement(final Genotype g, final Transition transition) { Utils.nonNull(g, "Genotype cannot be null"); Utils.nonNull(transition, "Transition cannot be null"); return isGenotypeInTransition(g, transition) || isGenotypeInTransition(g, transition.complement()); }
Source:
<code>public void testProcessWhenSharedConfigThenAddVolumeConfig() { <START> List<SharedComponent> sharedComponents = List.of(new SharedComponent("HDFS", "JOURNALNODE")); <END> ReflectionTestUtils.setField(underTest, "sharedComponents", sharedComponents); HostgroupView master1 = new HostgroupView("master1", 1, InstanceGroupType.GATEWAY, 1); HostgroupView master2 = new HostgroupView("master2", 1, InstanceGroupType.GATEWAY, 1); HostgroupView worker = new HostgroupView("worker", 2, InstanceGroupType.CORE, 2); HostgroupView compute = new HostgroupView("compute", 3, InstanceGroupType.CORE, 2); HostgroupView quorum = new HostgroupView("quorum", 3, InstanceGroupType.CORE, 2); setup("input/cb5660.bp", Builder.builder().withHostgroupViews(Set.of(master1, master2, worker, compute, quorum))); underTest.process(templateProcessor, templatePreparator); Map<String, List<ApiClusterTemplateConfig>> roleConfigs = mapRoleConfigs(); List<ApiClusterTemplateConfig> journalNodeBase = roleConfigs.get("hdfs-JOURNALNODE-BASE"); assertEquals(1, journalNodeBase.size()); assertEquals("dfs_journalnode_edits_dir", journalNodeBase.get(0).getName()); assertEquals("/hadoopfs/fs1/journalnode", journalNodeBase.get(0).getValue()); }</code><technical_language>I do test especially covers ZK case</technical_language>

Target:
public void testProcessWhenSharedConfigThenAddVolumeConfig() { List<SharedComponent> sharedComponents = List.of(new SharedComponent("ZOOKEEPER", "SERVER"), new SharedComponent("HDFS", "JOURNALNODE")); ReflectionTestUtils.setField(underTest, "sharedComponents", sharedComponents); HostgroupView master1 = new HostgroupView("master1", 1, InstanceGroupType.GATEWAY, 1); HostgroupView master2 = new HostgroupView("master2", 1, InstanceGroupType.GATEWAY, 1); HostgroupView worker = new HostgroupView("worker", 2, InstanceGroupType.CORE, 2); HostgroupView compute = new HostgroupView("compute", 3, InstanceGroupType.CORE, 2); HostgroupView quorum = new HostgroupView("quorum", 3, InstanceGroupType.CORE, 2); setup("input/cb5660.bp", Builder.builder().withHostgroupViews(Set.of(master1, master2, worker, compute, quorum))); underTest.process(templateProcessor, templatePreparator); Map<String, List<ApiClusterTemplateConfig>> roleConfigs = mapRoleConfigs(); List<ApiClusterTemplateConfig> journalNodeBase = roleConfigs.get("hdfs-JOURNALNODE-BASE"); assertEquals(1, journalNodeBase.size()); assertEquals("dfs_journalnode_edits_dir", journalNodeBase.get(0).getName()); assertEquals("/hadoopfs/fs1/journalnode", journalNodeBase.get(0).getValue()); List<ApiClusterTemplateConfig> zkServerBase = roleConfigs.get("zookeeper-SERVER-BASE"); assertEquals("dataDir", zkServerBase.get(0).getName()); assertEquals("/hadoopfs/fs1/zookeeper", zkServerBase.get(0).getValue()); assertEquals("dataLogDir", zkServerBase.get(1).getName()); assertEquals("/hadoopfs/fs1/zookeeper", zkServerBase.get(1).getValue()); }
Source:
<code>public boolean match(ChangeData object) throws OrmException { final PatchSet patchSet = object.currentPatchSet(db); if (patchSet == null) { return false; } final RevId revision = patchSet.getRevision(); if (revision == null) { return false; } final AnyObjectId objectId = ObjectId.fromString(revision.get()); if (objectId == null) { return false; } Change change = object.change(db); if (change == null) { return false; } final Project.NameKey projectName = change.getProject(); if (projectName == null) { return false; } Arguments args = new Arguments(patchSet, revision, objectId, change, projectName); try { RepoWalk repoWalk = repoWalksByProject.get(projectName); <START> return match(repoWalk.repository, repoWalk.revWalk, args); <END> } catch (RepositoryNotFoundException e) { log.error("Repository \"" + projectName.get() + "\" unknown.", e); } catch (IOException e) { log.error(projectName.get() + " cannot be read as a repository", e); } return false; }</code><technical_language>This is usage of RepoWalksCache show need RevWalk object (not RepoWalk). Change return type of RepoWalksCache.get RevWalk</technical_language>

Target:
public boolean match(ChangeData object) throws OrmException { final PatchSet patchSet = object.currentPatchSet(db); if (patchSet == null) { return false; } final RevId revision = patchSet.getRevision(); if (revision == null) { return false; } final AnyObjectId objectId = ObjectId.fromString(revision.get()); if (objectId == null) { return false; } Change change = object.change(db); if (change == null) { return false; } final Project.NameKey projectName = change.getProject(); if (projectName == null) { return false; } Arguments args = new Arguments(patchSet, revision, objectId, change, projectName); RepoWalk repoWalk = repoWalksCache.repoWalksByProject.get(projectName); return match(repoWalk.repository, repoWalk.revWalk, args); }
Source:
<code>public PersistentModel loadModel(IProject project) { PersistentModel model = this.cache.get(project); if (model == null) { model = readModel(project); if (model != null) { <START> this.cache.put(project, model); <END> } } return model; }</code><technical_language>put a null object in cache if model null. repeated cache misses result in file system again</technical_language>

Target:
public PersistentModel loadModel(IProject project) { return this.modelCache.getUnchecked(project); }
Source:
<code>public void testCreatePayload() { Injector injector = Guice.createInjector(new GsonModule(), new AbstractModule() { @Override protected void configure() { bind(new TypeLiteral<Supplier<URI>>() { }).annotatedWith(Provider.class).toInstance( Suppliers.ofInstance(URI.create(new ProfitBricksProviderMetadata().getEndpoint()))); } <START> }); <END> CreateSnapshotRequestBinder binder = injector.getInstance(CreateSnapshotRequestBinder.class); Volume.Request.CreateSnapshotPayload payload = Volume.Request.createSnapshotBuilder() .dataCenterId("datacenter-id") .volumeId("volume-id") .name("test-snapshot") .description("snapshot desc...") .build(); HttpRequest request = binder.createRequest( HttpRequest.builder().method("POST").endpoint("<LINK_0>").build(), binder.createPayload(payload) ); Multimap<String, String> expectedPayload = HashMultimap.create(); expectedPayload.put("name", "test-snapshot"); expectedPayload.put("description", "snapshot desc..."); assertEquals(request.getEndpoint().getPath(), "/rest/v2/datacenters/datacenter-id/volumes/volume-id/create-snapshot"); assertEquals(request.getPayload().getContentMetadata().getContentType(), MediaType.APPLICATION_FORM_URLENCODED); assertEquals(request.getPayload().getRawContent(), "&" + (new UrlEncodedFormPayload(expectedPayload)).getRawContent()); }</code><technical_language>This needed in binder tests. Create a base test class for binder tests initializes injector variable in a @BeforeClass method, tests focus tests</technical_language>

Target:
public void testCreatePayload() { CreateSnapshotRequestBinder binder = injector.getInstance(CreateSnapshotRequestBinder.class); Volume.Request.CreateSnapshotPayload payload = Volume.Request.createSnapshotBuilder() .dataCenterId("datacenter-id") .volumeId("volume-id") .name("test-snapshot") .description("snapshot desc...") .build(); HttpRequest request = binder.createRequest( HttpRequest.builder().method("POST").endpoint("<LINK_0>").build(), binder.createPayload(payload) ); Multimap<String, String> expectedPayload = HashMultimap.create(); expectedPayload.put("name", "test-snapshot"); expectedPayload.put("description", "snapshot desc..."); assertEquals(request.getEndpoint().getPath(), "/rest/v2/datacenters/datacenter-id/volumes/volume-id/create-snapshot"); assertEquals(request.getPayload().getContentMetadata().getContentType(), MediaType.APPLICATION_FORM_URLENCODED); assertEquals(request.getPayload().getRawContent(), "&" + (new UrlEncodedFormPayload(expectedPayload)).getRawContent()); }
Source:
<code>public String getContactName() { if (this.contact == null) return null; StringBuilder sb = new StringBuilder(32); if (this.contact.getFirstName() != null) { sb.append(this.contact.getFirstName()); } if (this.contact.getLastName() != null) { sb.append(" "); sb.append(this.contact.getLastName()); } if (this.contact.getOrganization() != null) { if (sb.length() > 0) <START> sb.append(","); <END> sb.append(" "); sb.append(this.contact.getOrganization()); } return sb.toString().trim(); }</code><technical_language>space line added this append. cleaned trim end in current code, space is needed if comma is needed</technical_language>

Target:
public String getContactName() { if (this.contact == null) return null; StringBuilder sb = new StringBuilder(32); if (this.contact.getFirstName() != null) { sb.append(this.contact.getFirstName()); } if (this.contact.getLastName() != null) { sb.append(" "); sb.append(this.contact.getLastName()); } if (this.contact.getOrganization() != null) { if (sb.length() > 0) sb.append(", "); sb.append(this.contact.getOrganization()); } return sb.toString().trim(); }
Source:
<code>private void initializeLocationProviders() { LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); mockLocationProviders.addAll(createMockProviders(locationManager)); <START> if (PlayServicesHelpers.isAvailable(this)) { <END> Log.d(TAG, "Adding FusedLocationProvider"); mockLocationProviders.add(createFusedLocationProvider()); } Log.d(TAG, String.format("Created mock providers: %s", mockLocationProviders.toString())); }</code><technical_language>is guaranteed this method is called once? IMHO safer perform clear mockLocationProviders</technical_language>

Target:
private void initializeLocationProviders() { LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); mockLocationProviders.clear(); mockLocationProviders.addAll(createMockProviders(locationManager)); if (PlayServicesHelpers.isAvailable(this)) { Log.d(TAG, "Adding FusedLocationProvider"); mockLocationProviders.add(createFusedLocationProvider()); } Log.d(TAG, String.format("Created mock providers: %s", mockLocationProviders.toString())); }
Source:
<code>private List<ICommitMessageProvider> getCommitMessageProviders() throws CoreException { List<ICommitMessageProvider> providers = new ArrayList<>(); IExtensionRegistry registry = Platform.getExtensionRegistry(); IConfigurationElement[] configs = registry .getConfigurationElementsFor(COMMIT_MESSAGE_PROVIDER_ID); for (IConfigurationElement config : configs) { <START> Object provider; <END> try { provider = config.createExecutableExtension("class"); if (provider instanceof ICommitMessageProvider) { providers.add((ICommitMessageProvider) provider); } else { Activator.logError( UIText.CommitDialog_WrongTypeOfCommitMessageProvider, null); } } catch (CoreException | InvalidRegistryObjectException e) { String contributorName; try { contributorName = config.getDeclaringExtension() .getContributor().getName(); } catch (InvalidRegistryObjectException e1) { contributorName = ""; } Activator.logError( NLS.bind( UIText.CommitDialog_ErrorCreatingCommitMessageProvider, contributorName), e); } } return providers; }</code><technical_language>Add here: String contributorName = "<unknown>";</technical_language>

Target:
private List<ICommitMessageProvider> getCommitMessageProviders() throws CoreException { List<ICommitMessageProvider> providers = new ArrayList<>(); IExtensionRegistry registry = Platform.getExtensionRegistry(); IConfigurationElement[] configs = registry .getConfigurationElementsFor(COMMIT_MESSAGE_PROVIDER_ID); for (IConfigurationElement config : configs) { Object provider; String contributorName = "<unknown"; try { contributorName = config.getDeclaringExtension() .getContributor().getName(); provider = config.createExecutableExtension("class"); if (provider instanceof ICommitMessageProvider) { providers.add((ICommitMessageProvider) provider); } else { Activator.logError( UIText.CommitDialog_WrongTypeOfCommitMessageProvider, null); } } catch (CoreException | InvalidRegistryObjectException e) { Activator.logError( MessageFormat.format( UIText.CommitDialog_ErrorCreatingCommitMessageProvider, contributorName), e); } } return providers; }
Source:
<code>public void removeFieldFile (String fieldInode, String contentInode, PageMode mode) { String velocityRootPath = VelocityUtil.getVelocityRootPath(); velocityRootPath += java.io.File.separator; String folderPath = mode.name() + java.io.File.separator; String filePath=folderPath + contentInode + "_" + fieldInode + "." + VelocityType.FIELD.fileExtension; java.io.File f = new java.io.File(velocityRootPath + filePath); <START> f.delete(); <END> DotResourceCache vc = CacheLocator.getVeloctyResourceCache(); vc.remove(ResourceManager.RESOURCE_TEMPLATE + filePath ); }</code><technical_language>![MAJOR](<LINK_0> 'Severity: MAJOR') "java.nio.Files#delete" for messages error conditions. [![rule](<LINK_3>](<LINK_4> ![MINOR](<LINK_1> 'Severity: MINOR') Do "boolean" returned "delete". [![rule](<LINK_3>](<LINK_2></technical_language>

Target:
public void removeFieldFile (String fieldInode, String contentInode, PageMode mode) { }
Source:
<code>public void touch() throws Exception { final String foo1 = "foo1"; long reply = jedis.touch(foo1, "foo2", "foo3"); assertEquals(0, reply); jedis.set(foo1, "bar1"); <START> await().atMost(2, TimeUnit.SECONDS).until(jedisTargetIsIdle(foo1)); <END> assertTrue(jedis.objectIdletime("foo1") > 0); reply = jedis.touch("foo1"); assertEquals(1, reply); assertTrue(jedis.objectIdletime("foo1") == 0); reply = jedis.touch("foo1", "foo2", "foo3"); assertEquals(1, reply); jedis.set("foo2", "bar2"); jedis.set("foo3", "bar3"); reply = jedis.touch("foo1", "foo2", "foo3"); assertEquals(3, reply); reply = jedis.touch(bfoo1, bfoo2, bfoo3); assertEquals(0, reply); jedis.set(bfoo1, bbar1); await().atMost(2, TimeUnit.SECONDS).until(jedisTargetIsIdle(bfoo1)); assertTrue(jedis.objectIdletime(bfoo1) > 0); reply = jedis.touch(bfoo1); assertEquals(1, reply); assertTrue(jedis.objectIdletime(bfoo1) == 0); reply = jedis.touch(bfoo1, bfoo2, bfoo3); assertEquals(1, reply); jedis.set(bfoo2, bbar2); jedis.set(bfoo3, bbar3); reply = jedis.touch(bfoo1, bfoo2, bfoo3); assertEquals(3, reply); }</code><technical_language>idea is wait for 1 second. 2000ms is safe. Is 2 seconds safe here</technical_language>

Target:
public void touch() throws Exception { final String foo1 = "foo1"; long reply = jedis.touch(foo1, "foo2", "foo3"); assertEquals(0, reply); jedis.set(foo1, "bar1"); AwaitilityUtils.waitFor(2000); assertTrue(jedis.objectIdletime("foo1") > 0); reply = jedis.touch("foo1"); assertEquals(1, reply); assertTrue(jedis.objectIdletime("foo1") == 0); reply = jedis.touch("foo1", "foo2", "foo3"); assertEquals(1, reply); jedis.set("foo2", "bar2"); jedis.set("foo3", "bar3"); reply = jedis.touch("foo1", "foo2", "foo3"); assertEquals(3, reply); reply = jedis.touch(bfoo1, bfoo2, bfoo3); assertEquals(0, reply); jedis.set(bfoo1, bbar1); AwaitilityUtils.waitFor(2000); assertTrue(jedis.objectIdletime(bfoo1) > 0); reply = jedis.touch(bfoo1); assertEquals(1, reply); assertTrue(jedis.objectIdletime(bfoo1) == 0); reply = jedis.touch(bfoo1, bfoo2, bfoo3); assertEquals(1, reply); jedis.set(bfoo2, bbar2); jedis.set(bfoo3, bbar3); reply = jedis.touch(bfoo1, bfoo2, bfoo3); assertEquals(3, reply); }
Source:
<code>protected void buildVmDrives() { Map<String, String>[] drives = new Map[vm.getDiskMap().size()]; int ideCount = 0, pciCount = 0; int i = 0; List<DiskImage> diskImages = getSortedDiskImages(); for (DiskImage disk : diskImages) { <START> VmDevice vmDevice = <END> DbFacade.getInstance().getVmDeviceDAO().get(new VmDeviceId(disk.getId(), vm.getId())); Map<String, String> drive = new HashMap<String, String>(); drive.put("domainID", disk.getstorage_ids().get(0).toString()); drive.put("poolID", disk.getstorage_pool_id().toString()); drive.put("volumeID", disk.getId().toString()); drive.put("imageID", disk.getimage_group_id().toString()); drive.put("format", disk.getvolume_format().toString() .toLowerCase()); drive.put("propagateErrors", disk.getpropagate_errors().toString() .toLowerCase()); switch (disk.getdisk_interface()) { case IDE: try { drive.put("if", "ide"); drive.put("index", String.valueOf(ideIndexSlots[ideCount])); ideCount++; } catch (IndexOutOfBoundsException e) { log.errorFormat("buildVmDrives throws IndexOutOfBoundsException for index {0}, IDE slots are limited to 4.", ideCount); throw e; } break; case VirtIO: drive.put("if", "virtio"); drive.put("index", String.valueOf(pciCount)); drive.put("boot", String.valueOf(disk.getboot()).toLowerCase()); pciCount++; break; default: logUnsupportedInterfaceType(); break; } drives[i] = drive; i++; } createInfo.add("drives", drives); }</code><technical_language>This variable anywhere, is this DB access requires</technical_language>

Target:
protected void buildVmDrives() { Map<String, String>[] drives = new Map[vm.getDiskMap().size()]; int ideCount = 0, pciCount = 0; int i = 0; List<DiskImage> diskImages = getSortedDiskImages(); for (DiskImage disk : diskImages) { Map<String, String> drive = new HashMap<String, String>(); drive.put("domainID", disk.getstorage_ids().get(0).toString()); drive.put("poolID", disk.getstorage_pool_id().toString()); drive.put("volumeID", disk.getId().toString()); drive.put("imageID", disk.getimage_group_id().toString()); drive.put("format", disk.getvolume_format().toString() .toLowerCase()); drive.put("propagateErrors", disk.getpropagate_errors().toString() .toLowerCase()); switch (disk.getdisk_interface()) { case IDE: try { drive.put("if", "ide"); drive.put("index", String.valueOf(ideIndexSlots[ideCount])); ideCount++; } catch (IndexOutOfBoundsException e) { log.errorFormat("buildVmDrives throws IndexOutOfBoundsException for index {0}, IDE slots are limited to 4.", ideCount); throw e; } break; case VirtIO: drive.put("if", "virtio"); drive.put("index", String.valueOf(pciCount)); drive.put("boot", String.valueOf(disk.getboot()).toLowerCase()); pciCount++; break; default: logUnsupportedInterfaceType(); break; } drives[i] = drive; i++; } createInfo.add("drives", drives); }
Source:
<code>public Scene getCurrentScene() { if (currentScene == null && project != null) { currentScene = project.getDefaultScene(); } <START> return currentScene; <END> }</code><technical_language>happen null is returned current scene = null project = null? this a problem</technical_language>

Target:
public Scene getCurrentScene() { if (currentScene == null) { currentScene = project.getDefaultScene(); } return currentScene; }
Source:
<code>public static int getItemIcon(Context appContext, String itemName) { <START> itemName = itemName.replaceFirst("itemdex_", ""); <END> return appContext.getResources() .getIdentifier("item_" + MyApplication.toId(itemName), "drawable", appContext.getPackageName()); }</code><technical_language>This throw NullPointerException. want unnecessary crash if avoid</technical_language>

Target:
public static int getItemIcon(Context appContext, String itemName) { if (appContext != null && itemName != null) { return appContext.getResources() .getIdentifier("item_" + MyApplication.toId(itemName), "drawable", appContext.getPackageName()); } else { return R.drawable.sprites_0; } }
Source:
<code>protected void markImagesIllegalIfNotInDb(VM vm) { List<DiskImage> imagesInDb = <START> getDiskImageDao().getAllSnapshotsForVmSnapshot(getParameters().getSnapshotSourceId()); <END> for (DiskImage fromConfigImg : vm.getImages()) { if (!imagesInDb.contains(fromConfigImg)) { fromConfigImg.setimageStatus(ImageStatus.ILLEGAL); } } }</code><technical_language>more robust check IDs, reduce possibility of bugs</technical_language>

Target:
protected void markImagesIllegalIfNotInDb(VM vm) { List<DiskImage> imagesInDb = getDiskImageDao().getAllSnapshotsForVmSnapshot(getParameters().getSnapshotSourceId()); Map<Guid, DiskImage> imagesInDbMap = ImagesHandler.getDiskImagesByIdMap(imagesInDb); for (DiskImage fromConfigImg : vm.getImages()) { if (!imagesInDbMap.containsKey(fromConfigImg.getId())) { fromConfigImg.setimageStatus(ImageStatus.ILLEGAL); } } }
Source:
<code>public <T> List<T> queryList(String sql) throws Exception { List<T> resultList = Lists.newArrayList(); ResultSet rs = executeQuery(sql); while (rs.next()) { resultList.add((T) rs.getObject(1)); } <START> rs.close(); <END> return resultList; }</code><technical_language>I a try-with-resources better, in case raise exception for instance</technical_language>

Target:
public <T> List<T> queryList(String sql) throws Exception { List<T> resultList = Lists.newArrayList(); try (ResultSet rs = executeQuery(sql)) { while (rs.next()) { resultList.add((T) rs.getObject(1)); } } return resultList; }