auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public WorkspaceCache createExternalWorkspace(String name, Connectors connectors) { <START> this.workspaceNames.add(name); <END> refreshRepositoryMetadata(true); Cache<NodeKey, CachedNode> nodeCache = cacheForWorkspace(name); ExecutionContext context = context(); String sourceKey = NodeKey.keyForSourceName(name); String workspaceKey = NodeKey.keyForWorkspaceName(name); ExternalDocumentStore documentStore = new ExternalDocumentStore(connectors); String rootId = documentStore.getRootId(sourceKey); NodeKey rootKey = new NodeKey(sourceKey, workspaceKey, rootId); WorkspaceCache workspaceCache = new WorkspaceCache(context, getKey(), name, documentStore, translator, rootKey, nodeCache, changeBus); workspaceCachesByName.put(name, workspaceCache); return workspace(name); }</code><technical_language>This do this safely. Right now, if existing workspace exists name external source, this method overwrite it. changed</technical_language>

Target:
public WorkspaceCache createExternalWorkspace(String name, Connectors connectors) throws RepositoryException { if (this.workspaceNames.contains(name)) { throw new RepositoryException(JcrI18n.connectorSourceNameInvalid.text(name)); } Cache<NodeKey, CachedNode> nodeCache = cacheForWorkspace(name); ExecutionContext context = context(); String sourceKey = NodeKey.keyForSourceName(name); String workspaceKey = NodeKey.keyForWorkspaceName(name); ExternalDocumentStore documentStore = new ExternalDocumentStore(connectors); String rootId = documentStore.getRootId(sourceKey); if (rootId == null) { throw new RepositoryException(JcrI18n.connectorDoesNotExposeRoot.text(name)); } NodeKey rootKey = new NodeKey(sourceKey, workspaceKey, rootId); WorkspaceCache workspaceCache = new WorkspaceCache(context, getKey(), name, documentStore, translator, rootKey, nodeCache, changeBus); externalWorkspaces.put(name, workspaceCache); return workspaceCache; }
Source:
<code>public void shouldEditAnIdentifierPoolSource() throws Exception { <START> <END> String name = "{\"name\":\"Updated Identifier Pool Description\"}"; assertEquals("Test Identifier Pool", service.getIdentifierSourceByUuid(POOL_SOURCE_UUID).getName()); handle(newPostRequest(getURI() + "/" + getUuid(), name)); assertEquals("Updated Identifier Pool Description", service.getIdentifierSourceByUuid(getUuid()).getName()); }</code><technical_language>remove empty lines</technical_language>

Target:
public void shouldEditAnIdentifierPoolSource() throws Exception { String name = "{\"name\":\"Updated Identifier Pool Name\"}"; assertEquals("Test Identifier Pool", service.getIdentifierSourceByUuid(POOL_SOURCE_UUID).getName()); handle(newPostRequest(getURI() + "/" + getUuid(), name)); assertEquals("Updated Identifier Pool Name", service.getIdentifierSourceByUuid(getUuid()).getName()); }
Source:
<code>public Object deserialize(ByteBuf b, CorfuRuntime rt) { int classNameLength = b.readShort(); byte[] classNameBytes = new byte[classNameLength]; b.readBytes(classNameBytes, 0, classNameLength); String className = new String(classNameBytes); if (className.equals("null")) { return null; } else if (className.equals("CorfuObject")) { int smrClassNameLength = b.readShort(); byte[] smrClassNameBytes = new byte[smrClassNameLength]; b.readBytes(smrClassNameBytes, 0, smrClassNameLength); String smrClassName = new String(smrClassNameBytes); try { return rt.getObjectsView().build() .setStreamID(new UUID(b.readLong(), b.readLong())) <START> .setType((Class<? extends ISMRObject>) Class.forName(smrClassName)) <END> .open(); } catch (ClassNotFoundException cnfe) { log.error("Exception during deserialization!", cnfe); throw new RuntimeException(cnfe); } } else { try (ByteBufInputStream bbis = new ByteBufInputStream(b)) { try (InputStreamReader r = new InputStreamReader(bbis)) { return gson.fromJson(r, Class.forName(className)); } } catch (IOException | ClassNotFoundException ie) { log.error("Exception during deserialization!", ie); throw new RuntimeException(ie); } } }</code><technical_language>Yea, casts cleaned ISMRObject</technical_language>

Target:
public Object deserialize(ByteBuf b, CorfuRuntime rt) { int classNameLength = b.readShort(); byte[] classNameBytes = new byte[classNameLength]; b.readBytes(classNameBytes, 0, classNameLength); String className = new String(classNameBytes); if (className.equals("null")) { return null; } else if (className.equals("CorfuObject")) { int smrClassNameLength = b.readShort(); byte[] smrClassNameBytes = new byte[smrClassNameLength]; b.readBytes(smrClassNameBytes, 0, smrClassNameLength); String smrClassName = new String(smrClassNameBytes); try { return rt.getObjectsView().build() .setStreamID(new UUID(b.readLong(), b.readLong())) .setType((Class<? extends ICorfuSMR>) Class.forName(smrClassName)) .open(); } catch (ClassNotFoundException cnfe) { log.error("Exception during deserialization!", cnfe); throw new RuntimeException(cnfe); } } else { try (ByteBufInputStream bbis = new ByteBufInputStream(b)) { try (InputStreamReader r = new InputStreamReader(bbis)) { return gson.fromJson(r, Class.forName(className)); } } catch (IOException | ClassNotFoundException ie) { log.error("Exception during deserialization!", ie); throw new RuntimeException(ie); } } }
Source:
<code>void doInitialize() { try { loadEverything(); } catch (Exception e) { throw new RuntimeException(e); } <START> } <END></code><technical_language>reason this is is get needlessly wrapped in a RuntimeException in next catch block</technical_language>

