auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected VdcActionParametersBase getParametersForTask(VdcActionType actionType, VdcActionParametersBase parameters) { VdcActionType parentCommandType = getParentCommand(actionType); VdcActionParametersBase parentParameters = null; <START> if (parentHasCallback()) { if (getTaskType() == AsyncTaskType.notSupported) { parentParameters = getParameters().getParentParameters(); } } else { parentParameters = getParameters().getParentParameters(); } <END> if (parentCommandType == VdcActionType.Unknown || parentParameters == null) { return parameters; } parentParameters.setExecutionReason(parameters.getExecutionReason()); parentParameters.setCommandType(parentCommandType); return parentParameters; }</code><technical_language>this replaced getParentCommand()</technical_language>

Target:
protected VdcActionParametersBase getParametersForTask(VdcActionType actionType, VdcActionParametersBase parameters) { VdcActionType parentCommandType = getParentCommandType(actionType); VdcActionParametersBase parentParameters = getParentParameters(); if (parentCommandType == VdcActionType.Unknown || parentParameters == null) { return parameters; } parentParameters.setExecutionReason(parameters.getExecutionReason()); parentParameters.setCommandType(parentCommandType); return parentParameters; }
Source:
<code>private boolean hasNonEmptyNameDefinition(EStructuralFeature labelStyleFeature) { boolean hasEmptyNameDefinition = true; if (edge.getActualMapping() instanceof EdgeMapping) { EdgeMapping actualMapping = (EdgeMapping) edge.getActualMapping(); EdgeStyleDescription style = actualMapping.getStyle(); if (style != null && style.eGet(labelStyleFeature) != null) { <START> String labelExpression = ((BasicLabelStyleDescription) style.eGet(labelStyleFeature)).getLabelExpression(); <END> hasEmptyNameDefinition = labelExpression.trim().length() != 0; hasEmptyNameDefinition = hasEmptyNameDefinition && isLabelExpressionEmpty(labelExpression); } } return hasEmptyNameDefinition; }</code><technical_language>avoid call eGet method twice</technical_language>

Target:
private boolean hasNonEmptyNameDefinition(EStructuralFeature labelStyleFeature) { boolean hasEmptyNameDefinition = true; if (edge.getActualMapping() instanceof EdgeMapping) { EdgeMapping actualMapping = (EdgeMapping) edge.getActualMapping(); EdgeStyleDescription style = actualMapping.getStyle(); if (style != null) { Object labelStyle = style.eGet(labelStyleFeature); if (labelStyle instanceof BasicLabelStyleDescription) { String labelExpression = ((BasicLabelStyleDescription) labelStyle).getLabelExpression(); hasEmptyNameDefinition = labelExpression.trim().length() != 0; hasEmptyNameDefinition = hasEmptyNameDefinition && isLabelExpressionEmpty(labelExpression); } } } return hasEmptyNameDefinition; }
Source:
<code>public boolean removeIfNotReferenced(KerberosKeytabEntity kerberosKeytabEntity) { if (kerberosKeytabEntity != null) { <START> if (!CollectionUtils.isEmpty(kerberosKeytabEntity.getKerberosKeytabPrincipalEntities())) { <END> ArrayList<String> ids = new ArrayList<>(); for (KerberosKeytabPrincipalEntity entity : kerberosKeytabEntity.getKerberosKeytabPrincipalEntities()) { Long id = entity.getKkpId(); if (id != null) { ids.add(String.valueOf(id)); } } LOG.debug(String.format("keytab entry for %s is still referenced by [%s]", kerberosKeytabEntity.getKeytabPath(), String.join(",", ids))); } else { LOG.debug(String.format("keytab entry for %s is no longer referenced. It will be removed.", kerberosKeytabEntity.getKeytabPath())); remove(kerberosKeytabEntity); return true; } } return false; }</code><technical_language>nit: CollectionUtils.isNotEmpty(...)</technical_language>

Target:
public boolean removeIfNotReferenced(KerberosKeytabEntity kerberosKeytabEntity) { if (kerberosKeytabEntity != null) { if (CollectionUtils.isNotEmpty(kerberosKeytabEntity.getKerberosKeytabPrincipalEntities())) { ArrayList<String> ids = new ArrayList<>(); for (KerberosKeytabPrincipalEntity entity : kerberosKeytabEntity.getKerberosKeytabPrincipalEntities()) { Long id = entity.getKkpId(); if (id != null) { ids.add(String.valueOf(id)); } } LOG.debug(String.format("keytab entry for %s is still referenced by [%s]", kerberosKeytabEntity.getKeytabPath(), String.join(",", ids))); } else { LOG.debug(String.format("keytab entry for %s is no longer referenced. It will be removed.", kerberosKeytabEntity.getKeytabPath())); remove(kerberosKeytabEntity); return true; } } return false; }
Source:
<code>public JsonNode getBodyJson() { ObjectNode node = JsonNodeFactory.instance.objectNode(); if (queryExpression != null) { node.set("query", queryExpression.toJson()); } <START> appendExecutionToJson(node); <END> return node; }</code><technical_language>if getBodyJson is implemented in abstractLightblueDataRequest a method creates a json node, adds execution it, in subclasses, overriding getBodyJson call super.getBodyJson(), add bits it</technical_language>

Target:
public JsonNode getBodyJson() { ObjectNode node = (ObjectNode)super.getBodyJson(); if (queryExpression != null) { node.set("query", queryExpression.toJson()); } return node; }
Source:
<code>public ParametersDefinitionProperty(@Nonnull ParameterDefinition... parameterDefinitions) { <START> if (parameterDefinitions != null) { <END> this.parameterDefinitions = Arrays.asList(parameterDefinitions); } else { this.parameterDefinitions = Collections.emptyList(); } }</code><technical_language>DRY <code>this(parameterDefinitions != null ? Arrays.asList(parameterDefinitions) : null)</code></technical_language>

