auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>void asyncProcessLevelNodes( final String path, final Processor<String> processor, final AsyncCallback.VoidCallback finalCb, final Object context, final int successRc, final int failureRc) { zk.sync(path, new AsyncCallback.VoidCallback() { @Override public void processResult(int rc, String path, Object ctx) { <START> if (rc == Code.NONODE.intValue()) { <END> finalCb.processResult(successRc, null, context); return; } else if (rc != Code.OK.intValue()) { LOG.error("Error syncing path " + path + " when getting its chidren: ", KeeperException.create(KeeperException.Code.get(rc), path)); finalCb.processResult(failureRc, null, context); return; } zk.getChildren(path, false, new AsyncCallback.ChildrenCallback() { @Override public void processResult(int rc, String path, Object ctx, List<String> levelNodes) { if (rc == Code.NONODE.intValue()) { finalCb.processResult(successRc, null, context); return; } else if (rc != Code.OK.intValue()) { LOG.error("Error polling hash nodes of " + path, KeeperException.create(KeeperException.Code.get(rc), path)); finalCb.processResult(failureRc, null, context); return; } AsyncListProcessor<String> listProcessor = new AsyncListProcessor<String>(scheduler); listProcessor.process(levelNodes, processor, finalCb, context, successRc, failureRc); } }, null); } }, null); }</code><technical_language>commits related "decouple metaformat cmd". I suggest a separate issue</technical_language>

Target:
void asyncProcessLevelNodes( final String path, final Processor<String> processor, final AsyncCallback.VoidCallback finalCb, final Object context, final int successRc, final int failureRc) { zk.sync(path, new AsyncCallback.VoidCallback() { @Override public void processResult(int rc, String path, Object ctx) { if (rc != Code.OK.intValue()) { LOG.error("Error syncing path " + path + " when getting its chidren: ", KeeperException.create(KeeperException.Code.get(rc), path)); finalCb.processResult(failureRc, null, context); return; } zk.getChildren(path, false, new AsyncCallback.ChildrenCallback() { @Override public void processResult(int rc, String path, Object ctx, List<String> levelNodes) { if (rc != Code.OK.intValue()) { LOG.error("Error polling hash nodes of " + path, KeeperException.create(KeeperException.Code.get(rc), path)); finalCb.processResult(failureRc, null, context); return; } AsyncListProcessor<String> listProcessor = new AsyncListProcessor<String>(scheduler); listProcessor.process(levelNodes, processor, finalCb, context, successRc, failureRc); } }, null); } }, null); }
Source:
<code>@Override public boolean process(Set<? extends TypeElement> types, RoundEnvironment env) { try { if (!env.processingOver()) { for (Element e : env.getElementsAnnotatedWith(Module.class)) { delayedModuleNames.add(e.asType().toString()); } return true; } <START> Set<Element> modules = new HashSet<Element>(); <END> for (String moduleName : delayedModuleNames) { modules.add(processingEnv.getElementUtils().getTypeElement(moduleName)); } for (Element element : modules) { Map<String, Object> annotation = CodeGen.getAnnotation(Module.class, element); if (!annotation.get("complete").equals(Boolean.TRUE)) { continue; } TypeElement moduleType = (TypeElement) element; Map<String, Binding<?>> bindings = processCompleteModule(moduleType); writeDotFile(moduleType, bindings); delayedModuleNames.remove(element.asType().toString()); } } catch (IOException e) { error("Graph processing failed: " + e); } return true; }</code><technical_language>nit: LinkedHashSet, HashSet. is worse a bug reproduce fails if iteration order is so</technical_language>

Target:
@Override public boolean process(Set<? extends TypeElement> types, RoundEnvironment env) { try { if (!env.processingOver()) { for (Element e : env.getElementsAnnotatedWith(Module.class)) { delayedModuleNames.add(e.asType().toString()); } return true; } Set<Element> modules = new LinkedHashSet<Element>(); for (String moduleName : delayedModuleNames) { modules.add(processingEnv.getElementUtils().getTypeElement(moduleName)); } for (Element element : modules) { Map<String, Object> annotation = CodeGen.getAnnotation(Module.class, element); if (!annotation.get("complete").equals(Boolean.TRUE)) { continue; } TypeElement moduleType = (TypeElement) element; Map<String, Binding<?>> bindings = processCompleteModule(moduleType); writeDotFile(moduleType, bindings); } } catch (IOException e) { error("Graph processing failed: " + e); } return true; }
Source:
<code>protected void initNode(Node node) { node.setBaseTime(TimeUnit.MILLISECONDS.toMicros(System.currentTimeMillis())); <START> } <END></code><technical_language>This needs System.nanoTime converted microseconds. loose precision</technical_language>

Target:
protected void initNode(Node node) { node.setBaseTime(TimeUnit.NANOSECONDS.toMicros(System.nanoTime())); }
Source:
<code>private List<PotentialAssignment> generateAssignmentsFromTypeAlone(ParameterSignature unassigned) { Class<?> paramType = unassigned.getType(); FromDataPoints fromDataPoints = unassigned.getAnnotation(FromDataPoints.class); if (fromDataPoints == null) { if (paramType.isEnum()) { return new EnumSupplier(paramType).getValueSources(unassigned); } else if (paramType.equals(Boolean.class) || paramType.equals(boolean.class)) { return new BooleanSupplier().getValueSources(unassigned); } } <START> return emptyList(); <END> }</code><technical_language>For symmetry nice else suggestion } else { return emptyList(); }</technical_language>

