auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private ModuleDataModelOracle getModuleOracle(String typeName) { Class<?> clazz = null; try { clazz = classLoader.loadClass(typeName); if (clazz == null) { clazz = getClass().forName(typeName); } } catch (ClassNotFoundException e) { logger.error("Unable to extract model for class '{}'.", typeName); throw new IllegalStateException("Unable to extract model for class '" + typeName + "'"); } if (clazz == null) { logger.error("Unable to extract model for class '{}'.", typeName); throw new IllegalStateException("Unable to extract model for class '" + typeName + "'"); } try { final ModuleDataModelOracleBuilder builder = ModuleDataModelOracleBuilder.newModuleOracleBuilder(evaluator); final ClassFactBuilder modelFactBuilder = new ClassFactBuilder(builder, clazz, false, type -> TypeSource.JAVA_PROJECT); ModuleDataModelOracle oracle = modelFactBuilder.getDataModelBuilder().build(); Map<String, FactBuilder> builders = new HashMap<>(); for (FactBuilder factBuilder : modelFactBuilder.getInternalBuilders().values()) { if (factBuilder instanceof ClassFactBuilder) { builders.put(((ClassFactBuilder) factBuilder).getType(), factBuilder); factBuilder.build((ModuleDataModelOracleImpl) oracle); } } builders.put(modelFactBuilder.getType(), modelFactBuilder); modelFactBuilder.build((ModuleDataModelOracleImpl) oracle); return oracle; <START> } catch (IOException ex) { <END> } return null; }</code><technical_language>I log exception</technical_language>

Target:
private ModuleDataModelOracle getModuleOracle(String typeName) { Class<?> clazz = null; try { clazz = classLoader.loadClass(typeName); if (clazz == null) { clazz = getClass().forName(typeName); } } catch (ClassNotFoundException e) { logger.error("Unable to extract model for class '{}'.", typeName); throw new IllegalStateException("Unable to extract model for class '" + typeName + "'"); } if (clazz == null) { logger.error("Unable to extract model for class '{}'.", typeName); throw new IllegalStateException("Unable to extract model for class '" + typeName + "'"); } try { final ModuleDataModelOracleBuilder builder = ModuleDataModelOracleBuilder.newModuleOracleBuilder(evaluator); final ClassFactBuilder modelFactBuilder = new ClassFactBuilder(builder, clazz, false, type -> TypeSource.JAVA_PROJECT); ModuleDataModelOracle oracle = modelFactBuilder.getDataModelBuilder().build(); Map<String, FactBuilder> builders = new HashMap<>(); for (FactBuilder factBuilder : modelFactBuilder.getInternalBuilders().values()) { if (factBuilder instanceof ClassFactBuilder) { builders.put(((ClassFactBuilder) factBuilder).getType(), factBuilder); factBuilder.build((ModuleDataModelOracleImpl) oracle); } } builders.put(modelFactBuilder.getType(), modelFactBuilder); modelFactBuilder.build((ModuleDataModelOracleImpl) oracle); return oracle; } catch (IOException ex) { logger.warn("Couldn't inspect model due to: {}", typeName, ex); } return null; }
Source:
<code>protected String[] getFilesToIncludes(File baseDir, String[] includes, String[] excludes) { final DirectoryScanner scanner = new DirectoryScanner(); scanner.setBasedir(baseDir); if (excludes != null) { scanner.setExcludes(excludes); } scanner.addDefaultExcludes(); if (includes != null && includes.length > 0) { scanner.setIncludes(includes); } else { scanner.setIncludes(DEFAULT_INCLUDES); } scanner.scan(); final String[] includedFiles = scanner.getIncludedFiles(); for (int i = 0; i < includedFiles.length; i++) { <START> includedFiles[i] = "/" + includedFiles[i].replace("\\", "/"); <END> } return includedFiles; }</code><technical_language>I this is a safe replace. File backslash Linux. replace(PATH_SEPARATOR, "/") :-)</technical_language>