Target:
public ParametersDefinitionProperty(@Nonnull ParameterDefinition... parameterDefinitions) { if (parameterDefinitions == null) { throw new NullPointerException("ParameterDefinitions is null when this is a not valid value"); } this.parameterDefinitions = Arrays.asList(parameterDefinitions) ; }
Source:
<code>public String getGroup(Object instance) { PrivilegedAction<Object> action = () -> invokeAccessibly(instance, method, Util.EMPTY_OBJECT_ARRAY); Object object = System.getSecurityManager() == null ? action.run() : AccessController.doPrivileged(action); <START> return String.class.cast(object); <END> }</code><technical_language>Instead of invoking lambda do if (System.getSecurityManager() == null) { return String.class.cast(invokeAccessibly(instance, method, Util.EMPTY_OBJECT_ARRAY)); } else { ... // priv action }</technical_language>

Target:
public String getGroup(Object instance) { Object object; if (System.getSecurityManager() == null) { object = invokeAccessibly(instance, method, Util.EMPTY_OBJECT_ARRAY); } else { object = AccessController.doPrivileged((PrivilegedAction<Object>) () -> invokeAccessibly(instance, method, Util.EMPTY_OBJECT_ARRAY)); } return String.class.cast(object); }
Source:
<code>public XML getXml(ObjectNode node, String location, ParseResult result){ if (node == null) { return null; } XML xml = new XML(); String value = getString("name", node, false, location + ".name", result); xml.setName(value); value = getString("namespace", node, false, location + ".url", result); xml.setNamespace(value); value = getString("prefix", node, false, location + ".email", result); xml.setPrefix(value); Boolean attribute = getBoolean("attribute", node, false, location, result); xml.setAttribute(attribute); Boolean wrapped = getBoolean("wrapped", node, false, location, result); xml.setWrapped(wrapped); <START> return xml; <END> }</code><technical_language>Provide messages in ParseResult if missing required fields</technical_language>

Target:
public XML getXml(ObjectNode node, String location, ParseResult result){ if (node == null) { return null; } XML xml = new XML(); String value = getString("name", node, false, location + ".name", result); if(StringUtils.isNotBlank(value)){ xml.setName(value); } value = getString("namespace", node, false, location + ".url", result); if(StringUtils.isNotBlank(value)){ xml.setNamespace(value); } value = getString("prefix", node, false, location + ".email", result); if(StringUtils.isNotBlank(value)){ xml.setPrefix(value); } Boolean attribute = getBoolean("attribute", node, false, location, result); if(attribute != null){ xml.setAttribute(attribute); } Boolean wrapped = getBoolean("wrapped", node, false, location, result); if(wrapped != null){ xml.setWrapped(wrapped); } Map <String,Object> extensions = getExtensions(node,location,result); if(extensions != null && extensions.size() > 0) { xml.setExtensions(extensions); } return xml; }
Source:
<code>public void modifiedService(ServiceReference reference, Object service) { logger.debug("ModuleHandlerFactory modified, updating handlers"); ModuleHandlerFactory moduleHandlerFactory = ((ModuleHandlerFactory) service); @SuppressWarnings("unchecked") <START> Collection<String> removed_handlers = (Collection<String>) reference.getProperty("removed_handlers"); <END> @SuppressWarnings("unchecked") Collection<String> added_handlers = (Collection<String>) reference.getProperty("added_handlers"); if (removed_handlers != null && removed_handlers.size() > 0) { removeMissingModuleTypes(removed_handlers); } if (added_handlers != null && added_handlers.size() > 0) { addNewModuleTypes(moduleHandlerFactory, added_handlers); } }</code><technical_language>this factory correctly set properties? find implementation do requirement? moduleHandlerFactories map, iterate remove module types anymore in "new" list of supported types simply add types in moduleHandlerFactories map</technical_language>

Target:
public void modifiedService(ServiceReference reference, Object service) { logger.debug("ModuleHandlerFactory modified, updating handlers"); ModuleHandlerFactory moduleHandlerFactory = ((ModuleHandlerFactory) service); Collection<String> types = new HashSet<String>(moduleHandlerFactory.getTypes()); HashSet<String> newTypes = new HashSet<String>(moduleHandlerFactory.getTypes()); ArrayList<String> removedTypes = new ArrayList<String>(); for (Map.Entry<String, ModuleHandlerFactory> entry : moduleHandlerFactories.entrySet()) { if (entry.getValue().equals(moduleHandlerFactory)) { String key = entry.getKey(); if (types.contains(key)) { newTypes.remove(key); } else { removedTypes.add(key); } } } if (removedTypes.size() > 0) { removeMissingModuleTypes(removedTypes); } if (newTypes.size() > 0) { addNewModuleTypes(moduleHandlerFactory, newTypes); } }
Source:
<code>public void testStaleRemoteLocks() throws Exception { <START> tm(1).begin(); <END> try { cache(1).put(1, "val_1"); cache(1).put(2, "val_2"); tm(1).commit(); } catch (Throwable e) { if (tm(1).getTransaction() != null) { tm(1).rollback(); } } assertValue(1, 1, "val_1"); assertValue(1, 2, "val_2"); assertFalse(checkLocked(1, 1)); assertFalse(checkLocked(1, 2)); eventually(new Condition() { @Override public boolean isSatisfied() throws Exception { return !checkLocked(0, 1) && !checkLocked(0, 2); } }); cache(0).put(1, "new_val_1"); assertValue(0, 1, "new_val_1"); assertValue(1, 1, null); assertValue(1, 2, "val_2"); }</code><technical_language>This begin/commit/rollback pattern is present source code encapsulated TestingUtil.withTx, instead? :)</technical_language>

Target:
public void testStaleRemoteLocks() throws Exception { TestingUtil.withTx(tm(1), new Callable<Object>() { @Override public Object call() throws Exception { cache(1).put(1, "val_1"); cache(1).put(2, "val_2"); return null; } }); assertValue(1, 1, "val_1"); assertValue(1, 2, "val_2"); assertFalse(checkLocked(1, 1)); assertFalse(checkLocked(1, 2)); eventually(new Condition() { @Override public boolean isSatisfied() throws Exception { return !checkLocked(0, 1) && !checkLocked(0, 2); } }); cache(0).put(1, "new_val_1"); assertValue(0, 1, "new_val_1"); assertValue(1, 1, null); assertValue(1, 2, "val_2"); }
Source:
<code>public XmlMementoSerializer(ClassLoader classLoader) { this.classLoader = checkNotNull(classLoader, "classLoader"); xstream.alias("brooklyn", MutableBrooklynMemento.class); xstream.alias("entity", BasicEntityMemento.class); xstream.alias("location", BasicLocationMemento.class); xstream.alias("configKey", BasicConfigKey.class); xstream.alias("attributeSensor", BasicAttributeSensor.class); <START> xstream.registerConverter(new ConverterImpl(Location.class, new Function<Location,String>() { <END> @Override public String apply(Location input) { return (input != null) ? input.getId() : null; }})); xstream.registerConverter(new ConverterImpl(Entity.class, new Function<Entity,String>() { @Override public String apply(Entity input) { return (input != null) ? input.getId() : null; }})); xstream.registerConverter(new ConverterImpl(EntityAdjunct.class, new Function<EntityAdjunct,String>() { @Override public String apply(EntityAdjunct input) { return (input != null) ? input.getId() : null; }})); }</code><technical_language>i worth extracting Identifiable interface getId() classes defining a constant Function<Identifiable,String> IDENTITY_FUNCTION invokes getId() is in 3 places</technical_language>

