auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private DescribeConfigsResponse describeConfigsResponse(ApiError error, NewTopic... topics) { if (error == null) error = new ApiError(Errors.NONE, ""); List<DescribeConfigsResponseData.DescribeConfigsResult> results = new ArrayList<>(); <START> for (NewTopic topic : topics) { <END> results.add(new DescribeConfigsResponseData.DescribeConfigsResult() .setErrorCode(error.error().code()) .setErrorMessage(error.message()) .setResourceType(ConfigResource.Type.TOPIC.id()) .setResourceName(topic.name()) .setConfigs(topic.configs().entrySet().stream().map(e -> new DescribeConfigsResponseData.DescribeConfigsResourceResult() .setName(e.getKey()) .setValue(e.getValue())).collect(Collectors.toList()))); } return new DescribeConfigsResponse(new DescribeConfigsResponseData() .setThrottleTimeMs(1000) .setResults(results)); }</code><technical_language>stream topics a collector in end</technical_language>

Target:
private DescribeConfigsResponse describeConfigsResponse(ApiError error, NewTopic... topics) { List<DescribeConfigsResponseData.DescribeConfigsResult> results = Stream.of(topics) .map(topic -> new DescribeConfigsResponseData.DescribeConfigsResult() .setErrorCode(error.error().code()) .setErrorMessage(error.message()) .setResourceType(ConfigResource.Type.TOPIC.id()) .setResourceName(topic.name()) .setConfigs(topic.configs().entrySet() .stream() .map(e -> new DescribeConfigsResponseData.DescribeConfigsResourceResult() .setName(e.getKey()) .setValue(e.getValue())) .collect(Collectors.toList()))) .collect(Collectors.toList()); return new DescribeConfigsResponse(new DescribeConfigsResponseData().setThrottleTimeMs(1000).setResults(results)); }
Source:
<code>public ExtensionRuleConfig() { <START> super(); <END> initialize(); }</code><technical_language>constructor ExtensionAdaptor(String) NAME parameter (initialize() removed)</technical_language>

Target:
public ExtensionRuleConfig() { super(NAME); }
Source:
<code>private SolrInputDocument toDoc(Question q) { List<String> tagNames = Lists.transform(q.getTags(), new Function<Tag, String>() { @Nullable @Override public String apply(@Nullable Tag tag) { return tag.getName(); } }); SolrInputDocument doc = new SolrInputDocument(); doc.addField("id", q.getId()); doc.addField("title", q.getTitle()); doc.addField("description", q.getMarkedDescription()); doc.addField("tags", tagNames.toString().replace("[", "").replace("]", "")); String answer = null; List<String> responses = new ArrayList<>(); for (Answer a : q.getAnswers()) { if (a.isSolution()) { answer = a.getDescription(); } else { responses.add(a.getDescription()); } } if (answer != null) { doc.addField("answer", answer); } if (responses.size() > 0) { doc.addField("responses", responses.toString().replace("[", "").replace("]", "")); <START> } <END> return doc; }</code><technical_language>I improve :-) ## Chico Sokol Mon, Nov 3, 2014 3:59 PM, monitorjbl notifications@github.com wrote: > In src/main/java/org/mamute/search/SolrQuestionIndex.java: > > > - String answer = null; > > - List<String> responses = new ArrayList<>(); > > - for (Answer a : q.getAnswers()) { > > - if (a.isSolution()) { > > - answer = a.getDescription(); > > - } else { > > - responses.add(a.getDescription()); > > - } > > - } > > + > > - if (answer != null) { > > - doc.addField("answer", answer); > > - } > > - if (responses.size() > 0) { > > - doc.addField("responses", responses.toString().replace("[", "").replace("]", "")); > > - } > > Sure, a Guava utility joins collections. I keeping > original implementation, I mind switching bit. > > - > Reply this email view GitHub > <LINK_0></technical_language>

Target:
private SolrInputDocument toDoc(Question q) { List<String> tagNames = Lists.transform(q.getTags(), new Function<Tag, String>() { @Nullable @Override public String apply(@Nullable Tag tag) { return tag.getName(); } }); SolrInputDocument doc = new SolrInputDocument(); doc.addField("id", q.getId()); doc.addField("title", q.getTitle()); doc.addField("description", q.getMarkedDescription()); doc.addField("tags", join(tagNames)); String solution = null; List<String> answers = new ArrayList<>(); for (Answer a : q.getAnswers()) { if (a.isSolution()) { solution = a.getDescription(); } else { answers.add(a.getDescription()); } } if (solution != null) { doc.addField("solution", solution); } if (answers.size() > 0) { doc.addField("answers", join(answers)); } return doc; }
Source:
<code>public static void setEnv(Map<String, String> newVariables) { Map<String, String> newenv = new HashMap<>(); newenv.putAll(System.getenv()); newenv.putAll(newVariables); try { Class<?> processEnvironmentClass = Class.forName(PROCESS_ENVIRONMENT); Field theEnvironmentField = processEnvironmentClass.getDeclaredField(THE_ENVIRONMENT_FILED); theEnvironmentField.setAccessible(true); Map<String, String> env = (Map<String, String>) theEnvironmentField.get(null); env.putAll(newenv); Field theCaseInsensitiveEnvironmentField = processEnvironmentClass .getDeclaredField(THE_CASE_INSENSITIVE_ENVIRONMENT); theCaseInsensitiveEnvironmentField.setAccessible(true); Map<String, String> cienv = (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null); cienv.putAll(newenv); } catch (NoSuchFieldException e) { try { Class[] classes = Collections.class.getDeclaredClasses(); Map<String, String> env = System.getenv(); <START> for (Class cl : classes) { <END> if (COLLECTIONS_UNMODIFIABLE_MAP.equals(cl.getName())) { Field field = cl.getDeclaredField(FIELD_M); field.setAccessible(true); Object obj = field.get(env); Map<String, String> map = (Map<String, String>) obj; map.clear(); map.putAll(newenv); } } } catch (IllegalAccessException | NoSuchFieldException ex) { logger.error("Unable to set environment variable via unmodifiable map", ex); } } catch (ClassNotFoundException | IllegalAccessException e) { logger.error("Unable to set environment variable", e); } }</code><technical_language>java 8 streams here</technical_language>