Target:
protected String[] getFilesToIncludes(File baseDir, String[] includes, String[] excludes) { final DirectoryScanner scanner = new DirectoryScanner(); scanner.setBasedir(baseDir); if (excludes != null) { scanner.setExcludes(excludes); } scanner.addDefaultExcludes(); if (includes != null && includes.length > 0) { scanner.setIncludes(includes); } else { scanner.setIncludes(DEFAULT_INCLUDES); } scanner.scan(); final String[] includedFiles = scanner.getIncludedFiles(); for (int i = 0; i < includedFiles.length; i++) { includedFiles[i] = "/" + includedFiles[i].replace(File.separator, "/"); } return includedFiles; }
Source:
<code>public Object loadByUniqueKey( String entityName, String uniqueKeyPropertyName, Object key, SharedSessionContractImplementor session) throws HibernateException { final SessionFactoryImplementor factory = session.getFactory(); UniqueKeyLoadable persister = (UniqueKeyLoadable) factory.getMetamodel().entityPersister( entityName ); EntityUniqueKey euk = new EntityUniqueKey( entityName, uniqueKeyPropertyName, key, getIdentifierOrUniqueKeyType( factory ), persister.getEntityMode(), session.getFactory() ); final PersistenceContext persistenceContext = session.getPersistenceContext(); Object result = persistenceContext.getEntity( euk ); if ( result == null ) { result = persister.loadByUniqueKey( uniqueKeyPropertyName, key, session ); } <START> <END> if (result != null) { persistenceContext.addEntity(euk, result); } return result == null ? null : persistenceContext.proxyFor( result ); }</code><technical_language>Need remove/amend TODO [#L685](<LINK_0> (16 lines above)</technical_language>

Target:
public Object loadByUniqueKey( String entityName, String uniqueKeyPropertyName, Object key, SharedSessionContractImplementor session) throws HibernateException { final SessionFactoryImplementor factory = session.getFactory(); UniqueKeyLoadable persister = (UniqueKeyLoadable) factory.getMetamodel().entityPersister( entityName ); EntityUniqueKey euk = new EntityUniqueKey( entityName, uniqueKeyPropertyName, key, getIdentifierOrUniqueKeyType( factory ), persister.getEntityMode(), session.getFactory() ); final PersistenceContext persistenceContext = session.getPersistenceContext(); Object result = persistenceContext.getEntity( euk ); if ( result == null ) { result = persister.loadByUniqueKey( uniqueKeyPropertyName, key, session ); if (result != null) { persistenceContext.addEntity(euk, result); } } return result == null ? null : persistenceContext.proxyFor( result ); }
Source:
<code>public boolean equals(Object obj) { boolean equals = false; if (obj instanceof MergeStrategySection && useContentMerge == ((MergeStrategySection) obj).useContentMerge && submitType.equals(((MergeStrategySection) obj).submitType)) { <START> equals = true; <END> } return equals; }</code><technical_language>Is OK assume of null? a user easily create a ref entry of defined? support this case in code, supported? I easily a project wanting override overriding/specifying other</technical_language>

Target:
public boolean equals(Object obj) { boolean equals = false; if (obj instanceof MergeStrategySection && ((name == null && ((MergeStrategySection) obj).name == null) || (name != null && name.equals(name))) && ((useContentMerge == null && ((MergeStrategySection) obj).useContentMerge == null) || (useContentMerge != null && useContentMerge .equals(((MergeStrategySection) obj).useContentMerge))) && ((submitType == null && ((MergeStrategySection) obj).submitType == null) || (submitType != null && submitType .equals(((MergeStrategySection) obj).submitType)))) { equals = true; } return equals; }
Source:
<code>public void onResponse(Map<String, Object> response) { try { processRefreshVdsStatsResponse((VDSReturnValue) response.get("result")); if <START> (!isVdsUpOrGoingToMaintenance) { <END> vdsManager.setStatus(VDSStatus.Up, vds); } refreshVdsRunTimeInfo(isVdsUpOrGoingToMaintenance); } catch(Throwable t) { onFailure(t); } }</code><technical_language>need check this point if host status non-operational</technical_language>

Target:
public void onResponse(Map<String, Object> response) { try { processRefreshVdsStatsResponse((VDSReturnValue) response.get("result")); if (!vdsUpOrGoingToMaintenance) { vdsManager.setStatus(VDSStatus.Up, vds); } refreshVdsRunTimeInfo(vdsUpOrGoingToMaintenance); } catch(Throwable t) { onFailure(t); } }
Source:
<code>static <T> T buildSqlObject(final Class<T> sqlObjectType, final HandleDing handle) { Factory f; if (factories.containsKey(sqlObjectType)) { f = factories.get(sqlObjectType); } else { Enhancer e = new Enhancer(); e.setClassLoader(sqlObjectType.getClassLoader()); List<Class<?>> interfaces = new ArrayList<>(); interfaces.add(CloseInternalDoNotUseThisClass.class); if (sqlObjectType.isInterface()) { interfaces.add(sqlObjectType); } else { e.setSuperclass(sqlObjectType); } e.setInterfaces(interfaces.toArray(new Class[interfaces.size()])); final SqlObject so = new SqlObject(buildHandlersFor(sqlObjectType), handle); e.setCallbackFilter(new CallbackFilter() { @Override public int accept(Method method) { return method.isDefault() ? 1 : 0; } }); e.setCallbacks(new Callback[] {new MethodInterceptor() { @Override public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable { return so.invoke(o, method, objects, methodProxy); } <START> }, <END> NoOp.INSTANCE }); T t = (T) e.create(); T actual = (T) factories.putIfAbsent(sqlObjectType, (Factory) t); if (actual == null) { return t; } f = (Factory) actual; } final SqlObject so = new SqlObject(buildHandlersFor(sqlObjectType), handle); return (T) f.newInstance(new Callback[] {new MethodInterceptor() { @Override public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable { return so.invoke(o, method, objects, methodProxy); } }, NoOp.INSTANCE }); }</code><technical_language>This anonymous class replaced so::invoke</technical_language>

Target:
static <T> T buildSqlObject(final Class<T> sqlObjectType, final HandleDing handle) { Factory f; if (factories.containsKey(sqlObjectType)) { f = factories.get(sqlObjectType); } else { Enhancer e = new Enhancer(); e.setClassLoader(sqlObjectType.getClassLoader()); List<Class<?>> interfaces = new ArrayList<>(); interfaces.add(CloseInternalDoNotUseThisClass.class); if (sqlObjectType.isInterface()) { interfaces.add(sqlObjectType); } else { e.setSuperclass(sqlObjectType); } e.setInterfaces(interfaces.toArray(new Class[interfaces.size()])); final SqlObject so = new SqlObject(buildHandlersFor(sqlObjectType), handle); e.setCallbackFilter(m -> m.isDefault() ? 1 : 0); e.setCallbacks(new Callback[] { (MethodInterceptor) so::invoke, NoOp.INSTANCE }); T t = (T) e.create(); T actual = (T) factories.putIfAbsent(sqlObjectType, (Factory) t); if (actual == null) { return t; } f = (Factory) actual; } final SqlObject so = new SqlObject(buildHandlersFor(sqlObjectType), handle); return (T) f.newInstance(new Callback[] { (MethodInterceptor) so::invoke, NoOp.INSTANCE }); }
Source:
<code>protected void renameTo(final String newName) throws IOException { if (!isNameEditable()) { <START> throw new IOException("Trying to rename an item that has not editable name."); <END> } final ItemGroup parent = getParent(); String oldName = this.name; String oldFullName = getFullName(); synchronized (parent) { synchronized (this) { if (newName == null) throw new IllegalArgumentException("New name is not given"); if (this.name.equals(newName)) return; Items.verifyItemDoesNotAlreadyExist(parent, newName, this); File oldRoot = this.getRootDir(); doSetName(newName); File newRoot = this.getRootDir(); boolean success = false; try { boolean interrupted = false; boolean renamed = false; for (int retry = 0; retry < 5; retry++) { if (oldRoot.renameTo(newRoot)) { renamed = true; break; } try { Thread.sleep(500); } catch (InterruptedException e) { interrupted = true; } } if (interrupted) Thread.currentThread().interrupt(); if (!renamed) { Copy cp = new Copy(); cp.setProject(new org.apache.tools.ant.Project()); cp.setTodir(newRoot); FileSet src = new FileSet(); src.setDir(oldRoot); cp.addFileset(src); cp.setOverwrite(true); cp.setPreserveLastModified(true); cp.setFailOnError(false); cp.execute(); try { Util.deleteRecursive(oldRoot); } catch (IOException e) { e.printStackTrace(); } } success = true; } finally { if (!success) doSetName(oldName); } parent.onRenamed(this, oldName, newName); } } ItemListener.fireLocationChange(this, oldFullName); }</code><technical_language>valid English. _Non-editable_ is, meant suggestion throw new IOException("Trying rename item support this operation.");</technical_language>

Target:
protected void renameTo(final String newName) throws IOException { if (!isNameEditable()) { throw new IOException("Trying to rename an item that does not support this operation."); } final ItemGroup parent = getParent(); String oldName = this.name; String oldFullName = getFullName(); synchronized (parent) { synchronized (this) { if (newName == null) throw new IllegalArgumentException("New name is not given"); if (this.name.equals(newName)) return; Items.verifyItemDoesNotAlreadyExist(parent, newName, this); File oldRoot = this.getRootDir(); doSetName(newName); File newRoot = this.getRootDir(); boolean success = false; try { boolean interrupted = false; boolean renamed = false; for (int retry = 0; retry < 5; retry++) { if (oldRoot.renameTo(newRoot)) { renamed = true; break; } try { Thread.sleep(500); } catch (InterruptedException e) { interrupted = true; } } if (interrupted) Thread.currentThread().interrupt(); if (!renamed) { Copy cp = new Copy(); cp.setProject(new org.apache.tools.ant.Project()); cp.setTodir(newRoot); FileSet src = new FileSet(); src.setDir(oldRoot); cp.addFileset(src); cp.setOverwrite(true); cp.setPreserveLastModified(true); cp.setFailOnError(false); cp.execute(); try { Util.deleteRecursive(oldRoot); } catch (IOException e) { e.printStackTrace(); } } success = true; } finally { if (!success) doSetName(oldName); } parent.onRenamed(this, oldName, newName); } } ItemListener.fireLocationChange(this, oldFullName); }
Source:
<code>LedgerMetadata(int metadataFormatVersion, int ensembleSize, int writeQuorumSize, int ackQuorumSize, LedgerMetadataFormat.State state, Optional<Long> lastEntryId, Optional<Long> length, Map<Long, List<BookieSocketAddress>> ensembles, DigestType digestType, Optional<byte[]> password, long ctime, boolean storeCtime, Map<String, byte[]> customMetadata) { checkArgument(ensembles.size() > 0, "There must be at least one ensemble in the ledger"); this.metadataFormatVersion = metadataFormatVersion; this.ensembleSize = ensembleSize; this.writeQuorumSize = writeQuorumSize; this.ackQuorumSize = ackQuorumSize; this.state = state; if (lastEntryId.isPresent()) { this.lastEntryId = lastEntryId.get(); } else { this.lastEntryId = LedgerHandle.INVALID_ENTRY_ID; } length.ifPresent((l) -> this.length = l); setEnsembles(ensembles); if (state != LedgerMetadataFormat.State.CLOSED) { currentEnsemble = this.ensembles.lastEntry().getValue(); } this.digestType = digestType.equals(DigestType.MAC) ? LedgerMetadataFormat.DigestType.HMAC : LedgerMetadataFormat.DigestType.valueOf(digestType.toString()); if (password.isPresent()) { this.password = password.get(); this.hasPassword = true; } else { <START> this.password = new byte[0]; <END> this.hasPassword = false; } this.ctime = ctime; this.storeCtime = storeCtime; this.customMetadata.putAll(customMetadata); }</code><technical_language>'null' better</technical_language>

Target:
LedgerMetadata(int metadataFormatVersion, int ensembleSize, int writeQuorumSize, int ackQuorumSize, LedgerMetadataFormat.State state, Optional<Long> lastEntryId, Optional<Long> length, Map<Long, List<BookieSocketAddress>> ensembles, DigestType digestType, Optional<byte[]> password, long ctime, boolean storeCtime, Map<String, byte[]> customMetadata) { checkArgument(ensembles.size() > 0, "There must be at least one ensemble in the ledger"); this.metadataFormatVersion = metadataFormatVersion; this.ensembleSize = ensembleSize; this.writeQuorumSize = writeQuorumSize; this.ackQuorumSize = ackQuorumSize; this.state = state; if (lastEntryId.isPresent()) { this.lastEntryId = lastEntryId.get(); } else { this.lastEntryId = LedgerHandle.INVALID_ENTRY_ID; } length.ifPresent((l) -> this.length = l); setEnsembles(ensembles); if (state != LedgerMetadataFormat.State.CLOSED) { currentEnsemble = this.ensembles.lastEntry().getValue(); } this.digestType = digestType.equals(DigestType.MAC) ? LedgerMetadataFormat.DigestType.HMAC : LedgerMetadataFormat.DigestType.valueOf(digestType.toString()); if (password.isPresent()) { this.password = password.get(); this.hasPassword = true; } else { this.password = null; this.hasPassword = false; } this.ctime = ctime; this.storeCtime = storeCtime; this.customMetadata.putAll(customMetadata); }
Source:
<code>public synchronized void registerDeviceStatusListener(DeviceStatusListener deviceStatusListener) { if (this.devStatMan != null) { if (deviceStatusListener == null) { <START> throw new NullPointerException("It's not allowed to pass a null DeviceStatusListener."); <END> } if (deviceStatusListener.getID() != null) { devStatMan.registerDeviceListener(deviceStatusListener); } else { throw new NullPointerException("It's not allowed to pass a null ID."); } } else { devListener = new LinkedList<DeviceStatusListener>(); devListener.add(deviceStatusListener); } }</code><technical_language>throw IllegalArgumentException</technical_language>

Target:
public synchronized void registerDeviceStatusListener(DeviceStatusListener deviceStatusListener) { if (this.devStatMan != null) { if (deviceStatusListener == null) { throw new IllegalArgumentException("It's not allowed to pass null."); } if (deviceStatusListener.getDeviceStatusListenerID() != null) { devStatMan.registerDeviceListener(deviceStatusListener); } else { throw new IllegalArgumentException("It's not allowed to pass a DeviceStatusListener with ID = null."); } } else { devListener = new LinkedList<DeviceStatusListener>(); devListener.add(deviceStatusListener); } }
Source:
<code>public void visitClass(ClassTree tree) { State oldState = currentState; <START> currentState = new State(null); <END> super.visitClass(tree); currentState = oldState; }</code><technical_language>a constructor parameters passing null explicitely</technical_language>

Target:
public void visitClass(ClassTree tree) { State oldState = currentState; currentState = new State(); scan(tree.members()); currentState = oldState; }
Source:
<code>public static LiteralArgumentBuilder<CommandSource> register() { return Commands.literal("give").requires(PermLevel.ADMIN) .then(Commands.argument("bee", EnumArgument.enumArgument(BeeDefinition.class)) .then(Commands.argument("type", EnumArgument.enumArgument(EnumBeeType.class)) .then(Commands.argument("player", EntityArgument.player()) <START> .executes(a -> execute(a.getSource(), a.getArgument("bee", BeeDefinition.class), a.getArgument("type", EnumBeeType.class), EntityArgument.getPlayer(a, "player")))) <END> .executes(a -> execute(a.getSource(), a.getArgument("bee", BeeDefinition.class), a.getArgument("type", EnumBeeType.class), a.getSource().asPlayer()))) .executes(a -> execute(a.getSource(), a.getArgument("bee", BeeDefinition.class), EnumBeeType.QUEEN, a.getSource().asPlayer()))) .executes(a -> execute(a.getSource(), BeeDefinition.FOREST, EnumBeeType.QUEEN, a.getSource().asPlayer())); }</code><technical_language>bees added other mods</technical_language>

Target:
public static LiteralArgumentBuilder<CommandSource> register() { return Commands.literal("give").requires(PermLevel.ADMIN) .then(Commands.argument("bee", BeeArgument.beeArgument()) .then(Commands.argument("type", EnumArgument.enumArgument(EnumBeeType.class)) .then(Commands.argument("player", EntityArgument.player()) .executes(a -> execute(a.getSource(), a.getArgument("bee", IBee.class), a.getArgument("type", EnumBeeType.class), EntityArgument.getPlayer(a, "player")))) .executes(a -> execute(a.getSource(), a.getArgument("bee", IBee.class), a.getArgument("type", EnumBeeType.class), a.getSource().asPlayer()))) .executes(a -> execute(a.getSource(), a.getArgument("bee", IBee.class), EnumBeeType.QUEEN, a.getSource().asPlayer()))) .executes(a -> execute(a.getSource(), BeeDefinition.FOREST.createIndividual(), EnumBeeType.QUEEN, a.getSource().asPlayer())); }
Source:
<code>public int cancelIfNotRunning(List<String> jobIds) { if (CollectionUtils.isEmpty(jobIds)) { return 0; } String hql = "update JobStatus j " + "set j.state = :canceled " + "where j.id in (:jobids) and j.state in (:created, :pending)"; Query query = this.currentSession().createQuery(hql) <START> .setParameterList("jobids", jobIds) <END> .setInteger("canceled", JobState.CANCELED.ordinal()) .setInteger("created", JobState.CREATED.ordinal()) .setInteger("pending", JobState.PENDING.ordinal()); return query.executeUpdate(); }</code><technical_language>need manually convert this do a safe list, allow large collections</technical_language>

Target:
public int cancelIfNotRunning(List<String> jobIds) { int cancelled = 0; if (CollectionUtils.isEmpty(jobIds)) { return cancelled; } String hql = "update JobStatus j " + "set j.state = :canceled " + "where j.id in (:jobids) and j.state in (:created, :pending)"; Query query = this.currentSession() .createQuery(hql) .setInteger("canceled", JobState.CANCELED.ordinal()) .setInteger("created", JobState.CREATED.ordinal()) .setInteger("pending", JobState.PENDING.ordinal()); Iterable<List<String>> blocks = Iterables.partition(jobIds, AbstractHibernateCurator.IN_OPERATOR_BLOCK_SIZE); for (List<String> block : blocks) { cancelled += query.setParameterList("jobids", block).executeUpdate(); } return cancelled; }
Source:
<code>public void testCommitFailure() throws Exception { <START> setUp(); <END> String key = "key"; Schema schema = createSchema(); Struct record = createRecord(schema); Collection<SinkRecord> sinkRecords = new ArrayList<>(); for (long offset = 0; offset < 7; offset++) { SinkRecord sinkRecord = new SinkRecord(TOPIC, PARTITION, Schema.STRING_SCHEMA, key, schema, record, offset); sinkRecords.add(sinkRecord); } DataWriter hdfsWriter = new DataWriter(connectorConfig, context, avroData); MemoryStorage storage = (MemoryStorage) hdfsWriter.getStorage(); storage.setFailure(MemoryStorage.Failure.appendFailure); hdfsWriter.write(sinkRecords); assertEquals(context.timeout(), (long) connectorConfig.getLong(HdfsSinkConnectorConfig.RETRY_BACKOFF_CONFIG)); Map<String, List<Object>> data = Data.getData(); String logFile = FileUtils.logFileName(url, logsDir, TOPIC_PARTITION); List<Object> content = data.get(logFile); assertEquals(null, content); hdfsWriter.write(new ArrayList<SinkRecord>()); content = data.get(logFile); assertEquals(null, content); Thread.sleep(context.timeout()); hdfsWriter.write(new ArrayList<SinkRecord>()); content = data.get(logFile); assertEquals(6, content.size()); hdfsWriter.close(); hdfsWriter.stop(); }</code><technical_language>move tests? in this test happen in test method, a good indicator @Before</technical_language>

Target:
public void testCommitFailure() throws Exception { String key = "key"; Schema schema = createSchema(); Struct record = createRecord(schema); Collection<SinkRecord> sinkRecords = new ArrayList<>(); for (long offset = 0; offset < 7; offset++) { SinkRecord sinkRecord = new SinkRecord(TOPIC, PARTITION, Schema.STRING_SCHEMA, key, schema, record, offset); sinkRecords.add(sinkRecord); } DataWriter hdfsWriter = new DataWriter(connectorConfig, context, avroData); MemoryStorage storage = (MemoryStorage) hdfsWriter.getStorage(); storage.setFailure(MemoryStorage.Failure.appendFailure); hdfsWriter.write(sinkRecords); assertEquals(context.timeout(), (long) connectorConfig.getLong(HdfsSinkConnectorConfig.RETRY_BACKOFF_CONFIG)); Map<String, List<Object>> data = Data.getData(); String logFile = FileUtils.logFileName(url, logsDir, TOPIC_PARTITION); List<Object> content = data.get(logFile); assertEquals(null, content); hdfsWriter.write(new ArrayList<SinkRecord>()); content = data.get(logFile); assertEquals(null, content); Thread.sleep(context.timeout()); hdfsWriter.write(new ArrayList<SinkRecord>()); content = data.get(logFile); assertEquals(6, content.size()); hdfsWriter.close(); hdfsWriter.stop(); }
Source:
<code>public Model create() { <START> return getModel(); <END> }</code><technical_language>event is a resource a model, sense for this return event resource instead. get model in other places if needed calling .getModel() resource</technical_language>

Target:
public Resource create() { return getResource(); }
Source:
<code>public List<CloudCatSubscription> getSecondCloudClientDataSubscriptions() { <START> return this.secondloudClientDataSubscriptions; <END> }</code><technical_language>mispelled</technical_language>

Target:
public List<CloudCatSubscription> getSecondCloudClientDataSubscriptions() { return this.secondCloudClientDataSubscriptions; }
Source:
<code>private static List<String> coursierPart(){ return Arrays.asList("launch", "org.scalameta:fastpass_2.12:latest.stable", <START> "--main", "scala.meta.internal.fastpass.pantsbuild.BloopPants", <END> "--" ); }</code><technical_language>preparing a PR add this main class suggestion "--main", "scala.meta.fastpass.Fastpass",</technical_language>

Target:
private static List<String> coursierPart(){ return Arrays.asList("launch", "org.scalameta:fastpass_2.12:latest.stable", "--main", "scala.meta.fastpass.Fastpass", "--" ); }
Source:
<code>private void setManagedVideoDevices(VmBase vmBase) { Map<Guid, VmDevice> managedDeviceMap = vmBase.getManagedDeviceMap(); if (managedDeviceMap == null) { managedDeviceMap = new HashMap<Guid, VmDevice>(); } List<VmDevice> devices = DbFacade.getInstance() .getVmDeviceDao() .getVmDeviceByVmIdAndType(vmBase.getId(), VmDeviceGeneralType.VIDEO); for (VmDevice device : devices) { <START> if (device.getType() == VmDeviceGeneralType.VIDEO) { <END> managedDeviceMap.put(device.getDeviceId(), device); } } }</code><technical_language>changed dao call if condition is longer neccessary loop removed completely - replace of Entities.businessEntitiesById</technical_language>

Target:
private void setManagedVideoDevices(VmBase vmBase) { Map<Guid, VmDevice> managedDeviceMap = vmBase.getManagedDeviceMap(); if (managedDeviceMap == null) { managedDeviceMap = new HashMap<Guid, VmDevice>(); } List<VmDevice> devices = DbFacade.getInstance() .getVmDeviceDao() .getVmDeviceByVmIdAndType(vmBase.getId(), VmDeviceGeneralType.VIDEO); for (VmDevice device : devices) { managedDeviceMap.put(device.getDeviceId(), device); } }
Source:
<code><START> public static Boolean isNumerical(Schema.Type type) { <END> return Schema.Type.INT.equals(type) || Schema.Type.LONG.equals(type) || Schema.Type.DOUBLE.equals(type) || Schema.Type.FLOAT.equals(type); }</code><technical_language>need is[Type] methods for avro type. do it</technical_language>

Target:
public static boolean isNumerical(Schema.Type type) { return Schema.Type.INT.equals(type) || Schema.Type.LONG.equals(type) || Schema.Type.DOUBLE.equals(type) || Schema.Type.FLOAT.equals(type); }
Source:
<code>private boolean validateDiscardAfterDeleteLegal(StorageDomainValidator storageDomainValidator) { if (getStoragePoolId() != null && <START> validate(storageDomainValidator.isDiscardAfterDeleteSupportedByDcVersion(getStoragePool().getCompatibilityVersion()))) { <END> return false; } return validate(storageDomainValidator.isDiscardAfterDeleteLegalForExistingStorageDomain()); }</code><technical_language>Please move this part a new line</technical_language>

Target:
private boolean validateDiscardAfterDeleteLegal(StorageDomainValidator storageDomainValidator) { if (getStoragePoolId() != null && !validate(storageDomainValidator.isDiscardAfterDeleteSupportedByDcVersion(getStoragePool().getCompatibilityVersion()))) { return false; } return validate(storageDomainValidator.isDiscardAfterDeleteLegalForExistingStorageDomain()); }
Source:
<code><START> public static Unit from(@Nullable final TimeUnit timeUnit) { <END> if (timeUnit == TimeUnit.DAYS) { return DAY; } else if (timeUnit == TimeUnit.HOURS) { return HOUR; } else if (timeUnit == TimeUnit.MINUTES) { return MINUTE; } else if (timeUnit == TimeUnit.SECONDS) { return SECOND; } else if (timeUnit == TimeUnit.MILLISECONDS) { return MILLISECOND; } else if (timeUnit == TimeUnit.MICROSECONDS) { return MICROSECOND; } else if (timeUnit == TimeUnit.NANOSECONDS) { return NANOSECOND; } else { return null; } }</code><technical_language>provide a variant returns Optional</technical_language>

Target:
@Nullable public static Unit from(@Nullable final TimeUnit timeUnit) { if (timeUnit == null) { return null; } return TIME_UNIT_MAP.get(timeUnit); }
Source:
<code>public void addSteps(MigrationStepRegistry registry) { registry .add(2000, "Delete settings defined in sonar.properties from PROPERTIES table", DeleteSettingsDefinedInSonarDotProperties.class) .add(2001, "Add scope to rules", AddRuleScope.class) .add(2002, "Set rules scope to MAIN", SetRuleScopeToMain.class) .add(2003, "Make scope not nullable in rules", MakeScopeNotNullableInRules.class) .add(2004, "Use rule id in QPROFILE_CHANGES", UseRuleIdInQPChangesData.class) .add(2005, "Create table DEPRECATED_RULE_KEYS", CreateDeprecatedRuleKeysTable.class) .add(2006, "Clean orphans in Compute Engine child tables", CleanCeChildTablesOrphans.class) .add(2007, "Update PERMISSION_TEMPLATES.KEYS ", UpdatePermissionTooLongTemplateKeys.class) .add(2008, "Increase branch type size in PROJECT_BRANCHES", IncreaseBranchTypeSizeForPullRequest.class) <START> .add(2009, "Add key type column in PROJECT_BRANCHES", AddKeyTypeInProjectBranches.class); <END> ; }</code><technical_language>minor: key_type instead of key type</technical_language>

Target:
public void addSteps(MigrationStepRegistry registry) { registry .add(2000, "Delete settings defined in sonar.properties from PROPERTIES table", DeleteSettingsDefinedInSonarDotProperties.class) .add(2001, "Add scope to rules", AddRuleScope.class) .add(2002, "Set rules scope to MAIN", SetRuleScopeToMain.class) .add(2003, "Make scope not nullable in rules", MakeScopeNotNullableInRules.class) .add(2004, "Use rule id in QPROFILE_CHANGES", UseRuleIdInQPChangesData.class) .add(2005, "Create table DEPRECATED_RULE_KEYS", CreateDeprecatedRuleKeysTable.class) .add(2006, "Clean orphans in Compute Engine child tables", CleanCeChildTablesOrphans.class) .add(2007, "Update PERMISSION_TEMPLATES.KEYS ", UpdatePermissionTooLongTemplateKeys.class) .add(2008, "Increase branch type size in PROJECT_BRANCHES", IncreaseBranchTypeSizeForPullRequest.class) .add(2009, "Add key_type column in PROJECT_BRANCHES", AddKeyTypeInProjectBranches.class) .add(2010, "Fill key_type column in PROJECT_BRANCHES", SetKeyTypeToBranchInProjectBranches.class) .add(2011, "Make key_type not nullable in PROJECT_BRANCHES", MakeKeyTypeNotNullableInProjectBranches.class) .add(2012, "Replace index in PROJECT_BRANCHES", ReplaceIndexInProjectBranches.class) ; }
Source:
<code>public String parse(String text, Locale locale) throws ParseException { if (StringUtils.isNotBlank(text)) { try { lawJournalEntryCodeExtractor.extractYear(text); lawJournalEntryCodeExtractor.extractJournalNo(text); <START> lawJournalEntryCodeExtractor.extractEntry(text); <END> } catch (IllegalArgumentException e) { throw new WrongRequestParameterException("invalid value"); } } return text; }</code><technical_language>clearer if lawJournalEntryCodeExtractor a method isCorrectLawJournalEntryCode(lawJornalEntryCode) beginning of extract method</technical_language>

Target:
public String parse(String text, Locale locale) throws ParseException { if (!lawJournalEntryCodeExtractor.isCorrectLawJournalEntryCode(text)) { throw new WrongRequestParameterException(String.format("invalid value '%s', input should be in format 'year/journal_number/entry_number'", text)); } return text; }
Source:
<code>private static void newZipFile(File zipFile) throws URISyntaxException, IOException { <START> if (zipFile.exists()) { <END> if (!zipFile.delete()) { END bytes in the file) throw new IOException("Cannot delete file " + zipFile); } } Map<String, String> env = new HashMap<>(); env.put("create", Boolean.TRUE.toString()); try (FileSystem ignored = FileSystems.newFileSystem(getZipURI(zipFile), env)) { } }</code><technical_language>2 if combined 1 if &&</technical_language>