Target:
public XmlMementoSerializer(ClassLoader classLoader) { this.classLoader = checkNotNull(classLoader, "classLoader"); xstream.alias("brooklyn", MutableBrooklynMemento.class); xstream.alias("entity", BasicEntityMemento.class); xstream.alias("location", BasicLocationMemento.class); xstream.alias("configKey", BasicConfigKey.class); xstream.alias("attributeSensor", BasicAttributeSensor.class); xstream.registerConverter(new ConverterImpl(Location.class)); xstream.registerConverter(new ConverterImpl(Entity.class)); xstream.registerConverter(new ConverterImpl(EntityAdjunct.class)); }
Source:
<code>public String createEntity(Referenceable referenceable) throws AtlasException { String entityJSON = InstanceSerialization.toJson(referenceable, true); log.debug("Creating new entity [{}]", entityJSON); List<String> guids = _createEntities(entityJSON); log.debug("Created instance for type [{}]", referenceable.getTypeName() + ", guids: " + guids); <START> if(guids == null || guids.isEmpty()) { <END> return null; } return guids.get(0); }</code><technical_language>merge this single line ternary opeator. Lets method return</technical_language>

Target:
public String createEntity(Referenceable referenceable) throws AtlasException { String entityJSON = InstanceSerialization.toJson(referenceable, true); LOG.debug("Creating new entity [{}]", entityJSON); List<String> guids = _createEntities(entityJSON); LOG.debug("Created instance for type [{}]", referenceable.getTypeName() + ", guids: " + guids); return guids != null && !guids.isEmpty() ? guids.get(0) : null; }
Source:
<code>void dropTables(final Set<TableReference> tablesToDrop) { try { clientPool.runWithRetry(client -> { KsDef ks = client.describe_keyspace(config.getKeyspaceOrThrow()); Set<TableReference> existingTables = Sets.newHashSet(); existingTables.addAll(ks.getCf_defs().stream() .map(CassandraKeyValueServices::tableReferenceFromCfDef) .collect(Collectors.toList())); for (TableReference table : tablesToDrop) { CassandraVerifier.sanityCheckTableName(table); if (existingTables.contains(table)) { CassandraKeyValueServices.runWithWaitingForSchemas( () -> truncateThenDrop(table, client), config, client, "dropping the column family for table " + table + " in a call to drop tables"); <START> cassandraTableMetadata.deleteAllRowsForTable(table); <END> } else { log.warn("Ignored call to drop a table ({}) that did not exist.", LoggingArgs.tableRef(table)); } } return null; }); } catch (Exception e) { throw Throwables.unwrapAndThrowAtlasDbDependencyException(e); } }</code><technical_language>mention, this is a perf hit (range scan instead of direct key lookup). ok I call drop often</technical_language>

Target:
void dropTables(final Set<TableReference> tablesToDrop) { try { clientPool.runWithRetry(client -> { KsDef ks = client.describe_keyspace(config.getKeyspaceOrThrow()); Set<TableReference> existingTables = Sets.newHashSet(); existingTables.addAll(ks.getCf_defs().stream() .map(CassandraKeyValueServices::tableReferenceFromCfDef) .collect(Collectors.toList())); for (TableReference table : tablesToDrop) { CassandraVerifier.sanityCheckTableName(table); if (existingTables.contains(table)) { CassandraKeyValueServices.runWithWaitingForSchemas( () -> truncateThenDrop(table, client), config, client, "dropping the column family for table " + table + " in a call to drop tables"); cassandraTableMetadata.deleteAllMetadataRowsForTable(table); } else { log.warn("Ignored call to drop a table ({}) that did not exist.", LoggingArgs.tableRef(table)); } } return null; }); } catch (Exception e) { throw Throwables.unwrapAndThrowAtlasDbDependencyException(e); } }
Source:
<code>private void launchTcpSlaveAgentListener() throws IOException { synchronized(tcpSlaveAgentListenerLock) { if (tcpSlaveAgentListener != null && tcpSlaveAgentListener.configuredPort != slaveAgentPort) { tcpSlaveAgentListener.shutdown(); tcpSlaveAgentListener = null; } if (slaveAgentPort != -1 && tcpSlaveAgentListener == null) { final String administrativeMonitorId = getClass().getName() + ".tcpBind"; try { tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort); AdministrativeMonitor toBeRemoved = null; ExtensionList<AdministrativeMonitor> all = AdministrativeMonitor.all(); <START> for (Iterator<AdministrativeMonitor> it = all.iterator(); it.hasNext(); ) { <END> AdministrativeMonitor am = it.next(); if (administrativeMonitorId.equals(am.id)) { toBeRemoved = am; break; } } all.remove(toBeRemoved); } catch (BindException e) { LOGGER.log(Level.WARNING, String.format("Failed to listen to incoming agent connections through JNLP port %s. Change the JNLP port number", slaveAgentPort), e); new AdministrativeError(administrativeMonitorId, "Failed to listen to incoming agent connections through JNLP", "Failed to listen to incoming agent connections through JNLP. <a href='configureSecurity'>Change the JNLP port number</a> to solve the problem.", e); } } } }</code><technical_language>Switch Java 5 foreach, then, need anymore old-school iterator style</technical_language>