Target:
public static void setEnv(Map<String, String> newVariables) { Map<String, String> newenv = new HashMap<>(); newenv.putAll(System.getenv()); newenv.putAll(newVariables); try { Class<?> processEnvironmentClass = Class.forName(PROCESS_ENVIRONMENT); Field theEnvironmentField = processEnvironmentClass.getDeclaredField(THE_ENVIRONMENT_FILED); theEnvironmentField.setAccessible(true); Map<String, String> env = (Map<String, String>) theEnvironmentField.get(null); env.putAll(newenv); Field theCaseInsensitiveEnvironmentField = processEnvironmentClass .getDeclaredField(THE_CASE_INSENSITIVE_ENVIRONMENT); theCaseInsensitiveEnvironmentField.setAccessible(true); Map<String, String> cienv = (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null); cienv.putAll(newenv); } catch (NoSuchFieldException e) { Class[] classes = Collections.class.getDeclaredClasses(); Map<String, String> env = System.getenv(); Arrays.asList(classes).stream().filter(cl -> COLLECTIONS_UNMODIFIABLE_MAP.equals(cl.getName())).forEach( (cl) -> { try { Field field = cl.getDeclaredField(FIELD_M); field.setAccessible(true); Object obj = field.get(env); Map<String, String> map = (Map<String, String>) obj; map.clear(); map.putAll(newenv); } catch (IllegalAccessException | NoSuchFieldException ex) { logger.error("Unable to set environment variable via unmodifiable map", ex); } } ); } catch (ClassNotFoundException | IllegalAccessException e) { logger.error("Unable to set environment variable", e); } }
Source:
<code>private List<DatanodeInfo> filterNodes( NodeOperationalState opState, NodeState health) { if (opState != null && health != null) { <START> return filterNodes(new NodeStatus(opState, health)); <END> } if (opState == null && health == null) { return getAllDatanodeInfos(); } ArrayList<DatanodeInfo> nodes = new ArrayList<>(); try { lock.readLock().lock(); for(DatanodeInfo dn : nodeMap.values()) { if (opState != null && dn.getNodeStatus().getOperationalState() != opState) { continue; } if (health != null && dn.getNodeStatus().getHealth() != health) { continue; } nodes.add(dn); } } finally { lock.readLock().unlock(); } return nodes; }</code><technical_language>write Line 395-440 simple stream().filter? wrong code a thought</technical_language>

Target:
private List<DatanodeInfo> filterNodes( NodeOperationalState opState, NodeState health) { if (opState != null && health != null) { return filterNodes(new NodeStatus(opState, health)); } if (opState == null && health == null) { return getAllDatanodeInfos(); } try { lock.readLock().lock(); return nodeMap.values().stream() .filter(n -> opState == null || n.getNodeStatus().getOperationalState() == opState) .filter(n -> health == null || n.getNodeStatus().getHealth() == health) .collect(Collectors.toList()); } finally { lock.readLock().unlock(); } }
Source:
<code>protected ActiveMQDestination(final SimpleString address, final TYPE type, final ActiveMQSession session) { <START> this(address, null, type, session); <END> }</code><technical_language>pass address instead of null for name</technical_language>

Target:
protected ActiveMQDestination(final SimpleString address, final TYPE type, final ActiveMQSession session) { this.simpleAddress = address; this.thetype = type; this.session = session; this.temporary = TYPE.isTemporary(type); this.queue = TYPE.isQueue(type); }
Source:
<code><START> protected HttpMessage createHttpMessageWithRespBody(String responseBody, <END> String contentType) throws HttpMalformedHeaderException, URIException { HttpRequestHeader requestHeader = new HttpRequestHeader(); requestHeader.setURI(new URI("<LINK_0>", false)); msg = new HttpMessage(); msg.setRequestHeader(requestHeader); msg.setResponseBody(responseBody); msg.setResponseHeader( "HTTP/1.1 200 OK\r\n" + "Server: Apache-Coyote/1.1\r\n" + "Content-Type: " + contentType + "\r\n" + "Content-Length: " + responseBody.length() + "\r\n"); return msg; }</code><technical_language>This method indented extra level. file tabs spaces. Running gradle spotlessApply task correctly format things</technical_language>

Target:
protected HttpMessage createHttpMessageWithRespBody(String responseBody, String contentType) throws HttpMalformedHeaderException, URIException { HttpRequestHeader requestHeader = new HttpRequestHeader(); requestHeader.setURI(new URI("<LINK_0>", false)); HttpMessage msg = new HttpMessage(); msg.setRequestHeader(requestHeader); msg.setResponseBody(responseBody); msg.setResponseHeader( "HTTP/1.1 200 OK\r\n" + "Server: Apache-Coyote/1.1\r\n" + "Content-Type: " + contentType + "\r\n" + "Content-Length: " + responseBody.length() + "\r\n"); return msg; }
Source:
<code>private boolean canRemoveVm() { <START> if (getVm() == null) { <END> return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_NOT_EXIST); } if (IsVmRunning(getVmId()) || (getVm().getStatus() == VMStatus.NotResponding)) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_RUNNING); } if (getVm().getStatus() == VMStatus.Suspended) { return failCanDoAction(VdcBllMessages.VM_CANNOT_REMOVE_VM_WHEN_STATUS_IS_NOT_DOWN); } if (isVmInPool(getVmId())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_ATTACHED_TO_POOL); } ValidationResult vmDuringSnapshotResult = new SnapshotsValidator().vmNotDuringSnapshot(getVm().getId()); if (!vmDuringSnapshotResult.isValid()) { addCanDoActionMessage(vmDuringSnapshotResult.getMessage().name()); return false; } VmHandler.updateDisksFromDb(getVm()); if (!ImagesHandler.PerformImagesChecks(getVm(), getReturnValue().getCanDoActionMessages(), getVm().getStoragePoolId(), Guid.Empty, false, !getParameters().getForce(), false, false, getParameters().getForce(), false, !getVm().getDiskMap().values().isEmpty(), true, getVm().getDiskMap().values())) { return false; } if (getParameters().getForce() && getVm().getStatus() == VMStatus.ImageLocked && AsyncTaskManager.getInstance().HasTasksByStoragePoolId(getVm().getStoragePoolId())) { return failCanDoAction(VdcBllMessages.VM_CANNOT_REMOVE_HAS_RUNNING_TASKS); } return true; }</code><technical_language>getVm() null here....it's checked canDoAction</technical_language>