Target:
private List<PotentialAssignment> generateAssignmentsFromTypeAlone(ParameterSignature unassigned) { Class<?> paramType = unassigned.getType(); FromDataPoints fromDataPoints = unassigned.getAnnotation(FromDataPoints.class); if (fromDataPoints == null) { if (paramType.isEnum()) { return new EnumSupplier(paramType).getValueSources(unassigned); } else if (paramType.equals(Boolean.class) || paramType.equals(boolean.class)) { return new BooleanSupplier().getValueSources(unassigned); } } else { return emptyList(); } }
Source:
<code>public static <TClass, TAnnotation extends Annotation> void scanClasspath(Class<TClass> superClass, Class<TAnnotation> annotationClass, String requirePackage, Consumer<Class<? extends TClass>> consumer) { FastClasspathScanner fcs; if (requirePackage != null) { fcs = new FastClasspathScanner(requirePackage); } else { fcs = new FastClasspathScanner(); } ScanResult scanResults = fcs.scan(); List<String> assignableFrom; if (superClass.isInterface()) { assignableFrom = scanResults.getNamesOfClassesImplementing(superClass.getName()); } else { assignableFrom = scanResults.getNamesOfSubclassesOf(superClass.getName()); } List<String> matches = scanResults.getNamesOfClassesWithAnnotation(annotationClass.getName()); if (assignableFrom.size() > 0) { matches.retainAll(assignableFrom); } log.debug("Found " + matches.size() + " classes with annotation '" + annotationClass.getName() + "' and super class '" + superClass.getName() + "'"); for (String className : matches) { Class<?> clazz; try { clazz = Class.forName(className); consumer.accept((Class<? extends TClass>) clazz); } catch (Throwable e) { log.trace("Cannot load class " + className, e); <START> return; <END> } } }</code><technical_language>I guess this change in non-intentional</technical_language>

Target:
public static <TClass, TAnnotation extends Annotation> void scanClasspath(Class<TClass> superClass, Class<TAnnotation> annotationClass, String requirePackage, Consumer<Class<? extends TClass>> consumer) { FastClasspathScanner fcs; if (requirePackage != null) { fcs = new FastClasspathScanner(requirePackage); } else { fcs = new FastClasspathScanner(); } ScanResult scanResults = fcs.scan(); List<String> assignableFrom = Collections.EMPTY_LIST; if (superClass != null) { if (superClass.isInterface()) { assignableFrom = scanResults.getNamesOfClassesImplementing(superClass.getName()); } else { assignableFrom = scanResults.getNamesOfSubclassesOf(superClass.getName()); } } List<String> matches = scanResults.getNamesOfClassesWithAnnotation(annotationClass.getName()); if (superClass != null) { matches.retainAll(assignableFrom); log.debug("Found " + matches.size() + " classes with annotation '" + annotationClass.getName() + "' and super class '" + superClass.getName() + "'"); } else { log.debug("Found " + matches.size() + " classes with annotation '" + annotationClass.getName() + "'"); } for (String className : matches) { Class<?> clazz; try { clazz = Class.forName(className); consumer.accept((Class<? extends TClass>) clazz); } catch (Throwable e) { log.error("Cannot load class " + className, e); continue; } } }
Source:
<code>public CompilerOptions getCompilerOptions() { final CompilerOptions options = new CompilerOptions(); options.setClosurePass(true); options.setCheckGlobalNamesLevel(CheckLevel.ERROR); options.setWarningLevel(DiagnosticGroups.DUPLICATE_VARS, CheckLevel.ERROR); <START> options.setLanguage(CompilerOptions.LanguageMode.ECMASCRIPT6_TYPED); <END> options.setLanguageOut(CompilerOptions.LanguageMode.NO_TRANSPILE); options.setWrapGoogModulesForWhitespaceOnly(false); options.setTrustedStrings(true); options.setPreferSingleQuotes(true); options.skipAllCompilerPasses(); setIdeMode(options); return options; }</code><technical_language>This work internally, FYI. :-)</technical_language>

Target:
public CompilerOptions getCompilerOptions() { final CompilerOptions options = new CompilerOptions(); options.setClosurePass(true); options.setCheckGlobalNamesLevel(CheckLevel.ERROR); options.setWarningLevel(DiagnosticGroups.DUPLICATE_VARS, CheckLevel.ERROR); options.setLanguage(CompilerOptions.LanguageMode.ECMASCRIPT6); options.setLanguageOut(CompilerOptions.LanguageMode.NO_TRANSPILE); options.setWrapGoogModulesForWhitespaceOnly(false); options.setTrustedStrings(true); options.setPreferSingleQuotes(true); options.skipAllCompilerPasses(); setIdeMode(options); return options; }
Source:
<code>public void handleAction(ActionParameters params) throws ActionException { JSONObject jsonPayload = params.getHttpParamAsJSON("featureData"); OskariLayer layer = getLayer(jsonPayload.optString("layerId")); <START> if (!canEdit(layer, params.getUser())) { <END> throw new ActionDeniedException("User doesn't have edit permission for layer: " + layer.getId()); } final WFSLayerConfiguration wfsMetadata = getWFSConfiguration(layer.getId()); final String wfstMessage = createWFSTMessage(jsonPayload, layer, wfsMetadata); LOG.debug("Inserting feature to service at", layer.getUrl(), "with payload", wfstMessage); final String responseString = postPayload(layer, wfstMessage); final String updatedFeatureId = parseFeatureIdFromResponse(responseString); flushLayerTilesCache(layer.getId()); ResponseHelper.writeResponse(params, JSONHelper.createJSONObject("fid", updatedFeatureId)); }</code><technical_language>DeleteFeatureHandler checks params.requireLoggedInUser(); prior calling this, I prefer</technical_language>

Target:
public void handleAction(ActionParameters params) throws ActionException { params.requireLoggedInUser(); JSONObject jsonPayload = params.getHttpParamAsJSON("featureData"); OskariLayer layer = getLayer(jsonPayload.optString("layerId")); if (!canEdit(layer, params.getUser())) { throw new ActionDeniedException("User doesn't have edit permission for layer: " + layer.getId()); } final WFSLayerConfiguration wfsMetadata = getWFSConfiguration(layer.getId()); final String wfstMessage = createWFSTMessage(jsonPayload, layer, wfsMetadata); LOG.debug("Inserting feature to service at", layer.getUrl(), "with payload", wfstMessage); final String responseString = postPayload(layer, wfstMessage); final String updatedFeatureId = parseFeatureIdFromResponse(responseString); flushLayerTilesCache(layer.getId()); ResponseHelper.writeResponse(params, JSONHelper.createJSONObject("fid", updatedFeatureId)); }
Source:
<code>private void runThread(CountDownLatch latch, VDSReturnValue value, FencingExecutor executor, FenceAgentOrder order, boolean succeeded) { value = executor.Fence(order); if (value.getSucceeded()) { executor = new FencingExecutor(getVds(), FenceActionType.Status); <START> succeeded = waitForStatus(getVds().getvds_name(), getParameters().getAction(), order); <END> latch.countDown(); } }</code><technical_language>general : countdown is in finally block avoid case in wait</technical_language>