Target:
private static void newZipFile(File zipFile) throws URISyntaxException, IOException { if (zipFile.exists() && !zipFile.delete()) { END bytes in the file) throw new IOException("Cannot delete file " + zipFile); } Map<String, Object> env = new HashMap<>(); env.put("create", Boolean.TRUE.toString()); try (FileSystem ignored = FileSystems.newFileSystem(getZipURI(zipFile), env)) { } }
Source:
<code>public ResponseEntity<?> createOrGetSubscription(@Valid @RequestBody final SubscriptionBase subscriptionBase, final Errors errors, final NativeWebRequest request, final Client client) { if (!featureToggleService.isFeatureEnabled(HIGH_LEVEL_API)) { return new ResponseEntity<>(NOT_IMPLEMENTED); } if (errors.hasErrors()) { return create(new ValidationProblem(errors), request); } try { return createSubscription(subscriptionBase, request, client); } catch (final DuplicatedSubscriptionException e) { try { <START> Subscription existingSubscription = getExistingSubscription(subscriptionBase); <END> UriComponents path = SUBSCRIPTION_PATH.buildAndExpand(existingSubscription.getId()); return status(OK).location(path.toUri()).body(existingSubscription); } catch (final ServiceUnavailableException ex) { LOG.error("Error occurred during fetching existing subscription", ex); return create(e.asProblem(), request); } catch (final NoSuchSubscriptionException | InternalNakadiException ex) { LOG.error("Error occurred during fetching existing subscription", ex); return create(INTERNAL_SERVER_ERROR, ex.getProblemMessage(), request); } } catch (final NakadiException e) { LOG.error("Error occurred during subscription creation", e); return create(e.asProblem(), request); } }</code><technical_language>final</technical_language>