Target:
private boolean canRemoveVm() { if (IsVmRunning(getVmId()) || (getVm().getStatus() == VMStatus.NotResponding)) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_IS_RUNNING); } if (getVm().getStatus() == VMStatus.Suspended) { return failCanDoAction(VdcBllMessages.VM_CANNOT_REMOVE_VM_WHEN_STATUS_IS_NOT_DOWN); } if (isVmInPool(getVmId())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_ATTACHED_TO_POOL); } ValidationResult vmDuringSnapshotResult = new SnapshotsValidator().vmNotDuringSnapshot(getVm().getId()); if (!vmDuringSnapshotResult.isValid()) { addCanDoActionMessage(vmDuringSnapshotResult.getMessage().name()); return false; } VmHandler.updateDisksFromDb(getVm()); if (!ImagesHandler.PerformImagesChecks(getVm(), getReturnValue().getCanDoActionMessages(), getVm().getStoragePoolId(), Guid.Empty, false, !getParameters().getForce(), false, false, getParameters().getForce(), false, !getVm().getDiskMap().values().isEmpty(), true, getVm().getDiskMap().values())) { return false; } if (getParameters().getForce() && getVm().getStatus() == VMStatus.ImageLocked && AsyncTaskManager.getInstance().HasTasksByStoragePoolId(getVm().getStoragePoolId())) { return failCanDoAction(VdcBllMessages.VM_CANNOT_REMOVE_HAS_RUNNING_TASKS); } return true; }
Source:
<code>public void handleGetMbusEncryptionKeyStatusResponse(final DeviceMessageMetadata deviceMessageMetadata, final ResponseMessageResultType resultType, final OsgpException exception, final GetMbusEncryptionKeyStatusResponseDto getMbusEncryptionKeyStatusResponseDto) { LOGGER.info("handleGetMbusEncryptionKeyStatusResponse for MessageType: {}", deviceMessageMetadata.getMessageType()); final String mbusDeviceIdentification = getMbusEncryptionKeyStatusResponseDto.getMbusDeviceIdentification(); final EncryptionKeyStatusType encryptionKeyStatusType = EncryptionKeyStatusType .valueOf(getMbusEncryptionKeyStatusResponseDto.getEncryptionKeyStatus().name()); this.webServiceResponseMessageSender.send( <START> ResponseMessage.newResponseMessageBuilder() <END> .withCorrelationUid(deviceMessageMetadata.getCorrelationUid()) .withOrganisationIdentification(deviceMessageMetadata.getOrganisationIdentification()) .withDeviceIdentification(mbusDeviceIdentification).withResult(resultType) .withOsgpException(exception).withDataObject(encryptionKeyStatusType) .withMessagePriority(deviceMessageMetadata.getMessagePriority()).build(), deviceMessageMetadata.getMessageType()); }</code><technical_language>Extract building of ResponseMessage variable (in eclipse, select text, right-click > refactor > extract local variable / select code + shift+alt+L). This code a bit more readable, especially passing in other besides ResponseMessage</technical_language>

Target:
public void handleGetMbusEncryptionKeyStatusResponse(final DeviceMessageMetadata deviceMessageMetadata, final ResponseMessageResultType resultType, final OsgpException exception, final GetMbusEncryptionKeyStatusResponseDto getMbusEncryptionKeyStatusResponseDto) { LOGGER.info("handleGetMbusEncryptionKeyStatusResponse for MessageType: {}", deviceMessageMetadata.getMessageType()); final String mbusDeviceIdentification = getMbusEncryptionKeyStatusResponseDto.getMbusDeviceIdentification(); final EncryptionKeyStatusType encryptionKeyStatusType = EncryptionKeyStatusType .valueOf(getMbusEncryptionKeyStatusResponseDto.getEncryptionKeyStatus().name()); ResponseMessage responseMessage = ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(deviceMessageMetadata.getCorrelationUid()) .withOrganisationIdentification(deviceMessageMetadata.getOrganisationIdentification()) .withDeviceIdentification(mbusDeviceIdentification).withResult(resultType) .withOsgpException(exception).withDataObject(encryptionKeyStatusType) .withMessagePriority(deviceMessageMetadata.getMessagePriority()).build(); this.webServiceResponseMessageSender.send( responseMessage, deviceMessageMetadata.getMessageType()); }
Source:
<code>public void testTimestamps() { assertQueryUsingH2Cte("SELECT ship_timestamp FROM lineitem_ex"); assertQueryUsingH2Cte("SELECT ship_timestamp FROM lineitem_ex WHERE ship_timestamp < TIMESTAMP '1993-01-01 01:00:00'"); assertQueryUsingH2Cte("SELECT count(*) FROM lineitem_ex WHERE ship_timestamp IS NOT NULL"); <START> assertQueryUsingH2Cte("SELECT count(*) FROM lineitem_ex WHERE ship_timestamp = (TIMESTAMP '2012-08-08 01:00:00')"); <END> assertQueryUsingH2Cte("SELECT commit_timestamp, ship_timestamp FROM lineitem_ex"); assertQueryUsingH2Cte("SELECT commit_timestamp, ship_timestamp FROM lineitem_ex WHERE ship_timestamp > (TIMESTAMP '1993-08-08 01:00:00') AND commit_timestamp < (TIMESTAMP '1993-08-08 01:00:00')"); assertQueryUsingH2Cte("SELECT commit_timestamp, ship_timestamp FROM lineitem_ex WHERE year(ship_timestamp) - year(commit_timestamp) > 1"); assertQueryUsingH2Cte("SELECT COUNT(*) FROM lineitem_ex WHERE commit_timestamp IS NULL"); assertQueryUsingH2Cte("SELECT commit_timestamp, ship_timestamp, orderkey FROM lineitem_ex WHERE year(commit_timestamp) > 1993 and year(ship_timestamp) > 1993 and year(ship_timestamp) - year(commit_timestamp) = 1"); }</code><technical_language>parentheses TIMESTAMP ... needed</technical_language>