Target:
private void runThread(CountDownLatch latch, VDSReturnValue value, FencingExecutor executor, FenceAgentOrder order, boolean succeeded) { value = executor.Fence(order); if (value.getSucceeded()) { try { executor = new FencingExecutor(getVds(), FenceActionType.Status); succeeded = waitForStatus(getVds().getvds_name(), getParameters().getAction(), order); } finally { latch.countDown(); } } }
Source:
<code>public WeldSEBeanDeploymentArchive build() { if (beansXml == null) { parseBeansXml(); } <START> return new WeldSEBeanDeploymentArchive(id, classes, beansXml); <END> }</code><technical_language>simply return new WeldSEBeanDeploymentArchive(id, classes, getParsedBeansXml()); leave out check above</technical_language>

Target:
public WeldSEBeanDeploymentArchive build() { return new WeldSEBeanDeploymentArchive(id, classes, getParsedBeansXml()); }
Source:
<code>public void prepare(Map map, TopologyContext topologyContext, OutputCollector outputCollector) { try { this.collector = outputCollector; synchronized (EsAbstractBolt.class) { if (client == null) { client = new StormEsClient(esConfig); } } } catch (Exception e) { <START> logger.warn("unable to initialize ESBolt ", e); <END> } }</code><technical_language>fail fast</technical_language>

Target:
public void prepare(Map map, TopologyContext topologyContext, OutputCollector outputCollector) { try { this.collector = outputCollector; synchronized (EsAbstractBolt.class) { if (client == null) { client = new StormEsClient(esConfig); } } } catch (Exception e) { throw new RuntimeException("unable to initialize EsBolt ", e); } }
Source:
<code>public void updatesChangeTransactionStatus() throws Exception { PaymentRequestEntity paymentRequest = PaymentRequestEntityFixture.aValidPaymentRequestEntity() .withTransactions(aChargeTransactionEntity().withStatus(ChargeStatus.CREATED).build()) .build(); when(mockPaymentRequestDao.findByExternalId(someExternalId)).thenReturn(Optional.of(paymentRequest)); <START> ChargeStatus newChargeStatus = ChargeStatus.ENTERING_CARD_DETAILS; <END> new StatusUpdater(mockPaymentRequestDao).updateChargeTransactionStatus(someExternalId, newChargeStatus); assertThat(paymentRequest.getChargeTransaction().getStatus(), is(newChargeStatus)); }</code><technical_language>convinced this variable is buying anything; I clear if repeat ENTERING_CARD_DETAILS time</technical_language>

Target:
public void updatesChangeTransactionStatus() throws Exception { PaymentRequestEntity paymentRequest = PaymentRequestEntityFixture.aValidPaymentRequestEntity() .withTransactions(aChargeTransactionEntity().withStatus(ChargeStatus.CREATED).build()) .build(); when(mockPaymentRequestDao.findByExternalId(SOME_EXTERNAL_ID)).thenReturn(Optional.of(paymentRequest)); ChargeStatus newChargeStatus = ENTERING_CARD_DETAILS; new StatusUpdater(mockPaymentRequestDao).updateChargeTransactionStatus(SOME_EXTERNAL_ID, newChargeStatus); assertThat(paymentRequest.getChargeTransaction().getStatus(), is(newChargeStatus)); }
Source:
<code>public BasePoseSubsystem(WPIFactory factory, XPropertyManager propManager) { log.info("Creating"); imu = factory.getGyro(ImuType.navX); currentHeadingProp = propManager.createEphemeralProperty("CurrentHeading", 0.0); lastImuHeading = imu.getYaw(); currentHeading = new ContiguousHeading(FACING_AWAY_FROM_DRIVERS); currentPitch = propManager.createEphemeralProperty("CurrentPitch", 0.0); currentRoll = propManager.createEphemeralProperty("CurrentRoll", 0.0); <START> leftDriveDistance = propManager.createEphemeralProperty("LeftDriveDistance", 0.0); <END> rightDriveDistance = propManager.createEphemeralProperty("RightDriveDistance", 0.0); totalDistanceX = propManager.createEphemeralProperty("TotalDistanceX", 0.0); totalDistanceY = propManager.createEphemeralProperty("TotalDistanceY", 0.0); rioRotated = propManager.createPersistentProperty("RioRotated", false); inherentRioPitch = propManager.createPersistentProperty("InherentRioPitch", 0.0); inherentRioRoll = propManager.createPersistentProperty("InherentRioRoll", 0.0); }</code><technical_language>Spacing, caps</technical_language>

Target:
public BasePoseSubsystem(WPIFactory factory, XPropertyManager propManager) { log.info("Creating"); imu = factory.getGyro(ImuType.navX); currentHeadingProp = propManager.createEphemeralProperty("CurrentHeading", 0.0); currentHeading = new ContiguousHeading(0); setCurrentHeading(FACING_AWAY_FROM_DRIVERS); currentPitch = propManager.createEphemeralProperty("Current pitch", 0.0); currentRoll = propManager.createEphemeralProperty("Current roll", 0.0); leftDriveDistance = propManager.createEphemeralProperty("Left drive distance", 0.0); rightDriveDistance = propManager.createEphemeralProperty("Right drive distance", 0.0); totalDistanceX = propManager.createEphemeralProperty("Total distance X", 0.0); totalDistanceY = propManager.createEphemeralProperty("Total distance Y", 0.0); rioRotated = propManager.createPersistentProperty("RIO rotated", false); inherentRioPitch = propManager.createPersistentProperty("Inherent RIO pitch", 0.0); inherentRioRoll = propManager.createPersistentProperty("Inherent RIO roll", 0.0); }
Source:
<code>protected void applyMigrationTasks(final ImportItem importItem, final IProgressMonitor monitor) { try { getItem(importItem).ifPresent(connectionItem -> { final TaCoKitConfigurationModel configuration = new TaCoKitConfigurationModel(connectionItem.getConnection()); if (configuration.needsMigration()) { try { manager().migrate(configuration, monitor); importItem.setProperty(connectionItem.getProperty()); final IProxyRepositoryFactory factory = ProxyRepositoryFactory.getInstance(); factory.save(connectionItem); final String version = RelationshipItemBuilder.LATEST_VERSION; <START> RepositoryUpdateManager.updateDBConnection(connectionItem, version, false, false); <END> } catch (Exception e) { logError(e); } } }); } catch (Exception e) { logError(e); } }</code><technical_language>I remember RepositoryUpdateManager.updateDBConnection(connectionItem, version, false, false); work migration need move TaCoKitProcessMigrator#postImport</technical_language>