Target:
void doInitialize() { try { loadEverything(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } }
Source:
<code>private static boolean validateValue(final MeasurementVariable var, final String value, final BindingResult errors) { <START> if (StringUtils.isBlank(value) || MISSING_VALUE.equals(value)) { <END> return true; } if (isInvalidNumber(var, value)) { errors.reject("warning.import.save.invalid.cell.numeric.value", new String[] {var.getAlias(), value}, ""); return false; } else if (isInvalidDate(var, value)) { errors.reject("warning.import.save.invalid.cell.date.value", new String[] {var.getAlias(), value}, ""); return false; } return true; }</code><technical_language>Placing this allow "missing" for date variables</technical_language>

Target:
private static boolean validateValue(final MeasurementVariable var, final String value, final BindingResult errors) { if (StringUtils.isBlank(value)) { return true; } if (isInvalidNumber(var, value)) { errors.reject("warning.import.save.invalid.cell.numeric.value", new String[] {var.getAlias(), value}, ""); return false; } else if (isInvalidDate(var, value)) { errors.reject("warning.import.save.invalid.cell.date.value", new String[] {var.getAlias(), value}, ""); return false; } return true; }
Source:
<code>static boolean isValidNlMsg(@NonNull ByteBuffer bytes) { return <START> bytes.position() < bytes.limit() && bytes.remaining() >= StructNlMsgHdr.STRUCT_SIZE; <END> }</code><technical_language>This kind of tests for thing, bytes.remaining is defined bytes.limit() - bytes.position(). assuming STRUCT_SIZE > 0, bytes.remaining() >= STRUCT_SIZE implies bytes.position() < bytes.limit(), making test useless</technical_language>

Target:
static boolean isValidNlMsg(@NonNull ByteBuffer bytes) { return bytes.remaining() >= StructNlMsgHdr.STRUCT_SIZE; }
Source:
<code>public CompletableFuture<Object> invokeAsync(ComponentRegistry componentRegistry) throws Throwable { if (command instanceof VisitableCommand) { VisitableCommand vc = (VisitableCommand) command; vc.init(componentRegistry); InvocationContextFactory icf = componentRegistry.getInvocationContextFactory().running(); InvocationContext ctx = icf.createRemoteInvocationContextForCommand(vc, getOrigin()); if (command instanceof RemoteLockCommand) { ctx.setLockOwner(((RemoteLockCommand) command).getKeyLockOwner()); } if (trace) log.tracef("Invoking command %s, with originLocal flag set to %b", command, ctx .isOriginLocal()); return componentRegistry.getInterceptorChain().running().invokeAsync(ctx, vc); } else { <START> throw new RuntimeException( <END> "Do we still need to deal with non-visitable commands? (" + command.getClass().getName() + ")"); } }</code><technical_language>throwing this exception 4.2, high time change field constructor VisitableCommand</technical_language>

Target:
public CompletionStage<?> invokeAsync(ComponentRegistry componentRegistry) throws Throwable { command.init(componentRegistry); InvocationContextFactory icf = componentRegistry.getInvocationContextFactory().running(); InvocationContext ctx = icf.createRemoteInvocationContextForCommand(command, getOrigin()); if (command instanceof RemoteLockCommand) { ctx.setLockOwner(((RemoteLockCommand) command).getKeyLockOwner()); } if (trace) log.tracef("Invoking command %s, with originLocal flag set to %b", command, ctx .isOriginLocal()); return componentRegistry.getInterceptorChain().running().invokeAsync(ctx, command); }
Source:
<code>protected boolean swapAndClearCache(String namespaceKey, String cacheKey) { final Lock lock = nsLocks.get(namespaceKey); lock.lock(); try { ConcurrentMap<String, String> cacheMap = mapMap.get(cacheKey); if (cacheMap == null) { <START> throw new IAE("Namespace [%s] does not exist", cacheKey); <END> } dataSize.addAndGet(cacheMap.size()); ConcurrentMap<String, String> prior = mapMap.put(namespaceKey, cacheMap); mapMap.remove(cacheKey); if (prior != null) { dataSize.addAndGet(-prior.size()); return true; } else { return false; } } finally { lock.unlock(); } }</code><technical_language>lookup instead of namespace</technical_language>

Target:
protected boolean swapAndClearCache(String namespaceKey, String cacheKey) { final Lock lock = nsLocks.get(namespaceKey); lock.lock(); try { ConcurrentMap<String, String> cacheMap = mapMap.get(cacheKey); if (cacheMap == null) { throw new IAE("Extraction Cache [%s] does not exist", cacheKey); } dataSize.addAndGet(cacheMap.size()); ConcurrentMap<String, String> prior = mapMap.put(namespaceKey, cacheMap); mapMap.remove(cacheKey); if (prior != null) { dataSize.addAndGet(-prior.size()); return true; } else { return false; } } finally { lock.unlock(); } }
Source:
<code>V mergeInternal(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction, Metadata metadata, long flags, ContextBuilder contextBuilder) { assertKeyNotNull(key); assertValueNotNull(value); assertFunctionNotNull(remappingFunction); DataConversion keyDataConversion = getKeyDataConversion(); DataConversion valueDataConversion = getValueDataConversion(); if (remappingFunction instanceof BiFunctionMapper) { BiFunctionMapper biFunctionMapper = (BiFunctionMapper) remappingFunction; keyDataConversion = biFunctionMapper.getKeyDataConversion(); valueDataConversion = biFunctionMapper.getValueDataConversion(); } ReadWriteKeyCommand<K, V, V> command = commandsFactory.buildReadWriteKeyCommand(key, new MergeFunction<>(value, remappingFunction, metadata), keyPartitioner.getSegment(key), <START> Params.fromFlagsBitSet(flags), keyDataConversion, valueDataConversion); <END> return invocationHelper.invoke(contextBuilder, command, 1); }</code><technical_language>If/Else avoid unnecessary assignment</technical_language>

Target:
V mergeInternal(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction, Metadata metadata, long flags, ContextBuilder contextBuilder) { assertKeyNotNull(key); assertValueNotNull(value); assertFunctionNotNull(remappingFunction); DataConversion keyDataConversion; DataConversion valueDataConversion; if (remappingFunction instanceof BiFunctionMapper) { BiFunctionMapper biFunctionMapper = (BiFunctionMapper) remappingFunction; keyDataConversion = biFunctionMapper.getKeyDataConversion(); valueDataConversion = biFunctionMapper.getValueDataConversion(); } else { keyDataConversion = getKeyDataConversion(); valueDataConversion = getValueDataConversion(); } ReadWriteKeyCommand<K, V, V> command = commandsFactory.buildReadWriteKeyCommand(key, new MergeFunction<>(value, remappingFunction, metadata), keyPartitioner.getSegment(key), Params.fromFlagsBitSet(flags), keyDataConversion, valueDataConversion); return invocationHelper.invoke(contextBuilder, command, 1); }
Source:
<code>public AuditLogType getAuditLogTypeValue() { if <START> (ACTIVE.equals(getCommandStatus()) <END> && getSucceeded()){ return outOfSyncHostsExist() ? CLUSTER_SYNC_ALL_NETWORKS_STARTED : CLUSTER_SYNC_NOTHING_TO_DO; } else if (ENDED_SUCCESSFULLY.equals(getCommandStatus())) { return CLUSTER_SYNC_ALL_NETWORKS_FINISHED; } return CLUSTER_SYNC_ALL_NETWORKS_FAILED; }</code><technical_language>getActionState</technical_language>

Target:
public AuditLogType getAuditLogTypeValue() { if (EXECUTE.equals(getActionState()) && getSucceeded()){ return outOfSyncHostsExist() ? CLUSTER_SYNC_ALL_NETWORKS_STARTED : CLUSTER_SYNC_NOTHING_TO_DO; } else if (EXECUTE.equals(getActionState()) && !getSucceeded()) { return CLUSTER_SYNC_ALL_NETWORKS_START_ERROR; } else if (END_SUCCESS.equals(getActionState())) { return CLUSTER_SYNC_ALL_NETWORKS_FINISHED; } return CLUSTER_SYNC_ALL_NETWORKS_FAILED; }
Source:
<code>public void testFunctionOr() throws Exception { <START> ecqlReparseTest("PropertyExists('name') = true OR PropertyExists('name') = false"); <END> }</code><technical_language>This test test this change</technical_language>

Target:
public void testFunctionOr() throws Exception { ecqlReparseTest("PropertyExists('name') = true OR PropertyExists('name') = false"); ecqlReparseTest("PropertyExists('name') IN (true, false)"); }
Source:
<code>private synchronized void registerMetricWithFqn(String fullyQualifiedMetricName, Metric metric) { try { <START> if (!globalMetricsRegistry.contains(fullyQualifiedMetricName)) { <END> metricRegistry.register(fullyQualifiedMetricName, metric); globalMetricsRegistry.add(fullyQualifiedMetricName); } registeredMetrics.add(fullyQualifiedMetricName); } catch (Exception e) { log.error("Unable to register metric {}", fullyQualifiedMetricName, e); } }</code><technical_language>MetricsRegistry.getName() instead of set here</technical_language>

Target:
private synchronized void registerMetricWithFqn(String fullyQualifiedMetricName, Metric metric) { try { if (!metricRegistry.getNames().contains(fullyQualifiedMetricName)) { metricRegistry.register(fullyQualifiedMetricName, metric); } registeredMetrics.add(fullyQualifiedMetricName); } catch (Exception e) { log.error("Unable to register metric {}", fullyQualifiedMetricName, e); } }
Source:
<code>public Application launchAppYaml(String url, boolean waitForTasksToComplete) { try { <START> Application app = createFromUrl(url); <END> EntityManagementUtils.start(app); log.info("Application started from YAML file "+url+": "+app); return app; } catch (Exception e) { throw Exceptions.propagate(e); } }</code><technical_language>This is wrong method update, replace called here. For a global check if patch successful check for references registerDeploymentPlan, instantiate, restricted EntityManagementUtils class (outside of camp projects)</technical_language>

Target:
public Application launchAppYaml(String url, boolean waitForTasksToComplete) { try { Reader input = Streams.reader(new ResourceUtils(this).getResourceFromUrl(url)); Application app = launchAppYaml(input, waitForTasksToComplete); log.info("Application started from YAML file "+url+": "+app); return app; } catch (Exception e) { throw Exceptions.propagate(e); } }
Source:
<code>private void collectIdColumns(String prefix, EntityType<?> ownerType, EntityType<?> currentType, Map<String, AttributeEntry<?, ?>> attributeMap, Attribute<?, ?> attribute, Class<?> fieldType) { List<String> identifierOrUniqueKeyEmbeddedPropertyNames = jpaProvider.getIdentifierOrUniqueKeyEmbeddedPropertyNames(currentType, attribute.getName()); for (String name : identifierOrUniqueKeyEmbeddedPropertyNames) { EntityType<?> fieldEntityType = delegate.entity(fieldType); Attribute<?, ?> idAttribute = JpaMetamodelUtils.getAttribute(fieldEntityType, name); try { Class<?> idType = JpaMetamodelUtils.resolveFieldClass(fieldType, idAttribute); String idPath = prefix + "." + name; attributeMap.put(idPath, new AttributeEntry(jpaProvider, ownerType, idAttribute, idPath, idType, Arrays.asList(attribute, idAttribute))); if (isAssociation(idAttribute) && !idAttribute.isCollection() && !jpaProvider.isForeignJoinColumn(ownerType, idAttribute.getName())) { collectIdColumns(idPath, ownerType, fieldEntityType, attributeMap, idAttribute, idType); } } <START> catch (NullPointerException e1) { <END> throw e1; } } }</code><technical_language>Again, I assume for testing</technical_language>

Target:
private void collectIdColumns(String prefix, EntityType<?> ownerType, EntityType<?> currentType, Map<String, AttributeEntry<?, ?>> attributeMap, Attribute<?, ?> attribute, Class<?> fieldType) { List<String> identifierOrUniqueKeyEmbeddedPropertyNames = jpaProvider.getIdentifierOrUniqueKeyEmbeddedPropertyNames(currentType, attribute.getName()); for (String name : identifierOrUniqueKeyEmbeddedPropertyNames) { EntityType<?> fieldEntityType = delegate.entity(fieldType); Attribute<?, ?> idAttribute = JpaMetamodelUtils.getAttribute(fieldEntityType, name); Class<?> idType = JpaMetamodelUtils.resolveFieldClass(fieldType, idAttribute); String idPath = prefix + "." + name; attributeMap.put(idPath, new AttributeEntry(jpaProvider, ownerType, idAttribute, idPath, idType, Arrays.asList(attribute, idAttribute))); if (isAssociation(idAttribute) && !idAttribute.isCollection() && !jpaProvider.isForeignJoinColumn(ownerType, idAttribute.getName())) { collectIdColumns(idPath, ownerType, fieldEntityType, attributeMap, idAttribute, idType); } } }
Source:
<code>private JobIdData submit(String sessionId, InputStream job, MediaType mediaType, Map<String, String> variables, Map<String, String> genericInfos) throws NotConnectedRestException { String uriTmpl = restEndpointURL + addSlashIfMissing(restEndpointURL) + "scheduler/submit"; ResteasyClient client = new ResteasyClientBuilder().httpEngine(httpEngine) .providerFactory(providerFactory) .build(); ResteasyWebTarget target = client.target(uriTmpl); if (variables != null) { for (String key : variables.keySet()) { target = target.matrixParam(key, variables.get(key)); } } if (genericInfos != null) { for (String key : genericInfos.keySet()) { target = target.queryParam(key, genericInfos.get(key)); } } MultipartFormDataOutput formData = new MultipartFormDataOutput(); formData.addFormData("file", job, mediaType); GenericEntity<MultipartFormDataOutput> entity = new GenericEntity<MultipartFormDataOutput>(formData) { }; Response response = target.request() .header("sessionid", sessionId) .post(Entity.entity(entity, MediaType.MULTIPART_FORM_DATA_TYPE)); if (response.getStatus() != HttpURLConnection.HTTP_OK) { if (response.getStatus() == HttpURLConnection.HTTP_UNAUTHORIZED) { throw new NotConnectedRestException("User not authenticated or session timeout."); } else { throwException(String.format("Job submission failed status code: %d", response.getStatus()), response); } } return response.readEntity(JobIdData.class); <START> } <END></code><technical_language>![MAJOR](<LINK_0> 'Severity: MAJOR') Iterate "entrySet" instead of "keySet". [![rule](<LINK_1>](<LINK_2></technical_language>

Target:
private JobIdData submit(String sessionId, InputStream job, MediaType mediaType, Map<String, String> variables, Map<String, String> genericInfos) throws NotConnectedRestException { String uriTmpl = restEndpointURL + addSlashIfMissing(restEndpointURL) + "scheduler/submit"; ResteasyClient client = new ResteasyClientBuilder().httpEngine(httpEngine) .providerFactory(providerFactory) .build(); ResteasyWebTarget target = client.target(uriTmpl); if (variables != null) { for (String key : variables.keySet()) { target = target.matrixParam(key, variables.get(key)); } } if (genericInfos != null) { for (String key : genericInfos.keySet()) { target = target.queryParamNoTemplate(key, genericInfos.get(key)); } } MultipartFormDataOutput formData = new MultipartFormDataOutput(); formData.addFormData("file", job, mediaType); GenericEntity<MultipartFormDataOutput> entity = new GenericEntity<MultipartFormDataOutput>(formData) { }; Response response = target.request() .header("sessionid", sessionId) .post(Entity.entity(entity, MediaType.MULTIPART_FORM_DATA_TYPE)); if (response.getStatus() != HttpURLConnection.HTTP_OK) { if (response.getStatus() == HttpURLConnection.HTTP_UNAUTHORIZED) { throw new NotConnectedRestException("User not authenticated or session timeout."); } else { throwException(String.format("Job submission failed status code: %d", response.getStatus()), response); } } return response.readEntity(JobIdData.class); }
Source:
<code>public DropwizardSSLConnectionSocketFactory(TlsConfiguration configuration) { this.configuration = configuration; <START> this.verifier = null; <END> }</code><technical_language>I reduce this constructor a call another constructor: java this(configuration, null);</technical_language>

Target:
public DropwizardSSLConnectionSocketFactory(TlsConfiguration configuration) { this(configuration, null); }
Source:
<code>public void consistencyCheckerLogUseSystemTimezoneIfConfigurable() throws Exception { TimeZone defaultTimeZone = TimeZone.getDefault(); try { ConsistencyCheckService service = mock( ConsistencyCheckService.class ); Mockito.when( service.runFullConsistencyCheck( any( File.class ), any( Config.class ), any( ProgressMonitorFactory.class ), any( LogProvider.class ), any( FileSystemAbstraction.class ), eq( false ), any( CheckConsistencyConfig.class ) ) ) <START> .then( (Answer<ConsistencyCheckService.Result>) invocationOnMock -> <END> { LogProvider provider = invocationOnMock.getArgumentAt( 3, LogProvider.class ); provider.getLog( "test" ).info( "testMessage" ); return ConsistencyCheckService.Result.success( new File( StringUtils.EMPTY ) ); } ); File storeDir = storeDirectory.directory(); File configFile = storeDirectory.file( Config.DEFAULT_CONFIG_FILE_NAME ); Properties properties = new Properties(); properties.setProperty( GraphDatabaseSettings.log_timezone.name(), LogTimeZone.SYSTEM.name() ); properties.store( new FileWriter( configFile ), null ); String[] args = {storeDir.getPath(), "-config", configFile.getPath()}; checkLogRecordTimeZone( service, args, 5, "+0500" ); checkLogRecordTimeZone( service, args, -5, "-0500" ); } finally { TimeZone.setDefault( defaultTimeZone ); } }</code><technical_language>Cast is reduntant</technical_language>

Target:
public void consistencyCheckerLogUseSystemTimezoneIfConfigurable() throws Exception { TimeZone defaultTimeZone = TimeZone.getDefault(); try { ConsistencyCheckService service = mock( ConsistencyCheckService.class ); Mockito.when( service.runFullConsistencyCheck( any( File.class ), any( Config.class ), any( ProgressMonitorFactory.class ), any( LogProvider.class ), any( FileSystemAbstraction.class ), eq( false ), any( CheckConsistencyConfig.class ) ) ) .then( invocationOnMock -> { LogProvider provider = invocationOnMock.getArgumentAt( 3, LogProvider.class ); provider.getLog( "test" ).info( "testMessage" ); return ConsistencyCheckService.Result.success( new File( StringUtils.EMPTY ) ); } ); File storeDir = storeDirectory.directory(); File configFile = storeDirectory.file( Config.DEFAULT_CONFIG_FILE_NAME ); Properties properties = new Properties(); properties.setProperty( GraphDatabaseSettings.log_timezone.name(), LogTimeZone.SYSTEM.name() ); properties.store( new FileWriter( configFile ), null ); String[] args = {storeDir.getPath(), "-config", configFile.getPath()}; checkLogRecordTimeZone( service, args, 5, "+0500" ); checkLogRecordTimeZone( service, args, -5, "-0500" ); } finally { TimeZone.setDefault( defaultTimeZone ); } }
Source:
<code>public Value atomize() { if (value == null) { Object data = attribute.getValue(); if (data instanceof List) { <START> final List<?> dataList = (List<?>) data; <END> final Item[] converted = new Item[dataList.size()]; for (int i = 0; i < dataList.size(); i++) { converted[i] = SaxonXPathRuleQuery.getAtomicRepresentation(dataList.get(i)); } value = new SequenceExtent(converted); } else { value = SaxonXPathRuleQuery.getAtomicRepresentation(attribute.getValue()); } } return value; }</code><technical_language>logic of this method is duplicated SaxonXPathRuleQuery::getRepresentation. In case list is empty, this EmptySequence.getInstance(), SaxonXPathRuleQuery</technical_language>

Target:
public Value atomize() { if (value == null) { Object data = attribute.getValue(); if (data instanceof List) { value = SaxonXPathRuleQuery.getSequenceRepresentation((List<?>) data); } else { value = SaxonXPathRuleQuery.getAtomicRepresentation(attribute.getValue()); } } return value; }
Source:
<code>public Operation getBatchOperation() { CompositeOperation compositeOperation = new CompositeOperation(); if (hasDiscoveryGroupName()) { compositeOperation.addStep(new UndefineAttribute(address, CONNECTOR_ATTRIBUTE)); compositeOperation.addStep(new WriteAttribute(address, DISCOVERY_GROUP_NAME, configuration .getSimpleValue(DISCOVERY_GROUP_NAME))); } else { compositeOperation.addStep(new UndefineAttribute(address, DISCOVERY_GROUP_NAME)); List<Property> propertyList = configuration.getList(CONNECTOR_PROPERTY).getList(); List<String> connectors = new ArrayList<String>(propertyList.size()); for (Property property : propertyList) { if (property instanceof PropertySimple) { PropertySimple propertySimple = (PropertySimple) property; connectors.add(propertySimple.getStringValue()); } else { <START> getLog().warn(property.getName() + " property has unexpected type: " + property.getClass()); <END> } } compositeOperation.addStep(new WriteAttribute(address, CONNECTOR_PROPERTY, connectors)); } return compositeOperation; }</code><technical_language>Is this warning logging of use? throw Exception ignore thing? log in debug mode most</technical_language>

Target:
public Operation getBatchOperation() { CompositeOperation compositeOperation = new CompositeOperation(); if (hasDiscoveryGroupName()) { compositeOperation.addStep(new UndefineAttribute(address, CONNECTOR_ATTRIBUTE)); compositeOperation.addStep(new WriteAttribute(address, DISCOVERY_GROUP_NAME, configuration .getSimpleValue(DISCOVERY_GROUP_NAME))); } else { compositeOperation.addStep(new UndefineAttribute(address, DISCOVERY_GROUP_NAME)); List<Property> propertyList = configuration.getList(CONNECTOR_PROPERTY).getList(); List<String> connectors = new ArrayList<String>(propertyList.size()); for (Property property : propertyList) { if (property instanceof PropertySimple) { PropertySimple propertySimple = (PropertySimple) property; connectors.add(propertySimple.getStringValue()); } else { throw new IllegalArgumentException(property.getName() + " property has unexpected type: " + property.getClass()); } } compositeOperation.addStep(new WriteAttribute(address, CONNECTOR_PROPERTY, connectors)); } return compositeOperation; }
Source:
<code>private void validateIdentifiers(final EObject element) { new ElkGraphSwitch<Object>() { @Override public Object caseElkNode(final ElkNode node) { validateIdentifier(node); <START> node.getLabels().stream().forEach(l -> generateIdentifiers(l)); <END> node.getPorts().stream().forEach(p -> generateIdentifiers(p)); node.getContainedEdges().stream().forEach(e -> generateIdentifiers(e)); node.getChildren().stream().forEach(c -> generateIdentifiers(c)); return null; } @Override public Object caseElkPort(final ElkPort port) { validateIdentifier(port); port.getLabels().stream().forEach(l -> generateIdentifiers(l)); return null; } @Override public Object caseElkLabel(final ElkLabel label) { validateIdentifier(label); label.getLabels().stream().forEach(l -> generateIdentifiers(l)); return null; } @Override public Object caseElkEdge(final ElkEdge edge) { validateIdentifier(edge); edge.getLabels().stream().forEach(l -> generateIdentifiers(l)); edge.getSections().stream().forEach(s -> generateIdentifiers(s)); return null; } @Override public Object caseElkEdgeSection(final ElkEdgeSection section) { validateIdentifier(section); return null; } }.doSwitch(element); }</code><technical_language>this validateIdentifiers(l) (same below)</technical_language>

Target:
private void validateIdentifiers(final EObject element) { new ElkGraphSwitch<Object>() { @Override public Object caseElkNode(final ElkNode node) { validateIdentifier(node); node.getLabels().stream().forEach(l -> validateIdentifier(l)); node.getPorts().stream().forEach(p -> validateIdentifier(p)); node.getContainedEdges().stream().forEach(e -> validateIdentifier(e)); node.getChildren().stream().forEach(c -> validateIdentifier(c)); return null; } @Override public Object caseElkPort(final ElkPort port) { validateIdentifier(port); port.getLabels().stream().forEach(l -> validateIdentifier(l)); return null; } @Override public Object caseElkLabel(final ElkLabel label) { validateIdentifier(label); label.getLabels().stream().forEach(l -> validateIdentifier(l)); return null; } @Override public Object caseElkEdge(final ElkEdge edge) { validateIdentifier(edge); edge.getLabels().stream().forEach(l -> validateIdentifier(l)); edge.getSections().stream().forEach(s -> validateIdentifier(s)); return null; } @Override public Object caseElkEdgeSection(final ElkEdgeSection section) { validateIdentifier(section); return null; } }.doSwitch(element); }
Source:
<code>public void setDetails(String key, Object value) { <START> this.details.put(key, value); <END> }</code><technical_language>a mutable details field here</technical_language>

Target:
public void setDetails(String key, Object value) { if (details == null) { this.details = newHashMap(); } this.details.put(key, value); }
Source:
<code>public ImmutableBoundedValue<Integer> fireDelay() { return ImmutableDataCachingUtil.getValue(ImmutableSpongeBoundedValue.class, Keys.FIRE_DAMAGE_DELAY, this.fireDelay, this.fireDelay, <START> intComparator(), 0); <END> }</code><technical_language>for here</technical_language>

Target:
public ImmutableBoundedValue<Integer> fireDelay() { return new ImmutableSpongeBoundedValue<Integer>(Keys.FIRE_DAMAGE_DELAY, this.fireDelay, 20, intComparator(), 0, Integer.MAX_VALUE); }
Source:
<code>private boolean requestForbidden(HttpServletRequest request) { if (!xsrfProtectionEnabled) { return false; } HttpSession session = request.getSession(false); String csrfTokenInHeader = request.getHeader("X-CSRF-Token"); if (session == null) { <START> return csrfTokenInHeader != null; <END> } else { String csrfTokenInSession = (String) session.getAttribute(VaadinService.getCsrfTokenAttributeName()); return csrfTokenInSession == null || !csrfTokenInSession.equals(csrfTokenInHeader); } }</code><technical_language>This fails requests a token header is session. reasons it? IMO read more logical if in case of empty session return early checking header: java HttpSession session = request.getSession(false); if (session == null) { return false; } String csrfToken = (String) request.getSession(); return csrfToken == null || !csrfToken.equals(request.getHeader("X-CSRF-Token"));</technical_language>

Target:
private boolean requestForbidden(HttpServletRequest request) { if (!xsrfProtectionEnabled) { return false; } HttpSession session = request.getSession(false); if (session == null) { return false; } String csrfTokenInSession = (String) session.getAttribute(VaadinService.getCsrfTokenAttributeName()); return csrfTokenInSession == null || !csrfTokenInSession.equals(request.getHeader("X-CSRF-Token")); }
Source:
<code>public List<String> getConfigList(String xpathString) { SAXReader reader = new SAXReader(); List<String> returnValue = new ArrayList<>(); try { Document doc = reader.read(getConfigFile()); DefaultXPath xpath = new DefaultXPath(xpathString); <START> @SuppressWarnings("unchecked") <END> List<DefaultElement> list = xpath.selectNodes(doc); for (final DefaultElement element : list) { returnValue.add(element.getText()); } } catch (DocumentException e) { LOGGER.log(Level.WARNING, String.format("Could not open config file '%s': '%s'", getConfigFile(), e.getMessage())); } return returnValue; }</code><technical_language>catch handle required exceptions</technical_language>

Target:
public List<String> getConfigList(String xpathString) { SAXReader reader = new SAXReader(); List<String> returnValue = new ArrayList<>(); try { Document doc = reader.read(getConfigFile()); DefaultXPath xpath = new DefaultXPath(xpathString); @SuppressWarnings("unchecked") List<DefaultElement> list = xpath.selectNodes(doc); for (final DefaultElement element : list) { returnValue.add(element.getText()); } } catch (DocumentException e) { LOGGER.log(Level.WARNING, String.format("Could not read '%s' as an xml document: '%s'", getConfigFile(), e.getMessage())); } catch (ClassCastException e) { LOGGER.log(Level.WARNING, String.format("Error reading configuration file %s: '%s' does not return a list of elements", getConfigFile(), xpathString)); } return returnValue; }
Source:
<code>DeleteOperation(ClusterMap clusterMap, RouterConfig routerConfig, NonBlockingRouterMetrics routerMetrics, ResponseHandler responsehandler, BlobId blobId, String serviceId, Callback<Void> callback, Time time, FutureResult<Void> futureResult) { this.submissionTimeMs = time.milliseconds(); this.routerConfig = routerConfig; this.routerMetrics = routerMetrics; this.responseHandler = responsehandler; this.blobId = blobId; this.serviceId = serviceId; this.futureResult = futureResult; this.callback = callback; this.time = time; this.deletionTimeMs = time.milliseconds(); this.deleteRequestInfos = new HashMap<Integer, DeleteRequestInfo>(); byte blobDcId = blobId.getDatacenterId(); <START> String preferredDcName = clusterMap.findDatacenterName(blobDcId); <END> this.operationTracker = new SimpleOperationTracker(routerConfig.routerDatacenterName, blobId.getPartition(), true, preferredDcName, routerConfig.routerDeleteSuccessTarget, routerConfig.routerDeleteRequestParallelism, false); }</code><technical_language>call this originatingDcName</technical_language>

Target:
DeleteOperation(ClusterMap clusterMap, RouterConfig routerConfig, NonBlockingRouterMetrics routerMetrics, ResponseHandler responsehandler, BlobId blobId, String serviceId, Callback<Void> callback, Time time, FutureResult<Void> futureResult) { this.submissionTimeMs = time.milliseconds(); this.routerConfig = routerConfig; this.routerMetrics = routerMetrics; this.responseHandler = responsehandler; this.blobId = blobId; this.serviceId = serviceId; this.futureResult = futureResult; this.callback = callback; this.time = time; this.deletionTimeMs = time.milliseconds(); this.deleteRequestInfos = new HashMap<Integer, DeleteRequestInfo>(); byte blobDcId = blobId.getDatacenterId(); String originatingDcName = clusterMap.getDatacenterName(blobDcId); this.operationTracker = new SimpleOperationTracker(routerConfig.routerDatacenterName, blobId.getPartition(), true, originatingDcName, true, Integer.MAX_VALUE, routerConfig.routerDeleteSuccessTarget, routerConfig.routerDeleteRequestParallelism, false); }
Source:
<code>public Set<LockRefreshToken> refreshLockRefreshTokens(Iterable<LockRefreshToken> tokens) { List<HeldLocksToken> fakeTokens = Lists.newArrayList(); LockDescriptor fakeLockDesc = StringLockDescriptor.of("refreshLockRefreshTokens"); SortedLockCollection<LockDescriptor> fakeLockSet = LockCollections.of(ImmutableSortedMap.of(fakeLockDesc, LockMode.READ)); for (LockRefreshToken token : tokens) { fakeTokens.add(new HeldLocksToken( token.getTokenId(), LockClient.ANONYMOUS, 0L, 0L, fakeLockSet, maxAllowedLockTimeout, 0L, <START> "fakeThread-refreshLockRefreshTokens")); <END> } return ImmutableSet.copyOf(Iterables.transform(refreshTokens(fakeTokens), HeldLocksTokens.getRefreshTokenFun())); }</code><technical_language>fakeThread</technical_language>

Target:
public Set<LockRefreshToken> refreshLockRefreshTokens(Iterable<LockRefreshToken> tokens) { List<HeldLocksToken> fakeTokens = Lists.newArrayList(); LockDescriptor fakeLockDesc = StringLockDescriptor.of("refreshLockRefreshTokens"); SortedLockCollection<LockDescriptor> fakeLockSet = LockCollections.of(ImmutableSortedMap.of(fakeLockDesc, LockMode.READ)); for (LockRefreshToken token : tokens) { fakeTokens.add(new HeldLocksToken( token.getTokenId(), LockClient.ANONYMOUS, 0L, 0L, fakeLockSet, maxAllowedLockTimeout, 0L, "UnknownThread-refreshLockRefreshTokens")); } return ImmutableSet.copyOf(Iterables.transform(refreshTokens(fakeTokens), HeldLocksTokens.getRefreshTokenFun())); }
Source:
<code>public void setScrollView(@Nullable ObservableWebView webView) { this.webView = webView; if (this.webView != null) { <START> this.webView.clearAllListeners(); <END> this.webView.addOnScrollChangeListener(this); this.webView.addOnDownMotionEventListener(this); this.webView.addOnUpOrCancelMotionEventListener(this); } }</code><technical_language>I this clear previous webView's listeners, current one</technical_language>

Target:
public void setScrollView(@Nullable ObservableWebView webView) { if (this.webView != null) { this.webView.clearAllListeners(); } this.webView = webView; if (this.webView != null) { this.webView.addOnScrollChangeListener(this); this.webView.addOnDownMotionEventListener(this); this.webView.addOnUpOrCancelMotionEventListener(this); } }
Source:
<code>public InterpreterResult interpret(String input, InterpreterContext context) { String[] tokens = splitTokens(input); String keyword = tokens[0]; InterpreterResult result; Protocol.Command command = Protocol.Command.valueOf(keyword); if (COMMANDS.containsKey(command)) { result = COMMANDS.get(command).execute(tokens); } else { <START> result = new InterpreterResult(ERROR, "keyword not found"); <END> } return result; }</code><technical_language>provide a error user Keyword " + tokens + " is supportted? do think</technical_language>

Target:
public InterpreterResult interpret(String input, InterpreterContext context) { String[] tokens = splitTokens(input); String keyword = tokens[0].toUpperCase(); InterpreterResult result; Protocol.Command command = Protocol.Command.valueOf(keyword); if (COMMANDS.containsKey(command)) { result = COMMANDS.get(command).execute(tokens); } else { result = new InterpreterResult(ERROR, "Keyword " + tokens + " is not supported"); } return result; }
Source:
<code>public void fromStream(ObjectInput inputStream) throws CacheLoaderException { Object objectFromStream; try { objectFromStream = getMarshaller().objectFromObjectStream(inputStream); } catch (IOException e) { throw log.unableToUnmarshall(e); } catch (ClassNotFoundException e) { throw log.unableToUnmarshall(e); } catch (InterruptedException e) { <START> throw log.unableToUnmarshall(e); <END> } if (objectFromStream instanceof InternalCacheEntry) { InternalCacheEntry ice = (InternalCacheEntry) objectFromStream; this.store(ice); } else if (objectFromStream instanceof Set) { Set<InternalCacheEntry> internalCacheEntries = (Set<InternalCacheEntry>) objectFromStream; for (InternalCacheEntry ice : internalCacheEntries) { this.store(ice); } } }</code><technical_language>catch restore interrupted state of Thread! Add this throws statement: Thread.currentThread().interrupt();</technical_language>

Target:
public void fromStream(ObjectInput inputStream) throws CacheLoaderException { Object objectFromStream; try { objectFromStream = getMarshaller().objectFromObjectStream(inputStream); } catch (IOException e) { Thread.currentThread().interrupt(); throw log.unableToUnmarshall(e); } catch (ClassNotFoundException e) { throw log.unableToUnmarshall(e); } catch (InterruptedException e) { throw log.unableToUnmarshall(e); } if (objectFromStream instanceof InternalCacheEntry) { InternalCacheEntry ice = (InternalCacheEntry) objectFromStream; this.store(ice); } else if (objectFromStream instanceof Set) { Set<InternalCacheEntry> internalCacheEntries = (Set<InternalCacheEntry>) objectFromStream; for (InternalCacheEntry ice : internalCacheEntries) { this.store(ice); } } }
Source:
<code><START> public synchronized EditTokenStorage getEditTokenStorage() { <END> if (editTokenStorage == null) { editTokenStorage = new EditTokenStorage(this); } return editTokenStorage; }</code><technical_language>Do code suspect is accessing methods main thread? way, is tolerable omit synchronization initialize in App.onCreate()</technical_language>

Target:
public EditTokenStorage getEditTokenStorage() { return editTokenStorage; }
Source:
<code>public SoundEffectPlayer(final String soundPath) { super(); path = soundPath; if (State.isSoundEffectsEnabled()) { initializeAudio(path); } <START> this.setVolume(DEFAULT_VOLUMELEVEL); <END> }</code><technical_language>volume set State.getVolume() (Same for SoundtrackPlayer)? State.resetAll() Default values, move Defaults State well. <review, logic</technical_language>

Target:
public SoundEffectPlayer(final String soundPath) { super(); path = soundPath; if (State.isSoundEffectsEnabled()) { initializeAudio(path); } this.setVolume(State.getSoundEffectVolume()); }
Source:
<code>private NBTTagCompound loadSpawnData( int dim, int chunkX, int chunkZ ) { if( !Thread.holdsLock( SpawnData.class ) ) { throw new IllegalStateException( "Invalid Request" ); } NBTTagCompound data = null; <START> File file = new File( this.spawnDirectory, dim + "_" + ( chunkX >> 4 ) + '_' + ( chunkZ >> 4 ) + ".dat" ); <END> if( file.isFile() ) { FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream( file ); data = CompressedStreamTools.readCompressed( fileInputStream ); } catch( Throwable e ) { data = new NBTTagCompound(); AELog.error( e ); } finally { if( fileInputStream != null ) { try { fileInputStream.close(); } catch( IOException e ) { AELog.error( e ); } } } } else { data = new NBTTagCompound(); } return data; }</code><technical_language>idea move string generation method. test generated string guarantee stay consistent</technical_language>

Target:
private NBTTagCompound loadSpawnData( int dim, int chunkX, int chunkZ ) { if( !Thread.holdsLock( SpawnData.class ) ) { throw new IllegalStateException( "Invalid Request" ); } NBTTagCompound data = null; final String fileName = this.encoder.encode( dim, chunkX, chunkZ ); final File file = new File( this.spawnDirectory, fileName ); if( file.isFile() ) { FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream( file ); data = CompressedStreamTools.readCompressed( fileInputStream ); } catch( Throwable e ) { data = new NBTTagCompound(); AELog.error( e ); } finally { if( fileInputStream != null ) { try { fileInputStream.close(); } catch( IOException e ) { AELog.error( e ); } } } } else { data = new NBTTagCompound(); } return data; }
Source:
<code>public Boolean call() throws IdentityProvisioningException { boolean success = false; String tenantDomainName = this.tenantDomainName; try { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomainName); ProvisionedIdentifier provisionedIdentifier = null; provisionedIdentifier = connector.provision(provisioningEntity); if (provisioningEntity.getOperation() == ProvisioningOperation.DELETE) { deleteProvisionedEntityIdentifier(idPName, connectorType, provisioningEntity, tenantDomainName); } else if (provisioningEntity.getOperation() == ProvisioningOperation.POST) { if (provisionedIdentifier == null || provisionedIdentifier.getIdentifier() == null) { provisionedIdentifier = new ProvisionedIdentifier(); provisionedIdentifier.setIdentifier(UUID.randomUUID().toString()); } provisioningEntity.setIdentifier(provisionedIdentifier); storeProvisionedEntityIdentifier(idPName, connectorType, provisioningEntity, tenantDomainName); } success = true; <START> } catch (Exception e) { <END> String errMsg = " Provisioning for Entity " + provisioningEntity.getEntityName() + " For operation = " + provisioningEntity.getOperation(); throw new IdentityProvisioningException(errMsg, e); } finally { PrivilegedCarbonContext.endTenantFlow(); if (tenantDomainName != null) { PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain( tenantDomainName); } } return success; }</code><technical_language>check Exception throwing</technical_language>