Target:
private void launchTcpSlaveAgentListener() throws IOException { synchronized(tcpSlaveAgentListenerLock) { if (tcpSlaveAgentListener != null && tcpSlaveAgentListener.configuredPort != slaveAgentPort) { tcpSlaveAgentListener.shutdown(); tcpSlaveAgentListener = null; } if (slaveAgentPort != -1 && tcpSlaveAgentListener == null) { final String administrativeMonitorId = getClass().getName() + ".tcpBind"; try { tcpSlaveAgentListener = new TcpSlaveAgentListener(slaveAgentPort); AdministrativeMonitor toBeRemoved = null; ExtensionList<AdministrativeMonitor> all = AdministrativeMonitor.all(); for (AdministrativeMonitor am : all) { if (administrativeMonitorId.equals(am.id)) { toBeRemoved = am; break; } } all.remove(toBeRemoved); } catch (BindException e) { LOGGER.log(Level.WARNING, String.format("Failed to listen to incoming agent connections through JNLP port %s. Change the JNLP port number", slaveAgentPort), e); new AdministrativeError(administrativeMonitorId, "Failed to listen to incoming agent connections through JNLP", "Failed to listen to incoming agent connections through JNLP. <a href='configureSecurity'>Change the JNLP port number</a> to solve the problem.", e); } } } }
Source:
<code>public static void main(String[] args) throws BookDuplicateException, BookNotFoundException, VersionMismatchException { <START> long bookId = 1; <END> BookRepository bookRepository = new BookRepository(); Book book = new Book(); book.setId(bookId); bookRepository.add(book); LOGGER.info("An empty book with version was added to repository", book.getVersion()); final Book aliceBook = bookRepository.get(bookId); final Book bobBook = bookRepository.get(bookId); aliceBook.setTitle("Kama Sutra"); bookRepository.update(aliceBook); LOGGER.info("Alice updates the book with new version {}", aliceBook.getVersion()); bobBook.setAuthor("Vatsyayana Mallanaga"); try { LOGGER.info("Bob tries to update the book with his version {}", bobBook.getVersion()); bookRepository.update(bobBook); } catch (VersionMismatchException e) { LOGGER.info("Exception: {}", e.getMessage()); } }</code><technical_language>Please local variable inference (var)</technical_language>

Target:
public static void main(String[] args) throws BookDuplicateException, BookNotFoundException, VersionMismatchException { var bookId = 1; var bookRepository = new BookRepository(); var book = new Book(); book.setId(bookId); bookRepository.add(book); LOGGER.info("An empty book with version was added to repository", book.getVersion()); final var aliceBook = bookRepository.get(bookId); final var bobBook = bookRepository.get(bookId); aliceBook.setTitle("Kama Sutra"); bookRepository.update(aliceBook); LOGGER.info("Alice updates the book with new version {}", aliceBook.getVersion()); bobBook.setAuthor("Vatsyayana Mallanaga"); try { LOGGER.info("Bob tries to update the book with his version {}", bobBook.getVersion()); bookRepository.update(bobBook); } catch (VersionMismatchException e) { LOGGER.info("Exception: {}", e.getMessage()); } }
Source:
<code><START> @Override public <END> void setId(EngineBackupLogId id) { dbName = id.getDbName(); doneAt = id.getDoneAt(); }</code><technical_language>please put @Override a separate line</technical_language>

Target:
public void setId(EngineBackupLogId id) { dbName = id.getDbName(); doneAt = id.getDoneAt(); }
Source:
<code>public List<storage_domains> listFailedAutorecoverables() { <START> return new SimpleJdbcTemplate(jdbcTemplate).query("select * from storage_domains where recoverable and status = " <END> + StorageDomainStatus.InActive.getValue(), StorageDomainRowMapper.instance); }</code><technical_language>please stored procedure here</technical_language>

Target:
public List<storage_domains> listFailedAutorecoverables() { return getCallsHandler().executeReadList("GetFailingVdss", StorageDomainRowMapper.instance, null); }
Source:
<code>public static Map getTenantBasedPublisherDomainMapping(String tenantDomain) throws APIManagementException { try { Registry registry = ServiceReferenceHolder.getInstance().getRegistryService(). getGovernanceSystemRegistry(); String resourcePath = APIConstants.API_DOMAIN_MAPPINGS.replace(APIConstants.API_DOMAIN_MAPPING_TENANT_ID_IDENTIFIER, tenantDomain); if (registry.resourceExists(resourcePath)) { Resource resource = registry.get(resourcePath); String content = new String((byte[]) resource.getContent(), Charset.defaultCharset()); JSONParser parser = new JSONParser(); JSONObject mappings = (JSONObject) parser.parse(content); if (mappings.containsKey(APIConstants.API_DOMAIN_MAPPINGS_PUBLISHER)) { return (Map) mappings.get(APIConstants.API_DOMAIN_MAPPINGS_PUBLISHER); } } } catch (RegistryException e) { String msg = "Error while retrieving publisher domain mappings from registry"; throw new APIManagementException(msg, e); <START> } catch (ClassCastException e) { <END> String msg = "Invalid JSON found in the publisher tenant domain mappings"; throw new APIManagementException(msg, e); } catch (ParseException e) { String msg = "Malformed JSON found in the publisher tenant domain mappings"; throw new APIManagementException(msg, e); } return null; }</code><technical_language>catch ClassCastException. Ideally, check instance type continue</technical_language>

Target:
public static Map getTenantBasedPublisherDomainMapping(String tenantDomain) throws APIManagementException { try { Registry registry = ServiceReferenceHolder.getInstance().getRegistryService(). getGovernanceSystemRegistry(); String resourcePath = APIConstants.API_DOMAIN_MAPPINGS.replace(APIConstants.API_DOMAIN_MAPPING_TENANT_ID_IDENTIFIER, tenantDomain); if (registry.resourceExists(resourcePath)) { Resource resource = registry.get(resourcePath); String content = new String((byte[]) resource.getContent(), Charset.defaultCharset()); JSONParser parser = new JSONParser(); JSONObject mappings = (JSONObject) parser.parse(content); if (mappings.containsKey(APIConstants.API_DOMAIN_MAPPINGS_PUBLISHER)) { return (Map) mappings.get(APIConstants.API_DOMAIN_MAPPINGS_PUBLISHER); } } } catch (RegistryException e) { String msg = "Error while retrieving publisher domain mappings from registry"; throw new APIManagementException(msg, e); } catch (ParseException e) { String msg = "Malformed JSON found in the publisher tenant domain mappings"; throw new APIManagementException(msg, e); } return null; }
Source:
<code>protected EEFWidgetStyle getWidgetStyle(EEFConditionalStyle conditionalStyle) { <START> return ((EEFButtonConditionalStyle) conditionalStyle).getStyle(); <END> }</code><technical_language>if (conditionalStyle instanceof EEFButtonConditionalStyle) { ... } if state of code safely today a class cast exception, I condone casting testing type first</technical_language>