Target:
public ResponseEntity<?> createOrGetSubscription(@Valid @RequestBody final SubscriptionBase subscriptionBase, final Errors errors, final NativeWebRequest request, final Client client) { if (!featureToggleService.isFeatureEnabled(HIGH_LEVEL_API)) { return new ResponseEntity<>(NOT_IMPLEMENTED); } if (errors.hasErrors()) { return create(new ValidationProblem(errors), request); } try { return createSubscription(subscriptionBase, request, client); } catch (final DuplicatedSubscriptionException e) { try { final Subscription existingSubscription = getExistingSubscription(subscriptionBase); final UriComponents path = SUBSCRIPTION_PATH.buildAndExpand(existingSubscription.getId()); return status(OK).location(path.toUri()).body(existingSubscription); } catch (final ServiceUnavailableException ex) { LOG.error("Error occurred during fetching existing subscription", ex); return create(e.asProblem(), request); } catch (final NoSuchSubscriptionException | InternalNakadiException ex) { LOG.error("Error occurred during fetching existing subscription", ex); return create(INTERNAL_SERVER_ERROR, ex.getProblemMessage(), request); } } catch (final NakadiException e) { LOG.error("Error occurred during subscription creation", e); return create(e.asProblem(), request); } }
Source:
<code>public void registerService(ServiceDescription description) throws IOException { for (JmDNS instance : jmdnsInstances) { <START> logger.debug("Registering new service at port (instance {})", description.serviceType, <END> description.servicePort, instance.getName()); ServiceInfo serviceInfo = ServiceInfo.create(description.serviceType, description.serviceName, description.servicePort, 0, 0, description.serviceProperties); instance.registerService(serviceInfo); } }</code><technical_language>suggest change this logger.debug("Registering new service {}:{} ({})", description.serviceType, instance.getInetAddress().getHostAddress(), description.servicePort, instance.getName());</technical_language>