Target:
public void testTimestamps() { assertQueryUsingH2Cte("SELECT ship_timestamp FROM lineitem_ex"); assertQueryUsingH2Cte("SELECT ship_timestamp FROM lineitem_ex WHERE ship_timestamp < TIMESTAMP '1993-01-01 01:00:00'"); assertQueryUsingH2Cte("SELECT count(*) FROM lineitem_ex WHERE ship_timestamp IS NOT NULL"); assertQueryUsingH2Cte("SELECT count(*) FROM lineitem_ex WHERE ship_timestamp = TIMESTAMP '2012-08-08 01:00:00'"); assertQueryUsingH2Cte("SELECT commit_timestamp, ship_timestamp FROM lineitem_ex"); assertQueryUsingH2Cte("SELECT commit_timestamp, ship_timestamp FROM lineitem_ex WHERE ship_timestamp > TIMESTAMP '1993-08-08 01:00:00' AND commit_timestamp < TIMESTAMP '1993-08-08 01:00:00'"); assertQueryReturnsEmptyResult("SELECT commit_timestamp, ship_timestamp FROM lineitem_ex WHERE year(ship_timestamp) - year(commit_timestamp) > 1"); assertQueryUsingH2Cte("SELECT commit_timestamp, ship_timestamp, orderkey FROM lineitem_ex WHERE year(commit_timestamp) > 1993 and year(ship_timestamp) > 1993 and year(ship_timestamp) - year(commit_timestamp) = 1"); }
Source:
<code>private void handleCredentials(HttpServletRequest request, String user, String password) { UserProfile userProfile = translateUser(user); <START> AuthenticationProfile profile = AuthenticationProfileRepository.getInstance().getProfile(userProfile.profile); <END> if (profile == null) { log.error(String.format("Error in obtaining profile %1$s", userProfile.profile)); } else { ExtMap outputMap = profile.getAuthn().invoke(new ExtMap().mput( Base.InvokeKeys.COMMAND, Authn.InvokeCommands.AUTHENTICATE_CREDENTIALS ).mput( Authn.InvokeKeys.USER, userProfile.userName ).mput( Authn.InvokeKeys.CREDENTIALS, password ) ); if (outputMap.<Integer> get(Base.InvokeKeys.RESULT) == Base.InvokeResult.SUCCESS && outputMap.<Integer> get(Authn.InvokeKeys.RESULT) == Authn.AuthResult.SUCCESS) { request.setAttribute(FiltersHelper.Constants.REQUEST_AUTH_RECORD_KEY, outputMap.<ExtMap> get(Authn.InvokeKeys.AUTH_RECORD)); request.setAttribute(FiltersHelper.Constants.REQUEST_PROFILE_KEY, userProfile.profile); } else { log.error( String.format( "Failure in authentication to profile %1$s. Invocation Result code is %2$s. Authn result code is %3$s", userProfile.profile, outputMap.<Integer> get(Base.InvokeKeys.RESULT), outputMap.<Integer> get(Authn.InvokeKeys.RESULT) ) ); } } }</code><technical_language>put profile UserProfile class... no? fail if (return null translateUser)</technical_language>

Target:
private void handleCredentials(HttpServletRequest request, String user, String password) { UserProfile userProfile = translateUser(user); if (userProfile == null || userProfile.profile == null) { log.error(String.format("Error in obtaining profile %1$s", userProfile.profile)); } else { ExtMap outputMap = userProfile.profile.getAuthn().invoke(new ExtMap().mput( Base.InvokeKeys.COMMAND, Authn.InvokeCommands.AUTHENTICATE_CREDENTIALS ).mput( Authn.InvokeKeys.USER, userProfile.userName ).mput( Authn.InvokeKeys.CREDENTIALS, password ) ); if (outputMap.<Integer> get(Base.InvokeKeys.RESULT) == Base.InvokeResult.SUCCESS && outputMap.<Integer> get(Authn.InvokeKeys.RESULT) == Authn.AuthResult.SUCCESS) { request.setAttribute(FiltersHelper.Constants.REQUEST_AUTH_RECORD_KEY, outputMap.<ExtMap> get(Authn.InvokeKeys.AUTH_RECORD)); request.setAttribute(FiltersHelper.Constants.REQUEST_PROFILE_KEY, userProfile.profile.getName()); } else { log.error( String.format( "Failure in authentication to profile %1$s. Invocation Result code is %2$s. Authn result code is %3$s", userProfile.profile, outputMap.<Integer> get(Base.InvokeKeys.RESULT), outputMap.<Integer> get(Authn.InvokeKeys.RESULT) ) ); } } }
Source:
<code>protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String requestUri = request.getRequestURI(); logger.debug("Starting execution of proxy request for {}", requestUri); SiteContext siteContext = SiteContext.getCurrent(); if (siteContext == null) { throw new IllegalStateException("Can't resolve site context for current request"); } String siteName = siteContext.getSiteName(); logger.debug("Resolved site for proxy request {}", siteName, requestUri); String targetUrl = getTargetUrl(siteContext, requestUri); logger.debug("Resolved target url for proxy request {}", targetUrl, requestUri); if (request.getRequestURL().toString().contains(targetUrl)) { logger.debug("Resolved target url for request is local, will skip proxy", requestUri); <START> throw new HttpProxyException("Local target url detected"); <END> } request.setAttribute(ATTR_TARGET_URI, targetUrl); request.setAttribute(ATTR_TARGET_HOST, URIUtils.extractHost(URI.create(targetUrl))); super.service(request, response); }</code><technical_language>I another exception specific this case, LocalTargetUrlProxyException</technical_language>

Target:
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String requestUri = request.getRequestURI(); logger.debug("Starting execution of proxy request for {}", requestUri); SiteContext siteContext = SiteContext.getCurrent(); if (siteContext == null) { throw new IllegalStateException("Can't resolve site context for current request"); } String siteName = siteContext.getSiteName(); logger.debug("Resolved site for proxy request {}", siteName, requestUri); String targetUrl = getTargetUrl(siteContext, requestUri); logger.debug("Resolved target url for proxy request {}", targetUrl, requestUri); if (request.getRequestURL().toString().contains(targetUrl)) { logger.debug("Resolved target url for request is local, will skip proxy", requestUri); throw new LocalTargetUrlProxyException("Local target url detected"); } request.setAttribute(ATTR_TARGET_URI, targetUrl); request.setAttribute(ATTR_TARGET_HOST, URIUtils.extractHost(URI.create(targetUrl))); super.service(request, response); }
Source:
<code>public void serialize(XMLExtendedStreamWriter writer, JdbcBinaryStoreConfiguration configuration) throws XMLStreamException { writer.writeStartElement(Element.BINARY_KEYED_JDBC_STORE); <START> writeJdbcStoreAttributes(writer, configuration); <END> writeJDBCStoreTable(writer, Element.BINARY_KEYED_TABLE, configuration.table()); writeCommonStoreElements(writer, configuration); writer.writeEndElement(); }</code><technical_language>CONCURRENCY_LEVEL LOCK_ACQUISITION_TIMEOUT missing</technical_language>