Target:
protected EEFWidgetStyle getWidgetStyle(EEFConditionalStyle conditionalStyle) { if (conditionalStyle instanceof EEFButtonConditionalStyle) { return ((EEFButtonConditionalStyle) conditionalStyle).getStyle(); } return null; }
Source:
<code>public KeySelectorResult select(KeyInfo keyInfo, KeySelector.Purpose purpose, AlgorithmMethod method, XMLCryptoContext context) throws KeySelectorException { Iterator ki = keyInfo.getContent().iterator(); <START> while (ki.hasNext()) { <END> XMLStructure info = (XMLStructure) ki.next(); if (!(info instanceof DOMKeyValue)) continue; final PublicKey pk; try { pk = ((DOMKeyValue) info).getPublicKey(); } catch (KeyException e) { throw new KeySelectorException(e); } if (algEquals(method.getAlgorithm(), pk.getAlgorithm())) { return new KeySelectorResult() { public Key getKey() { return pk; } }; } } throw new KeySelectorException("No key found!"); }</code><technical_language>foreach</technical_language>

Target:
public KeySelectorResult select(KeyInfo keyInfo, KeySelector.Purpose purpose, AlgorithmMethod method, XMLCryptoContext context) throws KeySelectorException { for (Object o : keyInfo.getContent()) { XMLStructure info = (XMLStructure) o; if (!(info instanceof DOMKeyValue)) continue; final PublicKey pk; try { pk = ((DOMKeyValue) info).getPublicKey(); } catch (KeyException e) { throw new KeySelectorException(e); } if (algEquals(method.getAlgorithm(), pk.getAlgorithm())) { return new KeySelectorResult() { public Key getKey() { return pk; } }; } } throw new KeySelectorException("No key found!"); }
Source:
<code>public void sendUpdate(List<GameObjectDAO> posList) { try { Thread.sleep(20); } catch (InterruptedException e) { e.printStackTrace(); } ByteBuffer buffer = ByteBuffer.allocate(1024); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.put((byte)1); buffer.put((byte)Opcodes.POSITION_UPDATE.getValue()); buffer.put((byte)2); <START> for (int i = 0; i < posList.size(); i++) <END> { GameObjectDAO data = posList.get(i); buffer.putInt(data.objectId); buffer.putDouble(data.x); buffer.putDouble(data.y); if (i < posList.size() - 1) { buffer.put((byte)31); } } buffer.put((byte)4); sendUdp(buffer.array()); }</code><technical_language>++i please :dancer:</technical_language>

Target:
public void sendUpdate(List<GameObjectDAO> posList) { try { Thread.sleep(20); } catch (InterruptedException e) { e.printStackTrace(); } ByteBuffer buffer = ByteBuffer.allocate(1024); buffer.order(ByteOrder.LITTLE_ENDIAN); buffer.put((byte)1); buffer.put((byte)Opcodes.POSITION_UPDATE.getValue()); buffer.put((byte)2); for (int i = 0; i < posList.size(); ++i) { GameObjectDAO data = posList.get(i); buffer.putInt(data.objectId); buffer.putDouble(data.x); buffer.putDouble(data.y); if (i < posList.size() - 1) { buffer.put((byte)31); } } buffer.put((byte)4); sendUdp(buffer.array()); }
Source:
<code>public Encounter findEncounter(Visit visit, EncounterParameters encounterParameters) { EncounterType encounterType = encounterParameters.getEncounterType(); if (encounterType == null) { throw new IllegalArgumentException("Encounter Type not found"); } if (visit.getEncounters() != null) { for (Encounter encounter : visit.getEncounters()) { <START> if (!encounter.isVoided() && (encounter.getUuid().equals(encounterParameters.getEncounterUuid()))) { <END> return encounter; } } } return null; }</code><technical_language>@bgeVam please remove unnecessary parenthesis encounter.getUuid().equals</technical_language>