Target:
public void registerService(ServiceDescription description) throws IOException { for (JmDNS instance : jmdnsInstances) { logger.debug("Registering new service at {}:{} ({})", description.serviceType, instance.getInetAddress().getHostAddress(), description.servicePort, instance.getName()); ServiceInfo serviceInfo = ServiceInfo.create(description.serviceType, description.serviceName, description.servicePort, 0, 0, description.serviceProperties); instance.registerService(serviceInfo); } }
Source:
<code>protected void onInit() { synchronized (this.initializationMonitor) { if (this.initialized) { return; } Assert.notNull(this.trigger, "Trigger is required"); if (this.taskExecutor != null) { if (!(this.taskExecutor instanceof ErrorHandlingTaskExecutor)) { if (this.errorHandler == null) { Assert.notNull(this.getBeanFactory(), "BeanFactory is required"); this.errorHandler = new MessagePublishingErrorHandler( new BeanFactoryChannelResolver(getBeanFactory())); this.errorHandlerIsDefault = true; } this.taskExecutor = new ErrorHandlingTaskExecutor(this.taskExecutor, this.errorHandler); } } if (this.transactionSynchronizationFactory == null) { this.transactionSynchronizationFactory = new PassthroughTransactionSynchronizationFactory(); <START> } <END> this.initialized = true; } }</code><technical_language>want hit of saving message in a TL __if poller is transactional__ - easily in XML parser DSL spec, easily @Poller annotation; need add a transactional property @Poller for that. other hand, "around" advice throw exception need access message if throws exception proceed. So, I mind if apply if advice chain is > 0 length - simplest solution work in cases while extra unneeded hit if configures advice chain</technical_language>