Target:
public void serialize(XMLExtendedStreamWriter writer, JdbcBinaryStoreConfiguration configuration) throws XMLStreamException { writer.writeStartElement(Element.BINARY_KEYED_JDBC_STORE); writeJdbcStoreAttributes(writer, configuration); writeCommonStoreSubAttributes(writer, configuration); writeJDBCStoreTable(writer, Element.BINARY_KEYED_TABLE, configuration.table()); writeJDBCStoreConnection(writer, configuration); writeCommonStoreElements(writer, configuration); writer.writeEndElement(); }
Source:
<code>private static GoNamedElement getFieldDefinition(@Nullable GoValue value) { GoKey key = PsiTreeUtil.getPrevSiblingOfType(value, GoKey.class); GoFieldName fieldName = key != null ? key.getFieldName() : null; PsiElement field = fieldName != null ? fieldName.resolve() : null; return field instanceof GoAnonymousFieldDefinition || field instanceof GoFieldDefinition ? ObjectUtils <START> .tryCast(field, GoNamedElement.class) : null; <END> }</code><technical_language>bad formatting</technical_language>

Target:
private static GoNamedElement getFieldDefinition(@Nullable GoValue value) { GoKey key = PsiTreeUtil.getPrevSiblingOfType(value, GoKey.class); GoFieldName fieldName = key != null ? key.getFieldName() : null; PsiElement field = fieldName != null ? fieldName.resolve() : null; return GoPsiImplUtil.isFieldDefinition(field) ? ObjectUtils.tryCast(field, GoNamedElement.class) : null; }
Source:
<code>public static final InputRow fromBytes(byte[] data, AggregatorFactory[] aggs) { try { DataInput in = ByteStreams.newDataInput(data); long timestamp = in.readLong(); Map<String, Object> event = Maps.newHashMap(); List<String> dimensions = Lists.newArrayList(); int dimNum = WritableUtils.readVInt(in); for(int i = 0; i < dimNum; i++) { String dimension = readString(in); dimensions.add(dimension); List<String> dimensionValues = readStringArray(in); if(dimensionValues==null) { continue; } if(dimensionValues.size() == 1) { event.put(dimension, dimensionValues.get(0)); } else { event.put(dimension, dimensionValues); } } int metricSize = WritableUtils.readVInt(in); for(int i = 0; i < metricSize; i++) { String metric = readString(in); <START> String type = readString(in); <END> if(type.equals(FLOAT)) { event.put(metric, in.readFloat()); } else if(type.equals(LONG)) { event.put(metric, WritableUtils.readVLong(in)); } else { ComplexMetricSerde serde = getComplexMetricSerde(type); byte[] value = readBytes(in); event.put(metric, serde.fromBytes(value, 0, value.length)); } } return new MapBasedInputRow(timestamp, dimensions, event); } catch(IOException ex) { throw Throwables.propagate(ex); } }</code><technical_language>type encoded a number instead of string, ValueType.XXX.ordinal() encoding. io.druid.segment.column.ValueType is enum defined types</technical_language>

Target:
public static final InputRow fromBytes(byte[] data, AggregatorFactory[] aggs) { try { DataInput in = ByteStreams.newDataInput(data); long timestamp = in.readLong(); Map<String, Object> event = Maps.newHashMap(); List<String> dimensions = Lists.newArrayList(); int dimNum = WritableUtils.readVInt(in); for (int i = 0; i < dimNum; i++) { String dimension = readString(in); dimensions.add(dimension); List<String> dimensionValues = readStringArray(in); if (dimensionValues == null) { continue; } if (dimensionValues.size() == 1) { event.put(dimension, dimensionValues.get(0)); } else { event.put(dimension, dimensionValues); } } int metricSize = WritableUtils.readVInt(in); for (int i = 0; i < metricSize; i++) { String metric = readString(in); String type = getType(metric, aggs, i); if (type.equals("float")) { event.put(metric, in.readFloat()); } else if (type.equals("long")) { event.put(metric, WritableUtils.readVLong(in)); } else { ComplexMetricSerde serde = getComplexMetricSerde(type); byte[] value = readBytes(in); event.put(metric, serde.fromBytes(value, 0, value.length)); } } return new MapBasedInputRow(timestamp, dimensions, event); } catch(IOException ex) { throw Throwables.propagate(ex); } }
Source:
<code>private long getCowVirtualSize(String id) throws IOException { <START> byte[] imgContent = new byte[72]; <END> ImageDownload downloadImage = getGlanceClient().images().download(id).execute(); try { int bytesRead = downloadImage.getInputStream().read(imgContent, 0, imgContent.length); if (bytesRead != imgContent.length) { throw new RuntimeException("Unable to read image header: " + bytesRead); } } finally { downloadImage.getInputStream().close(); } ByteBuffer b = ByteBuffer.wrap(imgContent); if (b.getInt() == 0x514649fb && b.getInt() == 2) { b.position(24); return b.getLong(); } throw new RuntimeException("Unable to recognize QCOW2 format"); }</code><technical_language>export length a constant</technical_language>

Target:
private long getCowVirtualSize(String id) throws IOException { byte[] imgContent = new byte[72]; ImageDownload downloadImage = getClient().images().download(id).execute(); try { int bytesRead = downloadImage.getInputStream().read(imgContent, 0, imgContent.length); if (bytesRead != imgContent.length) { throw new RuntimeException("Unable to read image header: " + bytesRead); } } finally { downloadImage.getInputStream().close(); } ByteBuffer b = ByteBuffer.wrap(imgContent); if (b.getInt() == 0x514649fb && b.getInt() == 2) { b.position(24); return b.getLong(); } throw new RuntimeException("Unable to recognize QCOW2 format"); }
Source:
<code>private void setRetryBackoff(long backOffMs) { <START> context.backoffMs(backOffMs); <END> }</code><technical_language>I mentioned this in review of patch adds this method, this implement backoff for full timeout. ensures get another callback _within_ timeout. This result in retrying a lot more if some partitions healthy receiving data. record timestamp failure occurred decide proceed execute() based desired amount of time elapsed yet</technical_language>