Target:
protected void applyMigrationTasks(final ImportItem importItem, final IProgressMonitor monitor) { try { getItem(importItem).ifPresent(connectionItem -> { final TaCoKitConfigurationModel configuration = new TaCoKitConfigurationModel(connectionItem.getConnection()); if (configuration.needsMigration()) { try { manager().migrate(configuration, monitor); importItem.setProperty(connectionItem.getProperty()); final IProxyRepositoryFactory factory = ProxyRepositoryFactory.getInstance(); factory.save(connectionItem); } catch (Exception e) { logError(e); } } }); } catch (Exception e) { logError(e); } }
Source:
<code>public final CTFClock getClock() { if (clocks.size() == 1) { if (singleClock == null) { singleClock = clocks.get(clocks.keySet().toArray()[0]); if (singleClock.getProperty(OFFSET) != null) { singleOffset = (Long) getClock().getProperty(OFFSET); } else { singleClock.addAttribute(OFFSET, 0); } if (singleClock.getProperty(FREQ) != null) { <START> singleScale = 1000000000.0 / ((Long) singleClock.getProperty(FREQ)).doubleValue(); <END> antiScale = 1.0 / singleScale; } } return singleClock; } return null; }</code><technical_language>a long casted a double, a Long, a double for division? Rounding errors galore! ;)</technical_language>

Target:
public final CTFClock getClock() { if (clocks.size() == 1) { singleClock = clocks.get(clocks.keySet().iterator().next()); return singleClock; } return null; }
Source:
<code>public Binary completeHttpUpload(String uploadToken) throws RepositoryException { return sd.perform(new ReadOperation<Binary>("completeHttpUpload") { @Nonnull @Override public Binary perform() throws RepositoryException { HttpBlobProvider httpBlobProvider = getHttpBlobProvider(); if (httpBlobProvider == null) { throw new RepositoryException("HTTP binary upload not supported"); } Blob blob = httpBlobProvider.completeHttpUpload(uploadToken); if (blob == null) { throw new RepositoryException("HTTP binary upload could not be completed"); } <START> ValueFactoryImpl vf = (ValueFactoryImpl) sessionContext.getValueFactory(); <END> return vf.createBinary(blob); } }); }</code><technical_language>@Oak committers: sense for SessionContext.getValueFactory() return ValueFactoryImpl right away, need cast? SessionContext creates a ValueFactoryImpl in constructor, AFAICS SessionContext is internal object required stick API interfaces (but I missing something). Alternatively, add a new interface BlobValueFactory ValueFactoryImpl implement, provide Binary createBinary(Blob) String getBlobId(Binary) (used in getHttpDownloadURL()).</technical_language>

Target:
public Binary completeHttpUpload(String uploadToken) throws RepositoryException { return sd.perform(new ReadOperation<Binary>("completeHttpUpload") { @Nonnull @Override public Binary perform() throws RepositoryException { HttpBlobProvider httpBlobProvider = getHttpBlobProvider(); if (httpBlobProvider == null) { throw new RepositoryException("HTTP binary upload not supported"); } Blob blob; try { blob = httpBlobProvider.completeHttpUpload(uploadToken); } catch (IllegalArgumentException e) { throw new InvalidHttpUploadTokenException(e); } if (blob == null) { throw new RepositoryException("HTTP binary upload could not be completed"); } ValueFactoryImpl vf = (ValueFactoryImpl) sessionContext.getValueFactory(); return vf.createBinary(blob); } }); }
Source:
<code>@Override public void lock() { <START> delegate.readLock().lock(); <END> inc(); }</code><technical_language>I understand in other methods super.{method} used</technical_language>

Target:
@Override public void lock() { super.lock(); inc(); }
Source:
<code>public SimpleFeatureCollection parse(File file, CoordinateReferenceSystem sourceCRS, CoordinateReferenceSystem targetCRS) throws ServiceException { OGRDataStoreFactory factory = new BridjOGRDataStoreFactory(); Map<String, String> connectionParams = new HashMap<String, String>(); connectionParams.put("DriverName", "MapInfo File"); connectionParams.put("DatasourceName", file.getAbsolutePath()); DataStore store = null; try { store = factory.createDataStore(connectionParams); String typeName = store.getTypeNames()[0]; SimpleFeatureSource source = store.getFeatureSource(typeName); CoordinateReferenceSystem crs = source.getSchema() .getGeometryDescriptor() .getCoordinateReferenceSystem(); if (crs != null) { sourceCRS = crs; } if (sourceCRS == null) { <START> throw new ServiceException("Failed to parse MIF", JSONHelper.createJSONObject("cause", "no_source_crs")); <END> } return FeatureCollectionParsers.read(source, sourceCRS, targetCRS); } catch (Exception e) { throw new ServiceException("Failed to parse MIF", e); } finally { if (store != null) { store.dispose(); } } }</code><technical_language>move this check FeatureCollectionParsers.read() function? checks sourceCRS null getTransform() handle invalid/unkown crs case</technical_language>