Target:
protected void onInit() { synchronized (this.initializationMonitor) { if (this.initialized) { return; } Assert.notNull(this.trigger, "Trigger is required"); if (this.taskExecutor != null) { if (!(this.taskExecutor instanceof ErrorHandlingTaskExecutor)) { if (this.errorHandler == null) { Assert.notNull(this.getBeanFactory(), "BeanFactory is required"); this.errorHandler = new MessagePublishingErrorHandler( new BeanFactoryChannelResolver(getBeanFactory())); this.errorHandlerIsDefault = true; } this.taskExecutor = new ErrorHandlingTaskExecutor(this.taskExecutor, this.errorHandler); } } if (this.transactionSynchronizationFactory == null && this.adviceChain != null) { if (this.adviceChain.stream().anyMatch(TransactionInterceptor.class::isInstance)) { this.transactionSynchronizationFactory = new PassthroughTransactionSynchronizationFactory(); } } this.initialized = true; } }
Source:
<code>public TextEditBasedChange[] getAllChanges(){ Set<ICompilationUnit> cuSet= fMap.keySet(); ICompilationUnit[] cus= cuSet.toArray(new ICompilationUnit[cuSet.size()]); <START> Arrays.sort(cus, (o1, o2) -> { <END> String name1= o1.getElementName(); String name2= o2.getElementName(); return name1.compareTo(name2); }); TextEditBasedChange[] textChanges= new TextEditBasedChange[cus.length]; for (int i= 0; i < cus.length; i++) { textChanges[i]= fMap.get(cus[i]); } return textChanges; }</code><technical_language>patch, 5 lines replaced (importing java.util.Comparator): Arrays.sort(cus, Comparator.comparing(ICompilationUnit::getElementName));</technical_language>