Target:
private void setRetryBackoff(long backOffMs) { context.timeout(backOffMs); }
Source:
<code>public static OAuth2AuthorizationRequest.Builder request() { String registrationId = "registration-id"; String clientId = "client-id"; Map<String, Object> additionalParameters = new HashMap<>(); additionalParameters.put(OAuth2ParameterNames.REGISTRATION_ID, registrationId); return OAuth2AuthorizationRequest.authorizationCode() .authorizationUri("<LINK_0>") .clientId(clientId) <START> .scope("openid") <END> .redirectUri("<LINK_1>") .state("state") .additionalParameters(additionalParameters); }</code><technical_language>verify this break existing test assumptions? modify this impact this is existing tests. invalidate a test expectations of scopes</technical_language>

Target:
public static OAuth2AuthorizationRequest.Builder request() { String registrationId = "registration-id"; String clientId = "client-id"; Map<String, Object> additionalParameters = new HashMap<>(); additionalParameters.put(OAuth2ParameterNames.REGISTRATION_ID, registrationId); return OAuth2AuthorizationRequest.authorizationCode() .authorizationUri("<LINK_0>") .clientId(clientId) .redirectUri("<LINK_1>") .state("state") .additionalParameters(additionalParameters); }
Source:
<code>public static boolean reportNewVersion(String newVersion, String currentVersion) { if (newVersion == null || newVersion.equals("")) { return false; } <START> if (newVersion.toLowerCase(Locale.US).endsWith("beta")) { <END> return false; } return !newVersion.equals(currentVersion); }</code><technical_language>endswith -> contains more robust</technical_language>

Target:
public static boolean reportNewVersion(String newVersion, String currentVersion) { if (newVersion == null || newVersion.equals("")) { return false; } if (!newVersion.matches(REALM_VERSION_PATTERN)) { return false; } return !newVersion.equals(currentVersion); }
Source:
<code>public static void main(String[] args) throws Exception { HeadlessEnvironment env = new HEnv(new Name("engine")); Context context = env.getContext(); ModuleManager moduleManager = context.get(ModuleManager.class); Future<Void> remoteModuleRegistryUpdater = Executors.newSingleThreadExecutor() .submit(moduleManager.getInstallManager().updateRemoteRegistry()); remoteModuleRegistryUpdater.get(); List<Module> sortedGameModules = getListOfGameModules(moduleManager); List<Module> sortedRemoteModules = getListofRemoteModules(moduleManager); <START> String wiki = generateWiki(moduleManager, sortedGameModules, sortedRemoteModules); <END> String fileName = "Module_Wiki.md"; BufferedWriter writer = new BufferedWriter(new FileWriter(new File(fileName))); writer.write(wiki); writer.flush(); writer.close(); System.out.println("Module Wiki generation file is ready!"); env.close(); }</code><technical_language>Thanks for breaking this smaller chunks</technical_language>

Target:
public static void main(String[] args) throws Exception { HeadlessEnvironment env = new ModuleMetaDataProvidingHeadlessEnvironment(new Name("engine")); Context context = env.getContext(); ModuleManager moduleManager = context.get(ModuleManager.class); List<Module> sortedGameModules = getListOfGameModules(moduleManager); List<Module> sortedRemoteModules = getListofRemoteModules(moduleManager); String wiki = generateWiki(moduleManager, sortedGameModules, sortedRemoteModules); String fileName = "Module_Wiki.md"; BufferedWriter writer = new BufferedWriter(new FileWriter(new File(fileName))); writer.write(wiki); writer.flush(); writer.close(); System.out.println("Module Wiki generation file is ready!"); env.close(); }
Source:
<code><START> public CannedAccessControlList getCannedACL() <END> { return cannedACL; }</code><technical_language>this package private</technical_language>

Target:
CannedAccessControlList getCannedACL() { return cannedACL; }
Source:
<code>public static void register(AggregationImplModule mod) { for (var supportedType : DataTypes.PRIMITIVE_TYPES) { mod.register( Signature.aggregate( NAME, supportedType.getTypeSignature(), supportedType.getTypeSignature()), args -> { var arg = args.get(0); var info = new FunctionInfo( new FunctionIdent(NAME, args), arg, FunctionInfo.Type.AGGREGATE ); if (arg instanceof FixedWidthType) { return new FixedMaximumAggregation(info); } else { <START> return new VariableMaximumAggregation(info); <END> } } ); } }</code><technical_language>minor: decide this of factory method avoid "on-call/on-demand" instanceof checks</technical_language>

Target:
public static void register(AggregationImplModule mod) { for (var supportedType : DataTypes.PRIMITIVE_TYPES) { var fixedWidthType = supportedType instanceof FixedWidthType; mod.register( Signature.aggregate( NAME, supportedType.getTypeSignature(), supportedType.getTypeSignature()), args -> { var arg = args.get(0); var info = new FunctionInfo( new FunctionIdent(NAME, args), arg, FunctionInfo.Type.AGGREGATE ); return fixedWidthType ? new FixedMaximumAggregation(info) : new VariableMaximumAggregation(info); } ); } }
Source:
<code><START> protected void editTextAndVerify(Address address, String attributeName, int value) throws Exception { <END> page.getConfigFragment().editTextAndSave(attributeName, String.valueOf(value)); administration.reloadIfRequired(); new ResourceVerifier(address, client).verifyAttribute(attributeName, value); }</code><technical_language>if in 100% UI identifier model attributeName. SMAP above. add methods more attribute identifier for cases identifier is attributeName ... for boolean (SMAP)</technical_language>

Target:
protected void editTextAndVerify(Address address, String attributeName, int value) throws Exception { page.getConfigFragment().editTextAndSave(attributeName, String.valueOf(value)); new ResourceVerifier(address, client).verifyAttribute(attributeName, value); }
Source:
<code>public static void addExtension(String name) { <START> String br = Configuration.getBrowser(); <END> try { if ("FF".equalsIgnoreCase(br)) { NewDriverProvider.getFirefoxProfile().addExtension(findExtension(name, "xpi")); } else if (br.contains("CHROME")) { NewDriverProvider.getChromeOptions().addExtensions(findExtension(name, "crx")); } else { throw new WebDriverException( String.format("'%s' browser doesn't support adding of extensions", br)); } } catch (IOException e) { PageObjectLogging.log("Error occurred during adding '" + name + "' extension", e, false); } }</code><technical_language>more meaningful variable name, instead of br, browser currentBrowser</technical_language>