Target:
public SimpleFeatureCollection parse(File file, CoordinateReferenceSystem sourceCRS, CoordinateReferenceSystem targetCRS) throws ServiceException { OGRDataStoreFactory factory = new BridjOGRDataStoreFactory(); Map<String, String> connectionParams = new HashMap<String, String>(); connectionParams.put("DriverName", "MapInfo File"); connectionParams.put("DatasourceName", file.getAbsolutePath()); DataStore store = null; try { store = factory.createDataStore(connectionParams); String typeName = store.getTypeNames()[0]; SimpleFeatureSource source = store.getFeatureSource(typeName); CoordinateReferenceSystem crs = source.getSchema() .getGeometryDescriptor() .getCoordinateReferenceSystem(); if (crs != null) { sourceCRS = crs; } return FeatureCollectionParsers.read(source, sourceCRS, targetCRS); } catch (ServiceException e) { throw e; } catch (Exception e) { throw new UserLayerException("Failed to parse MIF: " + e.getMessage(), UserLayerException.ErrorType.PARSER, UserLayerException.ErrorType.INVALID_FORMAT); } finally { if (store != null) { store.dispose(); } } }
Source:
<code>public boolean isValid(Object obj) { switch (nativeValue) { case CORE_TYPE_VALUE_INTEGER: return (obj instanceof Long || obj instanceof Integer || obj instanceof Short || obj instanceof Byte); case CORE_TYPE_VALUE_BOOLEAN: return (obj instanceof Boolean); case CORE_TYPE_VALUE_STRING: return (obj instanceof String); case CORE_TYPE_VALUE_BINARY: return (obj instanceof byte[] || obj instanceof ByteBuffer); case CORE_TYPE_VALUE_DATE: return (obj instanceof java.util.Date); <START> case CORE_TYPE_VALUE_FLOAT: <END> return (obj instanceof Float); case CORE_TYPE_VALUE_DOUBLE: return (obj instanceof Double); case CORE_TYPE_VALUE_DECIMAL128: return (obj instanceof Decimal128); case CORE_TYPE_VALUE_OBJECT: return(obj instanceof ObjectId); case CORE_TYPE_VALUE_LIST: case CORE_TYPE_VALUE_LINKING_OBJECTS: case CORE_TYPE_VALUE_INTEGER + LIST_OFFSET: case CORE_TYPE_VALUE_BOOLEAN + LIST_OFFSET: case CORE_TYPE_VALUE_STRING + LIST_OFFSET: case CORE_TYPE_VALUE_BINARY + LIST_OFFSET: case CORE_TYPE_VALUE_DATE + LIST_OFFSET: case CORE_TYPE_VALUE_FLOAT + LIST_OFFSET: case CORE_TYPE_VALUE_DOUBLE + LIST_OFFSET: case CORE_TYPE_VALUE_DECIMAL128 + LIST_OFFSET: case CORE_TYPE_VALUE_OBJECTID + LIST_OFFSET: return false; default: throw new RuntimeException("Unsupported Realm type: " + this); } }</code><technical_language>nice catch</technical_language>

Target:
public boolean isValid(Object obj) { switch (nativeValue) { case CORE_TYPE_VALUE_INTEGER: return (obj instanceof Long || obj instanceof Integer || obj instanceof Short || obj instanceof Byte); case CORE_TYPE_VALUE_BOOLEAN: return (obj instanceof Boolean); case CORE_TYPE_VALUE_STRING: return (obj instanceof String); case CORE_TYPE_VALUE_BINARY: return (obj instanceof byte[] || obj instanceof ByteBuffer); case CORE_TYPE_VALUE_DATE: return (obj instanceof java.util.Date); case CORE_TYPE_VALUE_FLOAT: return (obj instanceof Float); case CORE_TYPE_VALUE_DOUBLE: return (obj instanceof Double); case CORE_TYPE_VALUE_DECIMAL128: return (obj instanceof Decimal128); case CORE_TYPE_VALUE_OBJECTID: return (obj instanceof ObjectId); case CORE_TYPE_VALUE_OBJECT: return false; case CORE_TYPE_VALUE_LIST: case CORE_TYPE_VALUE_LINKING_OBJECTS: case CORE_TYPE_VALUE_INTEGER + LIST_OFFSET: case CORE_TYPE_VALUE_BOOLEAN + LIST_OFFSET: case CORE_TYPE_VALUE_STRING + LIST_OFFSET: case CORE_TYPE_VALUE_BINARY + LIST_OFFSET: case CORE_TYPE_VALUE_DATE + LIST_OFFSET: case CORE_TYPE_VALUE_FLOAT + LIST_OFFSET: case CORE_TYPE_VALUE_DOUBLE + LIST_OFFSET: case CORE_TYPE_VALUE_DECIMAL128 + LIST_OFFSET: case CORE_TYPE_VALUE_OBJECTID + LIST_OFFSET: return false; default: throw new RuntimeException("Unsupported Realm type: " + this); } }
Source:
<code>public Iterator iterator() { return new Iterator() { Integer cursor = 0; @Override public boolean hasNext() { return cursor != nodeList.getLength() - 1; } @Override public Node next() { <START> cursor = new Integer(cursor + 1); <END> if (cursor >= nodeList.getLength()) { throw new NoSuchElementException(); } else return nodeList.item(cursor); } @Override public void remove() { throw new UnsupportedOperationException(); } }; }</code><technical_language>cursor = cursor + 1</technical_language>

Target:
public Iterator iterator() { return new Iterator() { private Integer cursor = 0; @Override public boolean hasNext() { return cursor != nodeList.getLength() - 1; } @Override public Node next() { cursor++; if (cursor >= nodeList.getLength()) { throw new NoSuchElementException(); } else { return nodeList.item(cursor); } } @Override public void remove() { throw new UnsupportedOperationException(); } }; }
Source:
<code>protected ScheduledReporter(MetricRegistry registry, String name, MetricFilter filter, TimeUnit rateUnit, TimeUnit durationUnit, ScheduledExecutorService executor, boolean shutdownExecutorOnStop, Set<MetricAttribute> disabledMetricAttributes) { if (registry == null) { <START> throw new IllegalArgumentException("MetricRegistry must not be null !!!"); <END> } this.registry = registry; this.filter = filter; this.executor = executor == null ? createDefaultExecutor(name) : executor; this.shutdownExecutorOnStop = shutdownExecutorOnStop; this.rateFactor = rateUnit.toSeconds(1); this.rateUnit = calculateRateUnit(rateUnit); this.durationFactor = durationUnit.toNanos(1); this.durationUnit = durationUnit.toString().toLowerCase(Locale.US); this.disabledMetricAttributes = disabledMetricAttributes != null ? disabledMetricAttributes : Collections.emptySet(); }</code><technical_language>this a throw new NullPointerException("registry == null"); instead</technical_language>