Target:
public TextEditBasedChange[] getAllChanges(){ Set<ICompilationUnit> cuSet= fMap.keySet(); ICompilationUnit[] cus= cuSet.toArray(new ICompilationUnit[cuSet.size()]); Arrays.sort(cus, Comparator.comparing(ICompilationUnit::getElementName)); TextEditBasedChange[] textChanges= new TextEditBasedChange[cus.length]; for (int i= 0; i < cus.length; i++) { textChanges[i]= fMap.get(cus[i]); } return textChanges; }
Source:
<code><START> public synchronized void init() { <END> if (hasBeenInitialized) { throw new IllegalStateException("This map has already been initialized."); } List<Binding<?>> rootResourceBindings = new ArrayList<>(); for (Binding<?> binding : injector.getBindings().values()) { Type type = binding.getKey().getTypeLiteral().getType(); if (type instanceof Class) { Class<?> beanClass = (Class) type; if (GetRestful.isRootResource(beanClass)) { rootResourceBindings.add(binding); } } } for (Binding<?> binding : rootResourceBindings) { Class<?> clazz = (Class) binding.getKey().getTypeLiteral().getType(); if (Proxy.isProxyClass(clazz)) { for (Class<?> intf : clazz.getInterfaces()) { ResourceClass resourceClass = ResourceBuilder.rootResourceFromAnnotations(intf); registerConcreteMethods(resourceClass, clazz); } } else { ResourceClass resourceClass = ResourceBuilder.rootResourceFromAnnotations(clazz); registerConcreteMethods(resourceClass, clazz); } } lock(); }</code><technical_language>strictly critical change for this PR, in future I type of methods return a self-ref do some chaining in cases flow is instantiate initialize</technical_language>