Target:
public Boolean call() throws IdentityProvisioningException { boolean success = false; String tenantDomainName = this.tenantDomainName; try { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomainName); ProvisionedIdentifier provisionedIdentifier = null; provisionedIdentifier = connector.provision(provisioningEntity); if (provisioningEntity.getOperation() == ProvisioningOperation.DELETE) { deleteProvisionedEntityIdentifier(idPName, connectorType, provisioningEntity, tenantDomainName); } else if (provisioningEntity.getOperation() == ProvisioningOperation.POST) { if (provisionedIdentifier == null || provisionedIdentifier.getIdentifier() == null) { provisionedIdentifier = new ProvisionedIdentifier(); provisionedIdentifier.setIdentifier(UUID.randomUUID().toString()); } provisioningEntity.setIdentifier(provisionedIdentifier); storeProvisionedEntityIdentifier(idPName, connectorType, provisioningEntity, tenantDomainName); } success = true; } catch (IdentityApplicationManagementException e) { String errMsg = " Provisioning for Entity " + provisioningEntity.getEntityName() + " For operation = " + provisioningEntity.getOperation(); throw new IdentityProvisioningException(errMsg, e); } finally { PrivilegedCarbonContext.endTenantFlow(); if (tenantDomainName != null) { PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain( tenantDomainName); } } return success; }
Source:
<code>public int read(int offset, int[] positions, int positionCount) throws IOException { checkState(!valuesInUse, "BlockLease hasn't been closed yet"); if (!rowGroupOpen) { openRowGroup(); } allNulls = false; if (outputRequired) { ensureValuesCapacity(positionCount, nullsAllowed && presentStream != null); } if (filter != null) { <START> ensureOutputPositionsCapacity(positionCount); <END> } else { outputPositions = positions; } systemMemoryContext.setBytes(getRetainedSizeInBytes()); if (readOffset < offset) { skip(offset - readOffset); } int streamPosition = 0; if (dataStream == null && presentStream != null) { streamPosition = readAllNulls(positions, positionCount); } else if (filter == null) { streamPosition = readNoFilter(positions, positionCount); } else { streamPosition = readWithFilter(positions, positionCount); } readOffset = offset + streamPosition; return outputPositionCount; }</code><technical_language>Arrays.ensureCapacity methods in ensureValuesCapacity</technical_language>

Target:
public int read(int offset, int[] positions, int positionCount) throws IOException { checkState(!valuesInUse, "BlockLease hasn't been closed yet"); if (!rowGroupOpen) { openRowGroup(); } allNulls = false; if (outputRequired) { ensureValuesCapacity(positionCount, nullsAllowed && presentStream != null); } if (filter != null) { outputPositions = ensureCapacity(outputPositions, positionCount); } else { outputPositions = positions; } systemMemoryContext.setBytes(getRetainedSizeInBytes()); if (readOffset < offset) { skip(offset - readOffset); } int streamPosition; if (dataStream == null && presentStream != null) { streamPosition = readAllNulls(positions, positionCount); } else if (filter == null) { streamPosition = readNoFilter(positions, positionCount); } else { streamPosition = readWithFilter(positions, positionCount); } readOffset = offset + streamPosition; return outputPositionCount; }
Source:
<code>public String[] getColumnFamilies() { <START> return columnFamilies; <END> }</code><technical_language>nit: Arrays.copyOf</technical_language>

Target:
public String[] getColumnFamilies() { return Arrays.copyOf(columnFamilies, columnFamilies.length); }