Target:
public Encounter findEncounter(Visit visit, EncounterParameters encounterParameters) { if (visit == null) { throw new IllegalArgumentException("visit is required"); } if (encounterParameters == null) { throw new IllegalArgumentException("encounterParameters are required"); } for (final Encounter encounter : visit.getNonVoidedEncounters()) { if (encounter.getUuid() .equals(encounterParameters.getEncounterUuid())) { return encounter; } } return null; }
Source:
<code><START> public static List<String> getCountryCodes (HttpServletRequest request) throws DocumentException { <END> List<String> countryCodes = new ArrayList<>(); File dataFile = new File(request.getSession().getServletContext().getRealPath("files/country-code-iso-3166-all.xml")); SAXReader reader = new SAXReader(); Document dataDoc = reader.read(dataFile); List<Node> nodes = dataDoc.selectNodes(" for (Node node : nodes) { countryCodes.add(node.getStringValue().trim()); } return countryCodes; }</code><technical_language>This job, presents user a long list of unsorted codes. Please this a code => name map, user choose country names</technical_language>

Target:
public static Map<String, String> getCountryCodes (HttpServletRequest request) throws DocumentException { Map<String, String> countryCodes = new TreeMap<>(); File dataFile = new File(request.getSession().getServletContext().getRealPath("files/country-code-iso-3166-all.xml")); SAXReader reader = new SAXReader(); Document dataDoc = reader.read(dataFile); List<Node> nodes = dataDoc.selectNodes(" for (Node node : nodes) { String name = node.selectSingleNode("@name").getStringValue().trim(); String alpha2 = node.selectSingleNode("@alpha-2").getStringValue().trim(); countryCodes.put(name, alpha2); } return countryCodes; }
Source:
<code>protected Template doPopulate(Template model, VmTemplate entity) { <START> model.setConsoleDeviceEnabled(!getConsoleDevicesForEntity(new Guid(model.getId())).isEmpty()); <END> return model; }</code><technical_language>id VmTemplate entity, this create new UUID string</technical_language>

Target:
protected Template doPopulate(Template model, VmTemplate entity) { if (!model.isSetConsole()) { model.setConsole(new Console()); } model.getConsole().setEnabled(!getConsoleDevicesForEntity(entity.getId()).isEmpty()); return model; }
Source:
<code>private void setCamcorderProfile(CamcorderProfile profile, boolean recordAudio, int fps) { <START> int compatible_fps = isCompatibleWithDevice(fps * 1000) ? fps : profile.videoFrameRate; <END> mMediaRecorder.setOutputFormat(profile.fileFormat); mMediaRecorder.setVideoFrameRate(compatible_fps); mMediaRecorder.setVideoSize(profile.videoFrameWidth, profile.videoFrameHeight); mMediaRecorder.setVideoEncodingBitRate(profile.videoBitRate); mMediaRecorder.setVideoEncoder(profile.videoCodec); if (recordAudio) { mMediaRecorder.setAudioEncodingBitRate(profile.audioBitRate); mMediaRecorder.setAudioChannels(profile.audioChannels); mMediaRecorder.setAudioSamplingRate(profile.audioSampleRate); mMediaRecorder.setAudioEncoder(profile.audioCodec); } }</code><technical_language>* 1000</technical_language>

Target:
private void setCamcorderProfile(CamcorderProfile profile, boolean recordAudio, int fps) { int compatible_fps = isCompatibleWithDevice(fps) ? fps : profile.videoFrameRate; mMediaRecorder.setOutputFormat(profile.fileFormat); mMediaRecorder.setVideoFrameRate(compatible_fps); mMediaRecorder.setVideoSize(profile.videoFrameWidth, profile.videoFrameHeight); mMediaRecorder.setVideoEncodingBitRate(profile.videoBitRate); mMediaRecorder.setVideoEncoder(profile.videoCodec); if (recordAudio) { mMediaRecorder.setAudioEncodingBitRate(profile.audioBitRate); mMediaRecorder.setAudioChannels(profile.audioChannels); mMediaRecorder.setAudioSamplingRate(profile.audioSampleRate); mMediaRecorder.setAudioEncoder(profile.audioCodec); } }
Source:
<code>private String determineType(ModuleDeploymentRequest request, int lastIndex) { <START> String type = getNamedChannelModuleType(request, lastIndex); <END> if (type != null) { return type; } String name = request.getModule(); int index = request.getIndex(); List<ModuleDefinition> defs = moduleRegistry.findDefinitions(name); if (defs.size() == 0) { throw new RuntimeException("Module definition is missing for " + name); } if (defs.size() == 1) { type = defs.get(0).getType(); } if (lastIndex == 0) { for (ModuleDefinition def : defs) { if (def.getType().equals(ModuleType.JOB.getTypeName()) || def.getType().equals(ModuleType.TRIGGER.getTypeName())) { type = def.getType(); } } } else if (index == 0) { type = "source"; } else if (index == lastIndex) { type = "sink"; } if (type == null) { throw new RuntimeException("Module definition is missing for " + name); } return verifyModuleOfTypeExists(name, type); }</code><technical_language>return ModuleType @ghillert</technical_language>

Target:
private ModuleType determineType(ModuleDeploymentRequest request, int lastIndex) { ModuleType moduleType = getNamedChannelModuleType(request, lastIndex); if (moduleType != null) { return moduleType; } String type = null; String name = request.getModule(); int index = request.getIndex(); List<ModuleDefinition> defs = moduleRegistry.findDefinitions(name); if (defs.size() == 0) { throw new RuntimeException("Module definition is missing for " + name); } if (defs.size() == 1) { type = defs.get(0).getType(); } if (lastIndex == 0) { for (ModuleDefinition def : defs) { if (def.getType().equals(ModuleType.JOB.getTypeName()) || def.getType().equals(ModuleType.TRIGGER.getTypeName())) { type = def.getType(); } } } else if (index == 0) { type = ModuleType.SOURCE.getTypeName(); } else if (index == lastIndex) { type = ModuleType.SINK.getTypeName(); } if (type == null) { throw new NoSuchModuleException(name); } return verifyModuleOfTypeExists(name, type); }
Source:
<code>public DefaultEditorSession(final ManagedSession session, final CanvasCommandManager<AbstractCanvasHandler> canvasCommandManager, final @Session SessionCommandManager<AbstractCanvasHandler> sessionCommandManager, final @Request SessionCommandManager<AbstractCanvasHandler> requestCommandManager, final ClientCommandRegistry<org.kie.workbench.common.stunner.core.command.Command<AbstractCanvasHandler, CanvasViolation>> clientCommandRegistry) { this.session = session; <START> this.commandRegistry = clientCommandRegistry.setSession(session); <END> this.sessionCommandManager = sessionCommandManager; this.requestCommandManager = requestCommandManager; this.canvasCommandManager = canvasCommandManager; }</code><technical_language>yeah remove this :)</technical_language>

Target:
public DefaultEditorSession(final ManagedSession session, final CanvasCommandManager<AbstractCanvasHandler> canvasCommandManager, final @Session SessionCommandManager<AbstractCanvasHandler> sessionCommandManager, final @Request SessionCommandManager<AbstractCanvasHandler> requestCommandManager, final ClientCommandRegistry<org.kie.workbench.common.stunner.core.command.Command<AbstractCanvasHandler, CanvasViolation>> clientCommandRegistry) { this.session = session; this.commandRegistry = clientCommandRegistry; this.sessionCommandManager = sessionCommandManager; this.requestCommandManager = requestCommandManager; this.canvasCommandManager = canvasCommandManager; }
Source:
<code>public int hashCode() { <START> int result = (key ? 1 : 0); <END> result = 31 * result + (path != null ? path.hashCode() : 0); return result; }</code><technical_language>Minor : parentheses needed</technical_language>

Target:
public int hashCode() { int result = key ? 1 : 0; result = 31 * result + (path != null ? path.hashCode() : 0); return result; }
Source:
<code>public static List<String> nodetoolGetSSTables(String containerName, String keyspace, TableReference tableRef, byte[] rowKey) throws IOException, InterruptedException { <START> String query = String.format("nodetool getsstables %s %s__%s %s", <END> keyspace, tableRef.getNamespace().getName(), tableRef.getTablename(), BaseEncoding.base16().lowerCase().encode(rowKey)); String output = EteSetup.execCliCommand(containerName, query); String[] outputSplitIntoLines = output.split("\n"); return Arrays.stream(outputSplitIntoLines) .skip(1) .collect(Collectors.toList()); }</code><technical_language>is a utility converts a tablespace %s__%s? done this conversion creating table</technical_language>

Target:
public static List<String> nodetoolGetSSTables(String containerName, String keyspace, TableReference tableRef, byte[] rowKey) throws IOException, InterruptedException { String query = String.format("nodetool getsstables %s %s %s", keyspace, CassandraKeyValueServiceImpl.internalTableName(tableRef), BaseEncoding.base16().lowerCase().encode(rowKey)); String output = EteSetup.execCliCommand(containerName, query); String[] outputSplitIntoLines = output.split("\n"); return Arrays.stream(outputSplitIntoLines) .skip(1) .collect(Collectors.toList()); }
Source:
<code>public void userTuneElementProviderTest(XmlPullParserKind parserKind) throws XmlPullParserException, IOException, SmackParsingException { XmlPullParser parser = SmackTestUtil.getParserFor(xml, parserKind); UserTuneElement parsed = UserTuneProvider.INSTANCE.parse(parser); <START> assertEquals(xml, parsed.toXML().toString()); <END> }</code><technical_language>XmlUnitUtils.assertXmlSimilar(), slight changes in XML serialization do trigger test</technical_language>

Target:
public void userTuneElementProviderTest(XmlPullParserKind parserKind) throws XmlPullParserException, IOException, SmackParsingException { XmlPullParser parser = SmackTestUtil.getParserFor(xml, parserKind); UserTuneElement parsed = UserTuneProvider.INSTANCE.parse(parser); assertXmlSimilar(xml, parsed.toXML().toString()); }
Source:
<code>public void switchDefaultRepo(){ logger.info("Triggered switch default repo"); String[] openRepos = logic.getOpenRepositories().toArray(new String[0]); String currentRepo = logic.getDefaultRepo(); for(int i = 0; i < openRepos.length; i++){ if(openRepos[i].equals(currentRepo)){ if(i == openRepos.length-1){ primaryRepoChanged(openRepos[0]); } <START> else { <END> primaryRepoChanged(openRepos[i+1]); } break; } } }</code><technical_language>else in line }. Follow coding standard</technical_language>

Target:
public void switchDefaultRepo(){ String[] openRepos = repoSelector.getContents().toArray(new String[0]); String currentRepo = logic.getDefaultRepo(); for (int i = 0; i < openRepos.length; i++) { if (openRepos[i].equals(currentRepo)) { if (i == openRepos.length - 1) { primaryRepoChanged(openRepos[0]); repoSelector.setText(openRepos[0]); } else { primaryRepoChanged(openRepos[i + 1]); repoSelector.setText(openRepos[i + 1]); } } } }
Source:
<code>private void addRedirectListener() { response.addRedirectListener(new MutableResponse.RedirectListener() { @Override public void beforeRedirect() { if (!validator.hasErrors() && entityManager.getTransaction().isActive()) { <START> entityManager.getTransaction().commit(); <END> } } }); }</code><technical_language>Change commit();</technical_language>

Target:
private void addRedirectListener() { response.addRedirectListener(new MutableResponse.RedirectListener() { @Override public void beforeRedirect() { commit(entityManager.getTransaction()); } }); }
Source:
<code>public Operation waitForOperation(Operation operation, long timeout, TimeUnit timeUnit) throws TimeoutException, IOException { GetOperationRequest request = GetOperationRequest.newBuilder().setName(operation.getName()).build(); ExponentialBackOff backOff = new ExponentialBackOff.Builder() .setInitialIntervalMillis(100) .setMultiplier(1.3) .setMaxIntervalMillis(Ints.checkedCast(TimeUnit.SECONDS.toMillis(60))) .setMaxElapsedTimeMillis(Ints.checkedCast(timeUnit.toMillis(timeout))) .build(); Operation currentOperationState = operation; while (true) { if (currentOperationState.getDone()) { switch (currentOperationState.getResultCase()) { case RESPONSE: return currentOperationState; case ERROR: throw StatusProto.toStatusRuntimeException(currentOperationState.getError()); <START> case RESULT_NOT_SET: <END> throw new IllegalStateException( "System returned invalid response for Operation check: " + currentOperationState); } } final long backOffMillis; try { backOffMillis = backOff.nextBackOffMillis(); } catch (IOException e) { throw new RuntimeException(e); } if (backOffMillis == BackOff.STOP) { throw new TimeoutException("Operation did not complete in time"); } else { try { Thread.sleep(backOffMillis); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException("Interrupted while waiting for operation to finish"); } } currentOperationState = getOperation(request); } }</code><technical_language>replace this a default label instead</technical_language>

Target:
public Operation waitForOperation(Operation operation, long timeout, TimeUnit timeUnit) throws TimeoutException, IOException { GetOperationRequest request = GetOperationRequest.newBuilder().setName(operation.getName()).build(); ExponentialBackOff backOff = new ExponentialBackOff.Builder() .setInitialIntervalMillis(100) .setMultiplier(1.3) .setMaxIntervalMillis(Ints.checkedCast(TimeUnit.SECONDS.toMillis(60))) .setMaxElapsedTimeMillis(Ints.checkedCast(timeUnit.toMillis(timeout))) .build(); Operation currentOperationState = operation; while (true) { if (currentOperationState.getDone()) { switch (currentOperationState.getResultCase()) { case RESPONSE: return currentOperationState; case ERROR: throw StatusProto.toStatusRuntimeException(currentOperationState.getError()); default: throw new IllegalStateException( "System returned invalid response for Operation check: " + currentOperationState); } } final long backOffMillis; try { backOffMillis = backOff.nextBackOffMillis(); } catch (IOException e) { throw new RuntimeException(e); } if (backOffMillis == BackOff.STOP) { throw new TimeoutException("Operation did not complete in time"); } else { try { Thread.sleep(backOffMillis); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException("Interrupted while waiting for operation to finish"); } } currentOperationState = getOperation(request); } }
Source:
<code>public CounterStateProvider(ITmfTrace trace, String id) { super(trace, id); ImmutableSet.Builder<CounterAspect> counterAspects = new Builder<>(); <START> Iterable<@NonNull ITmfEventAspect<?>> aspects = trace.getEventAspects(); for (ITmfEventAspect<?> aspect : aspects) { if (aspect instanceof CounterAspect) { counterAspects.add((CounterAspect) aspect); } } fCounterAspects = counterAspects.build(); <END> }</code><technical_language>ImmutableSet.copyOf(Iterables.filter(...))</technical_language>

Target:
public CounterStateProvider(ITmfTrace trace, String id) { super(trace, id); Iterable<ITmfEventAspect<?>> counterAspects = Iterables.filter(trace.getEventAspects(), aspect -> aspect instanceof CounterAspect); fCounterAspects = ImmutableSet.copyOf(counterAspects); }
Source:
<code>public void testTumorOnlyWithDbsnp() throws Exception { Utils.resetRandomGenerator(); final File outputVcf = createTempFile("output", ".vcf"); final String[] args = { "-I", NA12878_20_21_WGS_bam, "-tumor", "NA12878", "-R", b37_reference_20_21, "-dbsnp", dbsnp_138_b37_20_21_vcf, "-L", "20:10000000-10010000", "-O", outputVcf.getAbsolutePath() }; runCommandLine(args); <START> final long numVariants = StreamSupport.stream(new FeatureDataSource<VariantContext>(outputVcf).spliterator(), false).count(); <END> }</code><technical_language>numVariants is</technical_language>

Target:
public void testTumorOnlyWithDbsnp() throws Exception { Utils.resetRandomGenerator(); final File outputVcf = createTempFile("output", ".vcf"); final String[] args = { "-I", NA12878_20_21_WGS_bam, "-tumor", "NA12878", "-R", b37_reference_20_21, "-dbsnp", dbsnp_138_b37_20_21_vcf, "-L", "20:10000000-10010000", "-O", outputVcf.getAbsolutePath() }; runCommandLine(args); }
Source:
<code>public void getFieldReportRequest(int id) { <START> HashMap<String, JSONObject> params = new HashMap<String, JSONObject>(); <END> UserFieldReportRequest fieldReportRequest = new UserFieldReportRequest(getActivity(), params, new Response.Listener<ArrayList<FieldReport>>() { @Override public void onResponse(ArrayList<FieldReport> fieldReports) { Log.e("Field Response", "Sucess"); setFieldReports(fieldReports); mFieldReportAdapter.notifyDataSetChanged(); } }, id); mNetworkManager.getRequestQueue().add(fieldReportRequest); }</code><technical_language>This of function call</technical_language>

Target:
public void getFieldReportRequest(int id) { UserFieldReportRequest fieldReportRequest = new UserFieldReportRequest(mParentActivity, new HashMap<String, JSONObject>(), new Response.Listener<ArrayList<FieldReport>>() { @Override public void onResponse(ArrayList<FieldReport> fieldReports) { setFieldReports(fieldReports); mFieldReportAdapter.notifyDataSetChanged(); }}, id); mNetworkManager.getRequestQueue().add(fieldReportRequest); }
Source:
<code>public ValidationResult validateConcurAccountInfo(ConcurAccountInfo concurAccountInfo) { <START> ValidationResult validationResult = checkAccountingString( <END> concurAccountInfo.getChart(), concurAccountInfo.getAccountNumber(), concurAccountInfo.getSubAccountNumber(), concurAccountInfo.getObjectCode(), concurAccountInfo.getSubObjectCode(), concurAccountInfo.getProjectCode()); return validationResult; }</code><technical_language>I consider eliminating this intermediate variable, validationResult, returning result of checkAccountingString() call directly</technical_language>

Target:
public ValidationResult validateConcurAccountInfo(ConcurAccountInfo concurAccountInfo) { return checkAccountingString( concurAccountInfo.getChart(), concurAccountInfo.getAccountNumber(), concurAccountInfo.getSubAccountNumber(), concurAccountInfo.getObjectCode(), concurAccountInfo.getSubObjectCode(), concurAccountInfo.getProjectCode()); }
Source:
<code><START> private int palatalize(char[] s, int len) { <END> if (StemmerUtil.endsWith(s, len, "ci") || StemmerUtil.endsWith(s, len, "ce") || StemmerUtil.endsWith(s, len, "či") || StemmerUtil.endsWith(s, len, "če")) { s[len - 2] = 'k'; return len - 1; } if (StemmerUtil.endsWith(s, len, "zi") || StemmerUtil.endsWith(s, len, "ze") || StemmerUtil.endsWith(s, len, "ži") || StemmerUtil.endsWith(s, len, "že")) { s[len - 2] = 'h'; return len - 1; } if (StemmerUtil.endsWith(s, len, "čte") || StemmerUtil.endsWith(s, len, "čti") || StemmerUtil.endsWith(s, len, "čtí")) { s[len - 3] = 'c'; s[len - 2] = 'k'; return len - 1; } if (StemmerUtil.endsWith(s, len, "šte") || StemmerUtil.endsWith(s, len, "šti") || StemmerUtil.endsWith(s, len, "ští")) { s[len - 3] = 's'; s[len - 2] = 'k'; return len - 1; } return len - 1; }</code><technical_language>add assert len > 2 (I minimal length accept errors here) len > 3 (it's minimal length enter this code)</technical_language>

Target:
private int palatalize(char[] s, int len) { assert len > 3; if (endsWith(s, len, "ci") || endsWith(s, len, "ce") || endsWith(s, len, "či") || endsWith(s, len, "če")) { s[len - 2] = 'k'; } else if (endsWith(s, len, "zi") || endsWith(s, len, "ze") || endsWith(s, len, "ži") || endsWith(s, len, "že")) { s[len - 2] = 'h'; } else if (endsWith(s, len, "čte") || endsWith(s, len, "čti") || endsWith(s, len, "čtí")) { s[len - 3] = 'c'; s[len - 2] = 'k'; } else if (endsWith(s, len, "šte") || endsWith(s, len, "šti") || endsWith(s, len, "ští")) { s[len - 3] = 's'; s[len - 2] = 'k'; } return len - 1; }