Target:
public static void addExtension(String name) { String browser = Configuration.getBrowser(); try { if ("FF".equalsIgnoreCase(browser)) { NewDriverProvider.getFirefoxProfile().addExtension(findExtension(name, "xpi")); } else if (browser.contains("CHROME")) { NewDriverProvider.getChromeOptions().addExtensions(findExtension(name, "crx")); } else { throw new WebDriverException( String.format("'%s' browser doesn't support adding of extensions", browser)); } } catch (IOException e) { PageObjectLogging.log("Error occurred during adding '" + name + "' extension", e, false); } }
Source:
<code>public Headers getHeadersFromGET(String url) { MockMvcRequestSpecification o = givenLocal().contentType(MediaType.TEXT_PLAIN_VALUE); <START> logger.debug("[getArtifact] URL " + url); <END> MockMvcResponse response = o.when().get(url); Headers allHeaders = response.getHeaders(); logger.debug("HTTP GET " + url); logger.debug("Response headers:"); allHeaders.forEach(header -> logger.debug("\t" + header.getName() + " = " + header.getValue())); if (response.getStatusCode() == OK || response.getStatusCode() == PARTIAL_CONTENT) { logger.debug("Received headers successfully."); return allHeaders; } else { logger.warn("[getArtifactAsByteArray] response " + response.getStatusCode()); return null; } }</code><technical_language>drop this logging here</technical_language>

Target:
public Headers getHeadersFromGET(String url) { MockMvcRequestSpecification o = givenLocal().contentType(MediaType.TEXT_PLAIN_VALUE); <<<<<<< 1d9871871bd012858efed0af3d97ca24f450461e ======= >>>>>>> Fixed PR MockMvcResponse response = o.when().get(url); Headers allHeaders = response.getHeaders(); logger.debug("HTTP GET " + url); logger.debug("Response headers:"); allHeaders.forEach(header -> logger.debug("\t" + header.getName() + " = " + header.getValue())); if (response.getStatusCode() == OK || response.getStatusCode() == PARTIAL_CONTENT) { logger.debug("Received headers successfully."); return allHeaders; } else { logger.warn("[getArtifactAsByteArray] response " + response.getStatusCode()); return null; } }
Source:
<code>private Optional<String> parseUsingGrobid(String plainText) { try { return Optional.of(grobidService.processCitation(plainText, GrobidService.ConsolidateCitations.WITH_METADATA)); } catch (IOException e) { <START> throw new UncheckedIOException("Could not process citation. " + e.getMessage(), e); <END> } }</code><technical_language>Please ParserException instead of uncheckedioex</technical_language>

Target:
private Optional<String> parseUsingGrobid(String plainText) { try { return Optional.of(grobidService.processCitation(plainText, GrobidService.ConsolidateCitations.WITH_METADATA)); } catch (SocketTimeoutException e) { String msg = "Connection timed out."; LOGGER.debug(msg, e); throw new RuntimeException(msg, e); } catch (IOException e) { String msg = "Could not process citation. " + e.getMessage(); LOGGER.debug(msg, e); throw new RuntimeException(msg, e); } }
Source:
<code>public NotificationService(NotificationProperties prop) throws NotificationServiceException { this.prop = prop; this.eventsManager = new EventsManager(); this.firstMatchSimpleFilter = new FirstMatchSimpleFilter(); Smtp smtp = new Smtp(prop); smtp.addObserver(this.eventsManager); <START> addTransport(smtp); <END> this.firstMatchSimpleFilter.registerTransport(smtp); configurationFilters = FirstMatchSimpleFilter.parse(prop.getProperty(NotificationProperties.FILTER)); markOldEventsAsProcessed(); }</code><technical_language>if transports is private, is need for a method wraps list add</technical_language>

Target:
public NotificationService(NotificationProperties prop) throws NotificationServiceException { this.prop = prop; this.eventsManager = new EventsManager(); this.firstMatchSimpleFilter = new FirstMatchSimpleFilter(); configurationFilters = FirstMatchSimpleFilter.parse(prop.getProperty(NotificationProperties.FILTER)); markOldEventsAsProcessed(); }
Source:
<code><START> protected byte[][] randomData(String prefix, int count) { <END> byte[][] result = new byte[count][]; for (int i = 0; i < count; ++i) { result[i] = Bytes.toBytes(prefix + RandomStringUtils.randomAlphanumeric(8)); } return result; }</code><technical_language>public</technical_language>

Target:
public byte[][] randomData(String prefix, int count) { byte[][] result = new byte[count][]; for (int i = 0; i < count; ++i) { result[i] = Bytes.toBytes(prefix + RandomStringUtils.randomAlphanumeric(8)); } return result; }
Source:
<code>public void updateDynamicSetting( String setting, String update ) throws IllegalArgumentException, InvalidSettingException { verifyValidDynamicSetting( setting ); synchronized ( params ) { <START> boolean oldDefault = false; <END> boolean newDefault = false; String oldValue; String newValue; if ( update == null || update.isEmpty() ) { String overriddenDefault = overriddenDefaults.get( setting ); boolean hasDefault = overriddenDefault != null; oldValue = hasDefault ? params.put( setting, overriddenDefault ) : params.remove( setting ); newValue = getDefaultValueOf( setting ); newDefault = true; } else { Map<String,String> newEntry = stringMap( setting, update ); List<SettingValidator> settingValidators = configOptions.stream() .map( ConfigOptions::settingGroup ) .collect( Collectors.toList() ); for ( SettingValidator validator : settingValidators ) { validator.validate( newEntry, ignore -> ); } oldValue = getDefaultValueOf( setting ); if ( params.put( setting, update ) == null ) { oldDefault = true; } newValue = update; } log.info( "Setting changed: '%s' changed from '%s' to '%s'", setting, oldDefault ? "default (" + oldValue + ")" : oldValue, newDefault ? "default (" + newValue + ")" : newValue ); updateListeners.getOrDefault( setting, emptyList() ).forEach( l -> l.accept( oldValue, newValue ) ); } }</code><technical_language>hard guess oldDefault newDefault called this</technical_language>