Target:
protected ScheduledReporter(MetricRegistry registry, String name, MetricFilter filter, TimeUnit rateUnit, TimeUnit durationUnit, ScheduledExecutorService executor, boolean shutdownExecutorOnStop, Set<MetricAttribute> disabledMetricAttributes) { if (registry == null) { throw new NullPointerException("registry == null"); } this.registry = registry; this.filter = filter; this.executor = executor == null ? createDefaultExecutor(name) : executor; this.shutdownExecutorOnStop = shutdownExecutorOnStop; this.rateFactor = rateUnit.toSeconds(1); this.rateUnit = calculateRateUnit(rateUnit); this.durationFactor = durationUnit.toNanos(1); this.durationUnit = durationUnit.toString().toLowerCase(Locale.US); this.disabledMetricAttributes = disabledMetricAttributes != null ? disabledMetricAttributes : Collections.emptySet(); }
Source:
<code>private static IndexStore getIndexStore( final IndexSettings indexSettings, final Map<String, Function<IndexSettings, IndexStore>> indexStoreFactories) { final String storeType = indexSettings.getValue(INDEX_STORE_TYPE_SETTING); final Type type; <START> final Boolean allowMmap = NODE_STORE_ALLOW_MMAP.get(indexSettings.getNodeSettings(), Settings.EMPTY); <END> if (storeType.isEmpty() || Type.FS.getSettingsKey().equals(storeType)) { type = defaultStoreType(allowMmap); } else { if (isBuiltinType(storeType)) { type = Type.fromSettingsKey(storeType); } else { type = null; } } if (allowMmap == false && (type == Type.MMAPFS || type == Type.HYBRIDFS)) { throw new IllegalArgumentException("store type [" + storeType + "] is not allowed because mmap is disabled"); } final IndexStore store; if (storeType.isEmpty() || isBuiltinType(storeType)) { store = new IndexStore(indexSettings); } else { Function<IndexSettings, IndexStore> factory = indexStoreFactories.get(storeType); if (factory == null) { throw new IllegalArgumentException("Unknown store type [" + storeType + "]"); } store = factory.apply(indexSettings); if (store == null) { throw new IllegalStateException("store must not be null"); } } return store; }</code><technical_language>is empty settings fallback needed here</technical_language>

Target:
private static IndexStore getIndexStore( final IndexSettings indexSettings, final Map<String, Function<IndexSettings, IndexStore>> indexStoreFactories) { final String storeType = indexSettings.getValue(INDEX_STORE_TYPE_SETTING); final Type type; final Boolean allowMmap = NODE_STORE_ALLOW_MMAP.getWithFallback(indexSettings.getNodeSettings()); if (storeType.isEmpty() || Type.FS.getSettingsKey().equals(storeType)) { type = defaultStoreType(allowMmap); } else { if (isBuiltinType(storeType)) { type = Type.fromSettingsKey(storeType); } else { type = null; } } if (allowMmap == false && (type == Type.MMAPFS || type == Type.HYBRIDFS)) { throw new IllegalArgumentException("store type [" + storeType + "] is not allowed because mmap is disabled"); } final IndexStore store; if (storeType.isEmpty() || isBuiltinType(storeType)) { store = new IndexStore(indexSettings); } else { Function<IndexSettings, IndexStore> factory = indexStoreFactories.get(storeType); if (factory == null) { throw new IllegalArgumentException("Unknown store type [" + storeType + "]"); } store = factory.apply(indexSettings); if (store == null) { throw new IllegalStateException("store must not be null"); } } return store; }
Source:
<code>public double getFractionTransferred() { if (transferableBytes == 0) { return 1.0D; } else { double percentage = (double) transferredBytes / (double) transferableBytes; <START> return percentage > 1.0D ? 1.0D : percentage; <END> } }</code><technical_language>Really</technical_language>

Target:
public double getFractionTransferred() { if (transferableBytes == 0) { return 1.0D; } else { double percentage = (double) transferredBytes / (double) transferableBytes; if (percentage > 1.0D) { RealmLog.error("Invalid progress state: %s", this); return 1.0D; } else { return percentage; } } }
Source:
<code>public void testOnStartCommandStartReplicationCommandsQueuedBeforeSetReplicators() { PeriodicReplicationService service = new TestReplicationService(mMockContext); Intent startIntent = new Intent(mMockContext, TestReplicationService.class); startIntent.putExtra(PeriodicReplicationService.EXTRA_COMMAND, PeriodicReplicationService.COMMAND_START_REPLICATION); Intent stopIntent = new Intent(mMockContext, TestReplicationService.class); stopIntent.putExtra(PeriodicReplicationService.EXTRA_COMMAND, PeriodicReplicationService .COMMAND_STOP_REPLICATION); service.setReplicationPolicyManager(mMockReplicationPolicyManager); service.onCreate(); final CountDownLatch latch = new CountDownLatch(2); service.setOperationStartedListener(new PeriodicReplicationService .OperationStartedListener() { @Override public void operationStarted(int operationId) { if (operationId == PeriodicReplicationService.COMMAND_START_REPLICATION) { <START> latch.countDown(); <END> } else if (operationId == PeriodicReplicationService.COMMAND_STOP_REPLICATION) { latch.countDown(); } } }); service.onStartCommand(startIntent, 0, 0); service.onStartCommand(stopIntent, 0, 0); service.setReplicators(mMockReplicators); try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } }</code><technical_language>Is in asserting commands in right order? implementation is a List I guess protects changes duplicate checking insertion wrong place in future. like: if (latch.getCount() == 2){ latch.countDown() } else { fail("Wrong order")} for start similarly a 1 count for stop event. WDYT</technical_language>