Target:
public synchronized MethodLocator init() { if (hasBeenInitialized) { throw new IllegalStateException("This map has already been initialized."); } List<Binding<?>> rootResourceBindings = new ArrayList<>(); for (Binding<?> binding : injector.getBindings().values()) { Type type = binding.getKey().getTypeLiteral().getType(); if (type instanceof Class) { Class<?> beanClass = (Class) type; if (GetRestful.isRootResource(beanClass)) { rootResourceBindings.add(binding); } } } for (Binding<?> binding : rootResourceBindings) { Class<?> clazz = (Class) binding.getKey().getTypeLiteral().getType(); if (Proxy.isProxyClass(clazz)) { for (Class<?> intf : clazz.getInterfaces()) { ResourceClass resourceClass = ResourceBuilder.rootResourceFromAnnotations(intf); registerConcreteMethods(resourceClass, clazz); } } else { ResourceClass resourceClass = ResourceBuilder.rootResourceFromAnnotations(clazz); registerConcreteMethods(resourceClass, clazz); } } lock(); return this; }
Source:
<code>public void visit(VarRefNode varRefNode) { String name = varRefNode.getName(); if (name.equals("this")) { mv.visitVarInsn(ALOAD, 0); } else if (ScopeStack.isSpecial(name)) { String object; switch (name) { case "true": object = "True"; break; case "false": object = "False"; break; default: object = "Nil"; break; } mv.visitTypeInsn(NEW, object); mv.visitInsn(DUP); mv.visitMethodInsn(INVOKESPECIAL, object, "<init>", "()V", false); } else { try { VarDeclNode decl = scope.getVarDeclNode(varRefNode.getName()); if (decl.isMethodVariable()) { mv.visitVarInsn(ALOAD, 1 + decl.getOffset()); } else if (decl.isClassField()) { mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETFIELD, ((ClazzNode) decl.getScope().getNode()).getName(), decl.getName(), "Lorg/twnc/runtime/BObject;"); } else { <START> mv.visitTypeInsn(NEW, "Nil"); <END> mv.visitInsn(DUP); mv.visitMethodInsn(INVOKESPECIAL, "Nil", "<init>", "()V", false); } } catch (VariableNotDeclaredException e) { e.printStackTrace(); } } super.visit(varRefNode); }</code><technical_language>this sense a default? is this secretly a bad error case</technical_language>

Target:
public void visit(VarRefNode varRefNode) { String name = varRefNode.getName(); if (name.equals("this")) { mv.visitVarInsn(ALOAD, 0); } else if (ScopeStack.isSpecial(name)) { String object; switch (name) { case "true": object = "True"; break; case "false": object = "False"; break; default: object = "Nil"; break; } mv.visitTypeInsn(NEW, object); mv.visitInsn(DUP); mv.visitMethodInsn(INVOKESPECIAL, object, "<init>", "()V", false); } else { try { VarDeclNode decl = scope.getVarDeclNode(varRefNode.getName()); if (decl.isMethodVariable()) { mv.visitVarInsn(ALOAD, 1 + decl.getOffset()); } else if (decl.isClassField()) { mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETFIELD, ((ClazzNode) decl.getScope().getNode()).getName(), decl.getName(), "Lorg/twnc/runtime/BObject;"); } else { throw new UnknownVariableDeclarationLocation(); } } catch (VariableNotDeclaredException e) { e.printStackTrace(); } } super.visit(varRefNode); }
Source:
<code>private EnvironmentVariableContext getEnvironmentVariableContextFromEnvironment(String pipelineName) { EnvironmentConfig environmentConfig = environmentConfigService.environmentForPipeline(pipelineName); if (environmentConfig == null) { return null; } secretParamResolver.resolve(environmentConfig); EnvironmentVariableContext environmentVariableContext = new EnvironmentVariableContext(); environmentConfig.getVariables().forEach(variable -> { <START> String resolvedValue = variable.getSecretParams().substitute(variable.getValue()); <END> environmentVariableContext.setProperty(variable.getName(), resolvedValue, variable.isSecure() || variable.hasSecretParams()); }); return environmentVariableContext; }</code><technical_language>Consider EnvironmentVariableConfig return a resolved substituting here</technical_language>

Target:
private EnvironmentVariableContext getEnvironmentVariableContextFromEnvironment(String pipelineName) { EnvironmentConfig environmentConfig = environmentConfigService.environmentForPipeline(pipelineName); if (environmentConfig == null) { return null; } secretParamResolver.resolve(environmentConfig); EnvironmentVariableContext environmentVariableContext = new EnvironmentVariableContext(); environmentConfig.getVariables().forEach(variable -> { environmentVariableContext.setProperty(variable.getName(), variable.valueForCommandline(), variable.isSecure() || variable.hasSecretParams()); }); return environmentVariableContext; }
Source:
<code>public void shouldHaveEnglishAsFirstAvailableLocale() { List<String> locales = LocaleUtils.getAvailableLocales(); <START> String defaultLocale = locales.get(0); <END> assertThat(defaultLocale, is(equalTo("en_GB"))); }</code><technical_language>variable renamed firstAvailableLocale</technical_language>

Target:
public void shouldHaveEnglishAsFirstAvailableLocale() { List<String> locales = LocaleUtils.getAvailableLocales(); String firstAvailableLocale = locales.get(0); assertThat(firstAvailableLocale, is(equalTo("en_GB"))); }
Source:
<code>public void testNodeSuspendedReturnsTrueWhenSuspended() { expect(node.getStatus()).andReturn(Status.SUSPENDED).atLeastOnce(); expect(node.getBackendStatus()).andReturn(null).atLeastOnce(); replay(node); <START> replay(computeService); <END> AtomicNodeSuspended nodeRunning = new AtomicNodeSuspended(computeService); AtomicReference<NodeMetadata> reference = Atomics.newReference(node); Assert.assertTrue(nodeRunning.apply(reference)); Assert.assertEquals(reference.get(), node); }</code><technical_language>[minor] replay(node, computeService);</technical_language>

Target:
public void testNodeSuspendedReturnsTrueWhenSuspended() { expect(node.getStatus()).andReturn(Status.SUSPENDED).atLeastOnce(); expect(node.getBackendStatus()).andReturn(null).atLeastOnce(); replay(node, computeService); AtomicNodeSuspended nodeSuspended = new AtomicNodeSuspended(computeService); AtomicReference<NodeMetadata> reference = Atomics.newReference(node); Assert.assertTrue(nodeSuspended.apply(reference)); Assert.assertEquals(reference.get(), node); }