Target:
public void updateDynamicSetting( String setting, String update ) throws IllegalArgumentException, InvalidSettingException { verifyValidDynamicSetting( setting ); synchronized ( params ) { boolean oldValueIsDefault = false; boolean newValueIsDefault = false; String oldValue; String newValue; if ( update == null || update.isEmpty() ) { String overriddenDefault = overriddenDefaults.get( setting ); boolean hasDefault = overriddenDefault != null; oldValue = hasDefault ? params.put( setting, overriddenDefault ) : params.remove( setting ); newValue = getDefaultValueOf( setting ); newValueIsDefault = true; } else { Map<String,String> newEntry = stringMap( setting, update ); List<SettingValidator> settingValidators = configOptions.stream() .map( ConfigOptions::settingGroup ) .collect( Collectors.toList() ); for ( SettingValidator validator : settingValidators ) { validator.validate( newEntry, ignore -> ); } String previousValue = params.put( setting, update ); if ( previousValue != null ) { oldValue = previousValue; } else { oldValue = getDefaultValueOf( setting ); oldValueIsDefault = true; } newValue = update; } log.info( "Setting changed: '%s' changed from '%s' to '%s'", setting, oldValueIsDefault ? "default (" + oldValue + ")" : oldValue, newValueIsDefault ? "default (" + newValue + ")" : newValue ); updateListeners.getOrDefault( setting, emptyList() ).forEach( l -> l.accept( oldValue, newValue ) ); } }
Source:
<code>public void flatMapTest(){ String result = TransactionFlow.of(transactionTemplate, this::load) .flatMap(this::newTransaction) .execute(10) .orElse(""); <START> <END> }</code><technical_language>Is this test missing assert</technical_language>

Target:
public void flatMapTest(){ String result = TransactionFlow.of(transactionTemplate, this::load) .flatMap(this::newTransaction) .execute(10) .orElse(""); assertThat(result,equalTo("data:10")); }
Source:
<code><START> public void actionShare(HomeActivity activity, ArrayList<IndexedItem> with, IOnResult<Boolean> listener) { <END> if (with.size() == 1 && with.get(0) instanceof IndexedFile) { IndexedFile file = (IndexedFile) with.get(0); Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); intent.putExtra(Intent.EXTRA_SUBJECT, activity.getString(R.string.share_file)); MimeTypeMap map = MimeTypeMap.getSingleton(); String mimeType = map.getMimeTypeFromExtension(file.getExtension().substring(1)); intent.setType(mimeType); Uri uri = Uri.fromFile(file.getUnlockedFile()); intent.putExtra(Intent.EXTRA_STREAM, uri); activity.setRequestedActivity(true); try { activity.startActivity(intent); } catch (ActivityNotFoundException e) { Utils.toast(R.string.share_not_found); } } else { Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND_MULTIPLE); intent.putExtra(Intent.EXTRA_SUBJECT, activity.getString(R.string.share_files)); ArrayList<Uri> files = new ArrayList<Uri>(); ArrayList<String> mimes = new ArrayList<String>(); MimeTypeMap myMime = MimeTypeMap.getSingleton(); for (IndexedItem item : with) { if (item instanceof IndexedFile) { IndexedFile file = (IndexedFile) item; Uri uri = Uri.fromFile(file.getUnlockedFile()); String mimeType = myMime.getMimeTypeFromExtension(file.getExtension().substring(1)); if (!mimes.contains(mimeType)) { mimes.add(mimeType); } files.add(uri); } } StringBuilder sb = new StringBuilder(); for (String mime : mimes) { sb.append(mime); sb.append(','); } sb.deleteCharAt(sb.length() - 1); String mimeType = sb.toString(); Utils.d("Mimetype: " + mimeType); intent.setType(mimeType); intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, files); try { activity.startActivity(intent); } catch (ActivityNotFoundException e) { Utils.toast(R.string.multi_share_not_found); } } if (listener != null) { listener.onResult(true); } }</code><technical_language>this refactored, a long method atm</technical_language>

Target:
public void actionShare(HomeActivity activity, ArrayList<IndexedItem> with, IOnResult<Boolean> listener) { Intent shareIntent; if (with.size() == 1 && with.get(0) instanceof IndexedFile) { shareIntent = getShareIntentSingle((IndexedFile) with.get(0)); } else { shareIntent = getShareIntentMultiple(with); } activity.setRequestedActivity(true); boolean activityFound = true; try { activity.startActivity(shareIntent); } catch (ActivityNotFoundException e) { Utils.toast(R.string.share_not_found); activityFound = false; } if (listener != null) { listener.onResult(activityFound); } }
Source:
<code>protected List<Section> getScrolledCompositeSections() { List<Section> sections = new ArrayList<Section>(); if (scrolledComposite.getChildren().length != 0 && scrolledComposite.getChildren()[0] instanceof Composite) { Composite sectionContainer = (Composite) scrolledComposite.getChildren()[0]; <START> sections = Lists.newArrayList(Iterables.filter(Arrays.asList(sectionContainer.getChildren()), Section.class)); <END> } return sections; }</code><technical_language>In case, FluentIterable.filter Iterables.filter creates a FluentIterable anyway</technical_language>

Target:
protected List<Section> getScrolledCompositeSections() { List<Section> sections = new ArrayList<Section>(); if (scrolledComposite.getChildren().length != 0 && scrolledComposite.getChildren()[0] instanceof Composite) { Composite sectionContainer = (Composite) scrolledComposite.getChildren()[0]; sections = FluentIterable.from(Arrays.asList(sectionContainer.getChildren())) .filter(Section.class) .toList(); } return sections; }
Source:
<code>private void setAutoPanMode(AutoPanMode current, AutoPanMode update) { <START> if (mPanMode.compareAndSet(current, update)) { <END> switch (current) { case DRONE: LocalBroadcastManager.getInstance(getActivity().getApplicationContext()) .unregisterReceiver(eventReceiver); break; case DISABLED: default: break; } switch (update) { case DRONE: LocalBroadcastManager.getInstance(getActivity().getApplicationContext()).registerReceiver (eventReceiver, mEventFilter); break; case DISABLED: default: break; } } }</code><technical_language>@droneboost call mPanMode.compareAndSet(current, update) accomplish intended functionality. especially want unregister event receiver filtering events besides drone gps updates</technical_language>

Target:
private void setAutoPanMode(AutoPanMode current, AutoPanMode update) { mPanMode.compareAndSet(current, update); }