Target:
public void testOnStartCommandStartReplicationCommandsQueuedBeforeSetReplicators() { PeriodicReplicationService service = new TestReplicationService(mMockContext); Intent startIntent = new Intent(mMockContext, TestReplicationService.class); startIntent.putExtra(PeriodicReplicationService.EXTRA_COMMAND, PeriodicReplicationService.COMMAND_START_REPLICATION); Intent stopIntent = new Intent(mMockContext, TestReplicationService.class); stopIntent.putExtra(PeriodicReplicationService.EXTRA_COMMAND, PeriodicReplicationService .COMMAND_STOP_REPLICATION); service.setReplicationPolicyManager(mMockReplicationPolicyManager); service.onCreate(); final CountDownLatch latch = new CountDownLatch(2); service.setOperationStartedListener(new PeriodicReplicationService .OperationStartedListener() { @Override public void operationStarted(int operationId) { if (latch.getCount() == 2 && operationId == PeriodicReplicationService .COMMAND_START_REPLICATION) { latch.countDown(); } else if (latch.getCount() == 1 && operationId == PeriodicReplicationService .COMMAND_STOP_REPLICATION) { latch.countDown(); } else { fail("Unexpected command or commands received in incorrect order"); } } }); service.onStartCommand(startIntent, 0, 0); service.onStartCommand(stopIntent, 0, 0); service.setReplicators(mMockReplicators); try { assertTrue("The countdown should reach zero", latch.await(DEFAULT_WAIT_SECONDS, TimeUnit.SECONDS)); } catch (InterruptedException e) { e.printStackTrace(); } }
Source:
<code>public static <T> void generateJSON(ChoiceProvider<T> provider, OutputStream outputStream) { Request request = RequestCycle.get().getRequest(); IRequestParameters params = request.getRequestParameters(); String term = params.getParameterValue("q").toOptionalString(); int page = params.getParameterValue("page").toInt(1); page -= 1; Response<T> response = new Response<>(); provider.query(term, page, response); <START> OutputStreamWriter out = new OutputStreamWriter(outputStream, request.getCharset()); <END> JSONWriter json = new JSONWriter(out); try { json.object(); json.key("items").array(); for (T item : response) { json.object(); provider.toJson(item, json); json.endObject(); } json.endArray(); json.key("more").value(response.getHasMore()).endObject(); } catch (JSONException e) { throw new RuntimeException("Could not write Json response", e); } try { out.flush(); } catch (IOException e) { throw new RuntimeException("Could not write Json to servlet response", e); } }</code><technical_language>resource leak: out closes (also in original code)</technical_language>

Target:
public static <T> void generateJSON(ChoiceProvider<T> provider, OutputStream outputStream) { Request request = RequestCycle.get().getRequest(); IRequestParameters params = request.getRequestParameters(); String term = params.getParameterValue("q").toOptionalString(); int page = params.getParameterValue("page").toInt(1); page -= 1; Response<T> response = new Response<>(); provider.query(term, page, response); OutputStreamWriter out = new OutputStreamWriter(outputStream, request.getCharset()); JSONWriter json = new JSONWriter(out); try { json.object(); json.key("items").array(); for (T item : response) { json.object(); provider.toJson(item, json); json.endObject(); } json.endArray(); json.key("more").value(response.getHasMore()).endObject(); } catch (JSONException e) { throw new RuntimeException("Could not write Json response", e); } try { out.flush(); } catch (IOException e) { throw new RuntimeException("Could not write Json to servlet response", e); } try { out.close(); } catch (IOException e) { throw new RuntimeException("Could not write Json to servlet response", e); } }
Source:
<code><START> public Class<? extends Permission> getPermissionClass(String className) { <END> try { return (Class<? extends Permission>) this.getClass().getClassLoader().loadClass(className); } catch (ClassNotFoundException e) { LOGGER.warn("permission class not found: ", e); return null; } }</code><technical_language>do work classNames Class objects instead? This smells dynamic-import :-(</technical_language>

Target:
public Class<? extends Permission> getPermissionClass(String className) throws ClassNotFoundException { if (supported.containsKey(className)) { return supported.get(className); } LOGGER.warn("permission class not found: {}", className); throw new ClassNotFoundException("PermissionType " + className + " not found in this provider"); }
Source:
<code>private void notifyFilteredOut(Object[] rawResult, Object[] filteredResult) { int rawIndex = 0; int filteredIndex = 0; for (; filteredIndex < filteredResult.length; ) { <START> if (!rawResult[rawIndex].equals(filteredResult[filteredIndex])) { <END> associateListener.filteredOut(rawResult[rawIndex++]); continue; } rawIndex++; filteredIndex++; } for (; rawIndex < rawResult.length; rawIndex++) { associateListener.filteredOut(rawResult[rawIndex]); } }</code><technical_language>This is a change, break clients differently implemented equals() (where multiple distinct elements equal)</technical_language>

Target:
private void notifyFilteredOut(Object[] rawResult, Object[] filteredResult) { int rawIndex = 0; int filteredIndex = 0; for (; filteredIndex < filteredResult.length; ) { if (rawIndex < rawResult.length && rawResult[rawIndex] != filteredResult[filteredIndex]) { associateListener.filteredOut(rawResult[rawIndex++]); continue; } rawIndex++; filteredIndex++; } for (; rawIndex < rawResult.length; rawIndex++) { associateListener.filteredOut(rawResult[rawIndex]); } }
Source:
<code>private static boolean isAcceptableDumpingDatabase(String databaseName) { <START> return (databaseName == null || !databaseName.equalsIgnoreCase("information_schema")); <END> }</code><technical_language>change "information_schema" constants</technical_language>

Target:
private static boolean isAcceptableDumpingDatabase(String databaseName) { return (databaseName == null || !databaseName.equalsIgnoreCase(CatalogConstants.INFORMATION_SCHEMA_DB_NAME)); }
Source:
<code>private <T extends BaseResourceIndex> void tryToReuseIndexEntities(List<T> theIndexesToRemove, List<T> theIndexesToAdd) { for (int addIndex = 0; addIndex < theIndexesToAdd.size(); addIndex++) { if (theIndexesToRemove.isEmpty()) { break; } T entityToReuse = theIndexesToRemove.remove(theIndexesToRemove.size() - 1); <START> entityToReuse.populateFrom(theIndexesToAdd.get(addIndex)); <END> theIndexesToAdd.set(addIndex, entityToReuse); } }</code><technical_language>a populateFrom() strategy runs risk of missing data if new fields added in future. This risk avoided copying id entityToReuse theIndexesToAdd.get(addIndex). need do some hibernate magic if in session (detach / reattach type stuff)</technical_language>

Target:
private <T extends BaseResourceIndex> void tryToReuseIndexEntities(List<T> theIndexesToRemove, List<T> theIndexesToAdd) { for (int addIndex = 0; addIndex < theIndexesToAdd.size(); addIndex++) { if (theIndexesToRemove.isEmpty()) { break; } T targetEntity = theIndexesToAdd.get(addIndex); if (targetEntity.getId() != null) { continue; } T entityToReuse = theIndexesToRemove.remove(theIndexesToRemove.size() - 1); targetEntity.setId(entityToReuse.getId()); } }
Source:
<code>private Map<String, Object> extractCoreGeneralInfo(XmlNode domain) { Map<String, Object> info = new HashMap<>(); info.put(VdsProperties.vm_name, domain.selectSingleNode("name").innerText); info.put(VdsProperties.vm_guid, domain.selectSingleNode("uuid").innerText); XmlNode cpusTopology = domain.selectSingleNode("cpu").selectSingleNode("topology"); if (cpusTopology != null) { info.put(VdsProperties.num_of_cpus, cpusTopology.attributes.get("sockets").innerText); } else { info.put(VdsProperties.num_of_cpus, domain.selectSingleNode("vcpu").innerText); <START> } <END> info.put(VdsProperties.mem_size_mb, domain.selectSingleNode("memory").innerText); XmlNode maxMemory = domain.selectSingleNode("maxMemory"); if (maxMemory == null) { maxMemory = domain.selectSingleNode("memory"); } info.putAll(DomainXmlUtils.parseMaxMemSize(maxMemory)); info.put(VdsProperties.emulatedMachine, DomainXmlUtils.parseEmulatedMachine(domain.selectSingleNode("os"))); return info; }</code><technical_language>libvirt describe topology sub-element like: "The *optional* topology element specifies requested topology..." inconsistent... anyway, this part good</technical_language>

Target:
private Map<String, Object> extractCoreGeneralInfo(XmlNode domain) { Map<String, Object> info = new HashMap<>(); info.put(VdsProperties.vm_name, domain.selectSingleNode("name").innerText); info.put(VdsProperties.vm_guid, domain.selectSingleNode("uuid").innerText); XmlNode cpusTopology = domain.selectSingleNode("cpu").selectSingleNode("topology"); if (cpusTopology != null) { info.put(VdsProperties.num_of_cpus, cpusTopology.attributes.get("sockets").innerText); } else { info.put(VdsProperties.num_of_cpus, domain.selectSingleNode("vcpu").innerText); } info.put(VdsProperties.mem_size_mb, domain.selectSingleNode("memory").innerText); info.putAll(DomainXmlUtils.parseMaxMemSize(domain.selectSingleNode("maxMemory"))); info.put(VdsProperties.emulatedMachine, DomainXmlUtils.parseEmulatedMachine(domain.selectSingleNode("os"))); return info; }
Source:
<code>public void testInvalidateAll() throws InterruptedException, ExecutionException, TimeoutException, NetworkException, InjectionException { setup(0); <START> final BlockingQueue<EncodedKey<Integer>> pullKeyToReplyQueue = new LinkedBlockingQueue<>(); <END> final ExecutorService executorService = ParameterWorkerTestUtil.setupPullReplyingThread(pullKeyToReplyQueue, workerHandler); ParameterWorkerTestUtil.setupSenderToEnqueuePullOps(pullKeyToReplyQueue, mockSender); final int numPulls = 1000; final CountDownLatch countDownLatch = new CountDownLatch(1); final ExecutorService pool = Executors.newSingleThreadExecutor(); final AsyncParameterWorker<Integer, Integer, Integer> asyncParameterWorker = (AsyncParameterWorker<Integer, Integer, Integer>) parameterWorker; pool.submit(() -> { for (int pull = 0; pull < numPulls; ++pull) { asyncParameterWorker.pull(0); asyncParameterWorker.invalidateAll(); } countDownLatch.countDown(); }); pool.shutdown(); final boolean allThreadsFinished = countDownLatch.await(10, TimeUnit.SECONDS); asyncParameterWorker.close(ParameterWorkerTestUtil.CLOSE_TIMEOUT); assertTrue(ParameterWorkerTestUtil.MSG_THREADS_SHOULD_FINISH, allThreadsFinished); verify(mockSender, times(numPulls)).sendPullMsg(anyString(), anyObject()); executorService.shutdown(); }</code><technical_language>I it. Then, ok stick current code</technical_language>

Target:
public void testInvalidateAll() throws InterruptedException, ExecutionException, TimeoutException, NetworkException, InjectionException { prepare(Long.MAX_VALUE); final BlockingQueue<EncodedKey<Integer>> pullKeyToReplyQueue = new LinkedBlockingQueue<>(); final ExecutorService executorService = ParameterWorkerTestUtil.startPullReplyingThreads(pullKeyToReplyQueue, workerHandler); ParameterWorkerTestUtil.setupSenderToEnqueuePullOps(pullKeyToReplyQueue, mockSender); final int numPulls = 1000; final CountDownLatch countDownLatch = new CountDownLatch(1); final ExecutorService pool = Executors.newSingleThreadExecutor(); final AsyncParameterWorker<Integer, Integer, Integer> asyncParameterWorker = (AsyncParameterWorker<Integer, Integer, Integer>) parameterWorker; pool.submit(() -> { for (int pull = 0; pull < numPulls; ++pull) { asyncParameterWorker.pull(0); asyncParameterWorker.invalidateAll(); } countDownLatch.countDown(); }); pool.shutdown(); final boolean allThreadsFinished = countDownLatch.await(10, TimeUnit.SECONDS); asyncParameterWorker.close(ParameterWorkerTestUtil.CLOSE_TIMEOUT); assertTrue(ParameterWorkerTestUtil.MSG_THREADS_SHOULD_FINISH, allThreadsFinished); verify(mockSender, times(numPulls)).sendPullMsg(anyString(), anyObject()); executorService.shutdown(); }
Source:
<code>public int getInstanceCap() { <START> return instanceCap; END> }</code><technical_language>If a change, revert</technical_language>

Target:
public Integer getInstanceCap() { return instanceCap; }