auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>default void testListColumnsOneSchema() throws Exception { SchemaTableName schemaTableName1 = schemaTableName("table1"); SchemaTableName schemaTableName2 = schemaTableName("table2"); ConnectorSession session = new TestingConnectorSession(ImmutableList.of()); List<ColumnMetadata> columns = ImmutableList.of( new ColumnMetadata("bigint_column", BIGINT), new ColumnMetadata("double_column", DOUBLE)); List<ColumnMetadata> expectedColumns = withSystemColumns(columns); ConnectorTableMetadata tableMetadata11 = new ConnectorTableMetadata(schemaTableName1, columns, getTableProperties()); ConnectorTableMetadata tableMetadata12 = new ConnectorTableMetadata(schemaTableName2, columns, getTableProperties()); <START> try (AutoCloseable cleanup = withTables(session, tableMetadata11, tableMetadata12)) { <END> run(ImmutableList.of( metadata -> assertEquals(metadata.listTableColumns(session, new SchemaTablePrefix()), ImmutableMap.of( schemaTableName1, expectedColumns, schemaTableName2, expectedColumns)), metadata -> assertEquals(metadata.listTableColumns(session, prefixOf(schemaTableName1)), ImmutableMap.of( schemaTableName1, expectedColumns)))); } }</code><technical_language>API nicer now. 4 issues. 1. I a big fan of withTables Consumer<ConnectorMetadata>. This assumes withTables is innermost call for multiple wrapped with* methods. interface of withTables differ interface of withSchemas for I dot a good point. currently withTables withSchemas list grow time. methods Runnable functional argument Consumer<T> if producing T (e.g. for withMetadata T is Metadata). 2. withTables single Runnable List<Runnable> (List<Consumer<ConnectorMetadata>> in code) 3. I worthy expand withTables tables argument. versions 1,2,3,4 tables</technical_language>

Target:
default void testListColumnsOneSchema() throws Exception { SchemaTableName schemaTableName1 = schemaTableName("table1"); SchemaTableName schemaTableName2 = schemaTableName("table2"); ConnectorSession session = new TestingConnectorSession(ImmutableList.of()); List<ColumnMetadata> columns = ImmutableList.of( new ColumnMetadata("bigint_column", BIGINT), new ColumnMetadata("double_column", DOUBLE)); List<ColumnMetadata> expectedColumns = extendWithConnectorSpecificColumns(columns); ConnectorTableMetadata tableMetadata11 = new ConnectorTableMetadata(schemaTableName1, columns, getTableProperties()); ConnectorTableMetadata tableMetadata12 = new ConnectorTableMetadata(schemaTableName2, columns, getTableProperties()); withTables(session, ImmutableList.of(tableMetadata11, tableMetadata12), ImmutableList.of( metadata -> assertEquals(metadata.listTableColumns(session, new SchemaTablePrefix()), ImmutableMap.of( schemaTableName1, expectedColumns, schemaTableName2, expectedColumns)), metadata -> assertEquals(metadata.listTableColumns(session, prefixOf(schemaTableName1)), ImmutableMap.of( schemaTableName1, expectedColumns)))); }
Source:
<code>public void process(Event event) { Map<String, String> dynamicProperties = new HashMap<String, String>(eventPublisherConfiguration.getToAdapterDynamicProperties()); Object outObject; if (traceEnabled) { trace.info(beforeTracerPrefix + event); } if (statisticsEnabled) { eventCounter.inc(); } if (!processingEnabled){ <START> log.info(enable_message); <END> return; } org.wso2.siddhi.core.event.Event siddhiEvent = EventPublisherUtil.convertToSiddhiEvent(event, inputStreamSize); try { if (customMappingEnabled) { outObject = outputMapper.convertToMappedInputEvent(siddhiEvent); } else { outObject = outputMapper.convertToTypedInputEvent(siddhiEvent); } } catch (EventPublisherConfigurationException e) { log.error("Cannot send " + event + " from " + eventPublisherConfiguration.getEventPublisherName(), e); return; } if (traceEnabled) { trace.info(afterTracerPrefix + outObject); } if (dynamicMessagePropertyEnabled) { changeDynamicEventAdapterMessageProperties(siddhiEvent.getData(), dynamicProperties, siddhiEvent.getArbitraryDataMap()); } OutputEventAdapterService eventAdapterService = EventPublisherServiceValueHolder.getOutputEventAdapterService(); eventAdapterService.publish(eventPublisherConfiguration.getEventPublisherName(), dynamicProperties, outObject); }</code><technical_language>Remove this</technical_language>

Target:
public void process(Event event) { Map<String, String> dynamicProperties = new HashMap<String, String>(eventPublisherConfiguration.getToAdapterDynamicProperties()); Object outObject; if (traceEnabled) { trace.info(beforeTracerPrefix + event); } if (statisticsEnabled) { eventCounter.inc(); } if (!processingEnabled) { return; } org.wso2.siddhi.core.event.Event siddhiEvent = EventPublisherUtil.convertToSiddhiEvent(event, inputStreamSize); try { if (customMappingEnabled) { outObject = outputMapper.convertToMappedInputEvent(siddhiEvent); } else { outObject = outputMapper.convertToTypedInputEvent(siddhiEvent); } } catch (EventPublisherConfigurationException e) { log.error("Cannot send " + event + " from " + eventPublisherConfiguration.getEventPublisherName(), e); return; } if (traceEnabled) { trace.info(afterTracerPrefix + outObject); } if (dynamicMessagePropertyEnabled) { changeDynamicEventAdapterMessageProperties(siddhiEvent.getData(), dynamicProperties, siddhiEvent.getArbitraryDataMap()); } OutputEventAdapterService eventAdapterService = EventPublisherServiceValueHolder.getOutputEventAdapterService(); eventAdapterService.publish(eventPublisherConfiguration.getEventPublisherName(), dynamicProperties, outObject); }
Source:
<code>private ContainerConfig buildContainerConfig() { List<String> ports = params.getPorts().stream() .map(Objects::toString).collect(Collectors.toList()); Map<String, List<PortBinding>> portBindings = new HashMap<>(); for (String port : ports) { List<PortBinding> hostPorts = new ArrayList<>(); hostPorts.add(PortBinding.of(ALL_NETWORK_INTERFACES, port)); portBindings.put(port, hostPorts); } HostConfig.Bind configurationFile = HostConfig.Bind.builder() .from("/home/nsx/prometheus.yml") .to("/etc/prometheus/prometheus.yml").build(); HostConfig hostConfig = HostConfig.builder() .privileged(true) <START> .binds(configurationFile) <END> .portBindings(portBindings) .build(); ContainerConfig.Builder builder = ContainerConfig.builder(); builder.hostConfig(hostConfig) .exposedPorts(ports.stream().toArray(String[]::new)) .image(imageName.get(getParams().getNodeType())); if (cmd.containsKey(getParams().getNodeType())) { builder.cmd(cmd.get(getParams().getNodeType())); } return builder.build(); }</code><technical_language>nsx dir name</technical_language>

Target:
private ContainerConfig buildContainerConfig() { List<String> ports = params.getPorts().stream() .map(Objects::toString).collect(Collectors.toList()); Map<String, List<PortBinding>> portBindings = new HashMap<>(); for (String port : ports) { List<PortBinding> hostPorts = new ArrayList<>(); hostPorts.add(PortBinding.of(ALL_NETWORK_INTERFACES, port)); portBindings.put(port, hostPorts); } HostConfig.Bind configurationFile = HostConfig.Bind.builder() .from("/home/nsx/prometheus.yml") .to("/etc/prometheus/prometheus.yml").build(); HostConfig hostConfig = HostConfig.builder() .privileged(true) .binds(configurationFile) .portBindings(portBindings) .build(); ContainerConfig.Builder builder = ContainerConfig.builder(); builder.hostConfig(hostConfig) .exposedPorts(ports.stream().toArray(String[]::new)) .image(IMAGE_NAME.get(getParams().getNodeType())); if (CMD.containsKey(getParams().getNodeType())) { builder.cmd(CMD.get(getParams().getNodeType())); } return builder.build(); }
Source:
<code>public final Sensor threadLevelSensor(final String threadId, final String sensorName, final RecordingLevel recordingLevel, final Sensor... parents) { final String key = threadSensorPrefix(threadId); synchronized (threadLevelSensors) { final String fullSensorName = key + SENSOR_NAME_DELIMITER + sensorName; <START> return Optional.ofNullable(metrics.getSensor(fullSensorName)) .orElseGet(() -> { threadLevelSensors.putIfAbsent(key, new LinkedList<>()); threadLevelSensors.get(key).push(fullSensorName); return metrics.sensor(fullSensorName, recordingLevel, parents); <END> }); } }</code><technical_language>Although, simplified this code, apply simplifications I proposed in PR #7914. I simplify this code shown here: return Optional.ofNullable(metrics.getSensor(fullSensorName)).orElseGet(() -> { threadLevelSensors.computeIfAbsent(key, -> new LinkedList<>()).push(fullSensorName); return metrics.sensor(fullSensorName, recordingLevel, parents); }); This simplification applied other methods below. If concerns this simplifications please share thoughts</technical_language>

Target:
public final Sensor threadLevelSensor(final String threadId, final String sensorName, final RecordingLevel recordingLevel, final Sensor... parents) { final String key = threadSensorPrefix(threadId); synchronized (threadLevelSensors) { final String fullSensorName = key + SENSOR_NAME_DELIMITER + sensorName; return Optional.ofNullable(metrics.getSensor(fullSensorName)) .orElseGet(() -> { threadLevelSensors.computeIfAbsent(key, ignored -> new LinkedList<>()).push(fullSensorName); return metrics.sensor(fullSensorName, recordingLevel, parents); }); } }
Source:
<code>public V replace(final K key, final V value) throws CacheLoaderException, CacheWriterException { putObserver.begin(); <START> getObserver.begin(); <END> statusTransitioner.checkAvailable(); checkNonNull(key, value); final AtomicReference<V> old = new AtomicReference<V>(); final BiFunction<K, V, V> remappingFunction = memoize(new BiFunction<K, V, V>() { @Override public V apply(final K k, final V inCache) { if (cacheWriter != null) { try { cacheWriter.write(key, value); } catch (Exception e) { throw newCacheWriterException(e); } } old.set(inCache); return value; } }); try { store.computeIfPresent(key, remappingFunction); } catch (CacheAccessException e) { putObserver.end(PutOutcome.FAILURE); getObserver.end(GetOutcome.FAILURE); try { remappingFunction.apply(key, null); } finally { removeKeysWithStrategy(Collections.singleton(key), e); } } catch (CacheWriterException e) { putObserver.end(PutOutcome.FAILURE); getObserver.end(GetOutcome.FAILURE); removeKeysWithStrategy(Collections.singleton(key), e); throw e; } if (old.get() != null) { getObserver.end(GetOutcome.HIT_NO_LOADER); putObserver.end(PutOutcome.ADDED); } else { getObserver.end(GetOutcome.MISS_NO_LOADER); } return old.get(); }</code><technical_language>issue putIfAbsent. is a disconnect track statistics 107 requires represented</technical_language>

Target:
public V replace(final K key, final V value) throws CacheLoaderException, CacheWriterException { replaceObserver.begin(); statusTransitioner.checkAvailable(); checkNonNull(key, value); final AtomicReference<V> old = new AtomicReference<V>(); final BiFunction<K, V, V> remappingFunction = memoize(new BiFunction<K, V, V>() { @Override public V apply(final K k, final V inCache) { if (cacheWriter != null) { try { cacheWriter.write(key, value); } catch (Exception e) { throw newCacheWriterException(e); } } old.set(inCache); return value; } }); try { store.computeIfPresent(key, remappingFunction); } catch (CacheAccessException e) { replaceObserver.end(ReplaceOutcome.FAILURE); try { remappingFunction.apply(key, null); } finally { removeKeysWithStrategy(Collections.singleton(key), e); } } catch (CacheWriterException e) { replaceObserver.end(ReplaceOutcome.FAILURE); removeKeysWithStrategy(Collections.singleton(key), e); throw e; } if (old.get() != null) { replaceObserver.end(ReplaceOutcome.HIT); } else { replaceObserver.end(ReplaceOutcome.MISS); } return old.get(); }
Source:
<code>private String tryAppendTrailingDocumentation(String documentation) { while (pos < data.length) { char c = data[pos]; if (c == ' ' || c == '\t') { pos++; } else if (c == '/') { pos++; break; } else { return documentation; } } if (pos == data.length || (data[pos] != '/' && data[pos] != '*')) { pos--; throw unexpected("expected ' END> } if (data[pos] == '*' && pos < data.length - 1 && data[pos + 1] == '/') { end = pos - 1; pos += 2; break; } pos++; } } else { while (true) { if (pos == data.length) { end = pos - 1; break; } char c = data[pos++]; if (c == '\n') { newline(); end = pos - 2; break; } } } while (end > start && (data[end] == ' ' || data[end] == '\t')) { end--; } if (end == start) { return documentation; } String trailingDocumentation = new String(data, start, end - start + 1); if (documentation.isEmpty()) { return trailingDocumentation; } return documentation + '\n' + trailingDocumentation; }</code><technical_language>oooh interesting, syntax is a more strict protoc. Works for me</technical_language>

Target:
private String tryAppendTrailingDocumentation(String documentation) { while (pos < data.length) { char c = data[pos]; if (c == ' ' || c == '\t') { pos++; } else if (c == '/') { pos++; break; } else { return documentation; } } if (pos == data.length || (data[pos] != '/' && data[pos] != '*')) { pos--; throw unexpected("expected ' } boolean isStar = data[pos] == '*'; pos++; if (pos < data.length && data[pos] == ' ') { pos++; } int start = pos; int end; if (isStar) { while (true) { if (pos == data.length || data[pos] == '\n') { throw unexpected("trailing comment must be closed on the same line"); } if (data[pos] == '*' && pos + 1 < data.length && data[pos + 1] == '/') { end = pos - 1; pos += 2; break; } pos++; } while (pos < data.length) { char c = data[pos++]; if (c == '\n') { newline(); break; } if (c != ' ' && c != '\t') { throw unexpected("no syntax may follow trailing comment"); } } } else { while (true) { if (pos == data.length) { end = pos - 1; break; } char c = data[pos++]; if (c == '\n') { newline(); end = pos - 2; break; } } } while (end > start && (data[end] == ' ' || data[end] == '\t')) { end--; } if (end == start) { return documentation; } String trailingDocumentation = new String(data, start, end - start + 1); if (documentation.isEmpty()) { return trailingDocumentation; } return documentation + '\n' + trailingDocumentation; }
Source:
<code>public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!MATCHER.matches(tree, state)) { return NO_MATCH; } List<? extends ExpressionTree> arguments = tree.getArguments(); return describeMatch( <START> tree, SuggestedFix.builder().postfixWith(arguments.get(0), ", -1").build()); <END> }</code><technical_language>consider Iterables.getOnlyElement instead of get(0) assumption number of arguments explicit</technical_language>

Target:
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!MATCHER.matches(tree, state)) { return NO_MATCH; } List<? extends ExpressionTree> arguments = tree.getArguments(); return describeMatch( tree, SuggestedFix.builder().postfixWith(getOnlyElement(arguments), ", -1").build()); }
Source:
<code>public ReflectionMappers setColumnNameMatchers(List<ColumnNameMatcher> columnNameMatchers) { synchronized (lock) { this.columnNameMatchers.clear(); this.columnNameMatchers.addAll(columnNameMatchers); <START> } <END> return this; }</code><technical_language>expected benefit for this change? This method is typically called VM--let's prioritize simplicity for low-traffic methods this</technical_language>

Target:
public ReflectionMappers setColumnNameMatchers(List<ColumnNameMatcher> columnNameMatchers) { this.columnNameMatchers = new ArrayList<>(columnNameMatchers); return this; }
Source:
<code>private void validateNewFolderName() { String name = fFolderName.getText(); IWorkspace workspace = fParentFolder.getWorkspace(); IStatus nameStatus = workspace.validateName(name, IResource.FOLDER); if ("".equals(name)) { updateStatus(new Status(IStatus.ERROR, Activator.PLUGIN_ID, IStatus.ERROR, Messages.Dialog_EmptyNameError, null)); return; } if (!nameStatus.isOK()) { updateStatus(nameStatus); return; } IPath path = new Path(name); <START> if (fParentFolder.getFolder(path).exists() || fParentFolder.getFile(path).exists()) { <END> updateStatus(new Status(IStatus.ERROR, Activator.PLUGIN_ID, IStatus.ERROR, Messages.Dialog_ExistingNameError, null)); return; } updateStatus(new Status(IStatus.OK, Activator.PLUGIN_ID, "")); }</code><technical_language>findMember folder file checked time</technical_language>

Target:
private void validateNewFolderName() { String name = fFolderName.getText(); IWorkspace workspace = fParentFolder.getWorkspace(); IStatus nameStatus = workspace.validateName(name, IResource.FOLDER); if ("".equals(name)) { updateStatus(new Status(IStatus.ERROR, Activator.PLUGIN_ID, IStatus.ERROR, Messages.Dialog_EmptyNameError, null)); return; } if (!nameStatus.isOK()) { updateStatus(nameStatus); return; } if (fParentFolder.findMember(name) != null) { updateStatus(new Status(IStatus.ERROR, Activator.PLUGIN_ID, IStatus.ERROR, Messages.Dialog_ExistingNameError, null)); return; } updateStatus(new Status(IStatus.OK, Activator.PLUGIN_ID, "")); }
Source:
<code>protected void prepareOnAffectedNodes(TxInvocationContext<?> ctx, PrepareCommand command, Collection<Address> recipients, boolean sync) { try { RpcOptions rpcOptions; if (sync) { rpcOptions = rpcManager.getRpcOptionsBuilder(ResponseMode.SYNCHRONOUS_IGNORE_LEAVERS, DeliverOrder.NONE).build(); } else { <START> rpcOptions = rpcManager.getDefaultRpcOptions(sync); <END> } Map<Address, Response> responseMap = rpcManager.invokeRemotely(recipients, command, rpcOptions); checkTxCommandResponses(responseMap, command); } finally { transactionRemotelyPrepared(ctx); } }</code><technical_language>replace sync false</technical_language>

Target:
protected void prepareOnAffectedNodes(TxInvocationContext<?> ctx, PrepareCommand command, Collection<Address> recipients, boolean sync) { try { RpcOptions rpcOptions; if (sync) { rpcOptions = rpcManager.getRpcOptionsBuilder(ResponseMode.SYNCHRONOUS_IGNORE_LEAVERS, DeliverOrder.NONE).build(); } else { rpcOptions = rpcManager.getDefaultRpcOptions(false); } Map<Address, Response> responseMap = rpcManager.invokeRemotely(recipients, command, rpcOptions); checkTxCommandResponses(responseMap, command); } finally { transactionRemotelyPrepared(ctx); } }
Source:
<code>public Context getSharedSpanBuilder(String spanName, Context context) { return Context.NONE; <START> } <END></code><technical_language>throw UnsupportedOperationException return work</technical_language>

Target:
public Context getSharedSpanBuilder(String spanName, Context context) { throw logger.logExceptionAsError( new UnsupportedOperationException("This operation is not supported in OpenCensus")); }
Source:
<code>public void validate() { super.validate(); String algorithmName = getAlgorithm(); if (algorithmName != null) { if (!PERCEPTRON_VALUE.equals(algorithmName)) { <START> throw new IllegalArgumentException("trainParams are not valid!"); <END> } } }</code><technical_language>"algorithmName PERCEPTRON"</technical_language>

Target:
public void validate() { super.validate(); String algorithmName = getAlgorithm(); if (algorithmName != null) { if (!PERCEPTRON_VALUE.equals(algorithmName)) { throw new IllegalArgumentException("algorithmName must be PERCEPTRON"); } } }
Source:
<code>private void assertSTGeometries(String wkt, String... expected) { ImmutableList<String> expectedList; if (expected == null) { expectedList = null; } else { expectedList = ImmutableList.copyOf(expected); } <START> assertFunction("transform(ST_Geometries(ST_GeometryFromText('" + wkt + "')), x -> ST_ASText(x))", new ArrayType(VARCHAR), expectedList); <END> }</code><technical_language>String.format for readability format("transform(ST_Geometries(ST_GeometryFromText('%s')), x -> ST_ASText(x))", wkt)</technical_language>

Target:
private void assertSTGeometries(String wkt, String... expected) { assertFunction(String.format("transform(ST_Geometries(ST_GeometryFromText('%s')), x -> ST_ASText(x))", wkt), new ArrayType(VARCHAR), ImmutableList.copyOf(expected)); }
Source:
<code>XmrTxProofRequest(Socks5ProxyProvider socks5ProxyProvider, XmrTxProofModel model) { this.parser = new XmrTxProofParser(); this.model = model; httpClient = new XmrTxProofHttpClient(socks5ProxyProvider); if (model.getServiceAddress().regionMatches(0, "http:", 0, 5)) { httpClient.setBaseUrl(model.getServiceAddress()); httpClient.setIgnoreSocks5Proxy(true); <START> } if (model.getServiceAddress().regionMatches(0, "https:", 0, 6)) { <END> httpClient.setBaseUrl(model.getServiceAddress()); httpClient.setIgnoreSocks5Proxy(false); } else { httpClient.setBaseUrl("http://" + model.getServiceAddress()); httpClient.setIgnoreSocks5Proxy(false); } terminated = false; firstRequest = System.currentTimeMillis(); }</code><technical_language>else if</technical_language>

Target:
XmrTxProofRequest(Socks5ProxyProvider socks5ProxyProvider, XmrTxProofModel model) { this.parser = new XmrTxProofParser(); this.model = model; httpClient = new XmrTxProofHttpClient(socks5ProxyProvider); if (model.getServiceAddress().regionMatches(0, "http:", 0, 5)) { httpClient.setBaseUrl(model.getServiceAddress()); httpClient.setIgnoreSocks5Proxy(true); } else if (model.getServiceAddress().regionMatches(0, "https:", 0, 6)) { httpClient.setBaseUrl(model.getServiceAddress()); httpClient.setIgnoreSocks5Proxy(false); } else { httpClient.setBaseUrl("http://" + model.getServiceAddress()); httpClient.setIgnoreSocks5Proxy(false); } terminated = false; firstRequest = System.currentTimeMillis(); }
Source:
<code>private static Class<? extends ICategoryFilter> getCategoryFilterClass(IConfigurationElement element) { try { <START> return (Class<? extends ICategoryFilter>)element.createExecutableExtension("category-filter-class").getClass(); END> } catch(CoreException e) { WebUiPlugin.getDefault().logError(e); return null; } }</code><technical_language>If category filter implement ICategoryFilter get ClassCastException here. check casting</technical_language>

Target:
private static Class<? extends ICategoryFilter> getCategoryFilterClass(IConfigurationElement element) { if(element.getAttribute("category-filter-class") != null){ try { Object o = element.createExecutableExtension("category-filter-class"); if(o instanceof ICategoryFilter) { return (Class<? extends ICategoryFilter>)o.getClass(); } else { WebUiPlugin.getDefault().logError("Category Filter " + element.getAttribute("category-filter-class") + " should implement ICategoryFilter."); } } catch(CoreException e) { WebUiPlugin.getDefault().logError(e); } } return null; }
Source:
<code>public EnumActionResult onItemUse(EntityPlayer player, World worldIn, BlockPos pos, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { pos = pos.offset(facing); ItemStack itemstack = player.getHeldItem(hand); Binding binding = getBinding(player.getHeldItem(hand)); <START> if (binding != null) { <END> if (!player.canPlayerEdit(pos, facing, itemstack)) return EnumActionResult.FAIL; if (worldIn.isAirBlock(pos) && NetworkHelper.getSoulNetwork(binding).syphonAndDamage(player, SoulTicket.item(player.getHeldItem(hand), 100)).isSuccess()) { worldIn.playSound(player, pos, SoundEvents.ITEM_FIRECHARGE_USE, SoundCategory.BLOCKS, 1.0F, itemRand.nextFloat() * 0.4F + 0.8F); worldIn.setBlockState(pos, Blocks.FIRE.getDefaultState(), 11); } else return EnumActionResult.FAIL; if (player instanceof EntityPlayerMP) CriteriaTriggers.PLACED_BLOCK.trigger((EntityPlayerMP) player, pos, itemstack); return EnumActionResult.SUCCESS; } else return EnumActionResult.FAIL; }</code><technical_language>early escape nesting</technical_language>

Target:
public EnumActionResult onItemUse(EntityPlayer player, World worldIn, BlockPos pos, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { pos = pos.offset(facing); ItemStack itemstack = player.getHeldItem(hand); Binding binding = getBinding(player.getHeldItem(hand)); if (binding == null) return EnumActionResult.FAIL; if (!player.canPlayerEdit(pos, facing, itemstack)) return EnumActionResult.FAIL; if (worldIn.isAirBlock(pos) && NetworkHelper.getSoulNetwork(binding).syphonAndDamage(player, SoulTicket.item(player.getHeldItem(hand), 100)).isSuccess()) { worldIn.playSound(player, pos, SoundEvents.ITEM_FIRECHARGE_USE, SoundCategory.BLOCKS, 1.0F, itemRand.nextFloat() * 0.4F + 0.8F); worldIn.setBlockState(pos, Blocks.FIRE.getDefaultState(), 11); } else return EnumActionResult.FAIL; if (player instanceof EntityPlayerMP) CriteriaTriggers.PLACED_BLOCK.trigger((EntityPlayerMP) player, pos, itemstack); return EnumActionResult.SUCCESS; }
Source:
<code>public void update(SolGame game) { addRemove(game); float ts = game.getTimeStep(); myWorld.step(ts, 6, 2); SolCam cam = game.getCam(); Vector2 camPos = cam.getPos(); myFarEndDist = 1.5f * cam.getViewDist(); myFarBeginDist = 1.33f * myFarEndDist; boolean recalcRad = false; if (myRadiusRecalcAwait > 0) { myRadiusRecalcAwait -= ts; } else { myRadiusRecalcAwait = MAX_RADIUS_RECALC_AWAIT; recalcRad = true; } for (SolObject o : myObjs) { o.update(game); SolMath.checkVectorsTaken(o); List<Drawable> drawables = o.getDrawables(); for (Drawable drawable : drawables) { drawable.update(game, o); } if (o.shouldBeRemoved(game)) { removeObjDelayed(o); continue; } if (isFar(o, camPos)) { <START> if (o != game.getHero().getHero()) { <END> FarObj fo = o.toFarObj(); if (fo != null) { addFarObjNow(fo); } removeObjDelayed(o); continue; } } if (recalcRad) { recalcRadius(o); } } for (Iterator<FarObjData> it = myFarObjs.iterator(); it.hasNext(); ) { FarObjData fod = it.next(); FarObj fo = fod.fo; fo.update(game); SolMath.checkVectorsTaken(fo); if (fo.shouldBeRemoved(game)) { removeFo(it, fo); continue; } if (isNear(fod, camPos, ts)) { SolObject o = fo.toObj(game); if (o instanceof StarPort) { addObjNow(game, o); } else { addObjDelayed(o); } removeFo(it, fo); } } addRemove(game); }</code><technical_language>Rename o please</technical_language>

Target:
public void update(SolGame game) { addRemove(game); float ts = game.getTimeStep(); myWorld.step(ts, 6, 2); SolCam cam = game.getCam(); Vector2 camPos = cam.getPos(); myFarEndDist = 1.5f * cam.getViewDist(); myFarBeginDist = 1.33f * myFarEndDist; boolean recalcRad = false; if (myRadiusRecalcAwait > 0) { myRadiusRecalcAwait -= ts; } else { myRadiusRecalcAwait = MAX_RADIUS_RECALC_AWAIT; recalcRad = true; } for (SolObject o : myObjs) { o.update(game); SolMath.checkVectorsTaken(o); List<Drawable> drawables = o.getDrawables(); for (Drawable drawable : drawables) { drawable.update(game, o); } if (o.shouldBeRemoved(game)) { removeObjDelayed(o); if (game.getHero().isAlive() && game.getHero().isNonTranscendent() && o == game.getHero().getHero()) { game.getHero().die(); } continue; } if (isFar(o, camPos)) { if (game.getHero().isAlive() && game.getHero().isNonTranscendent() && o != game.getHero().getHero()) { FarObj fo = o.toFarObj(); if (fo != null) { addFarObjNow(fo); } removeObjDelayed(o); continue; } } if (recalcRad) { recalcRadius(o); } } for (Iterator<FarObjData> it = myFarObjs.iterator(); it.hasNext(); ) { FarObjData fod = it.next(); FarObj fo = fod.fo; fo.update(game); SolMath.checkVectorsTaken(fo); if (fo.shouldBeRemoved(game)) { removeFo(it, fo); continue; } if (isNear(fod, camPos, ts)) { SolObject o = fo.toObj(game); if (o instanceof StarPort) { addObjNow(game, o); } else { addObjDelayed(o); } removeFo(it, fo); } } addRemove(game); }
Source:
<code>public void run() { <START> getWrappedRunnable().run(); <END> if (!sd.isDisposed()) { long nextTick; long nowNanoseconds = now(TimeUnit.NANOSECONDS); if (nowNanoseconds + CLOCK_DRIFT_TOLERANCE_NANOSECONDS < lastNowNanoseconds || nowNanoseconds >= lastNowNanoseconds + periodInNanoseconds + CLOCK_DRIFT_TOLERANCE_NANOSECONDS) { nextTick = nowNanoseconds + periodInNanoseconds; startInNanoseconds = nextTick - (periodInNanoseconds * (++count)); } else { nextTick = startInNanoseconds + (++count * periodInNanoseconds); } lastNowNanoseconds = nowNanoseconds; long delay = nextTick - nowNanoseconds; sd.replace(schedule(this, delay, TimeUnit.NANOSECONDS)); } }</code><technical_language>Please turn method calls</technical_language>

Target:
public void run() { decoratedRun.run(); if (!sd.isDisposed()) { long nextTick; long nowNanoseconds = now(TimeUnit.NANOSECONDS); if (nowNanoseconds + CLOCK_DRIFT_TOLERANCE_NANOSECONDS < lastNowNanoseconds || nowNanoseconds >= lastNowNanoseconds + periodInNanoseconds + CLOCK_DRIFT_TOLERANCE_NANOSECONDS) { nextTick = nowNanoseconds + periodInNanoseconds; startInNanoseconds = nextTick - (periodInNanoseconds * (++count)); } else { nextTick = startInNanoseconds + (++count * periodInNanoseconds); } lastNowNanoseconds = nowNanoseconds; long delay = nextTick - nowNanoseconds; sd.replace(schedule(this, delay, TimeUnit.NANOSECONDS)); } }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); setTheme(UIUtils.getThemeResourceId( prefs.getString(Settings.KEY_PREF_THEME, Settings.DEFAULT_PREF_THEME))); super.onCreate(savedInstanceState); hostManager = HostManager.getInstance(this); if (hostManager.getHostInfo() == null && !(this instanceof AddHostActivity)) { final Intent intent = new Intent(this, AddHostActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); finish(); <START> } <END> }</code><technical_language>This useful, it? ran a situation this happened you? If describe it</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); setTheme(UIUtils.getThemeResourceId( prefs.getString(Settings.KEY_PREF_THEME, Settings.DEFAULT_PREF_THEME))); super.onCreate(savedInstanceState); }
Source:
<code>public StreamsAddressRequest() { this.reqType = ALL_STREAMS; <START> this.streamsRanges = Collections.EMPTY_LIST; <END> beforeCompactionMark = false; }</code><technical_language>Collections.emptyList() prevent generating warnings</technical_language>

Target:
public StreamsAddressRequest() { this.reqType = ALL_STREAMS; this.streamsRanges = Collections.emptyList(); forSequencerTrim = false; }
Source:
<code>public void optimizeStatement() throws StandardException { SubqueryFlattening.flatten(this); resultSet = resultSet.preprocess(getCompilerContext().getNumTables(), null, null); accept(new ConstantExpressionVisitor()); <START> <END> GenericLanguageConnectionContext lcc = (GenericLanguageConnectionContext) ContextService.getContext(LanguageConnectionContext.CONTEXT_ID); if (lcc == null || !lcc.getUnSatTreePruningOff()) accept(new TreePruningVisitor()); resultSet = resultSet.optimize(getDataDictionary(), null, 1.0d); resultSet = resultSet.modifyAccessPaths(); }</code><technical_language>lcc null</technical_language>

Target:
public void optimizeStatement() throws StandardException { SubqueryFlattening.flatten(this); resultSet = resultSet.preprocess(getCompilerContext().getNumTables(), null, null); accept(new ConstantExpressionVisitor()); accept(new TreePruningVisitor()); resultSet = resultSet.optimize(getDataDictionary(), null, 1.0d); resultSet = resultSet.modifyAccessPaths(); }
Source:
<code>public void testBitwiseSrl() { assertFunction("bitwise_shift_right_logical(7, 2, 4)", BIGINT, 1L); assertFunction("bitwise_shift_right_logical(7, 2, 64)", BIGINT, 7L >>> 2L); assertFunction("bitwise_shift_right_logical(-4, 6, 64)", BIGINT, -4L >>> 6L); assertFunction("bitwise_shift_right_logical(-8, 2, 5)", BIGINT, 6L); <START> assertFunction("bitwise_shift_right_logical(-1152905011916701696, 62, 64)", BIGINT, 3L); <END> assertFunction("bitwise_shift_right_logical(-1152905011916701696, 62, 4)", BIGINT, 0L); assertFunction("bitwise_shift_right_logical(-1152905011916701696, 1, 4)", BIGINT, 0L); assertInvalidFunction("bitwise_shift_right_logical(7, -3, 2)", INVALID_FUNCTION_ARGUMENT); }</code><technical_language>suggestion assertFunction("bitwise_shift_right_logical(0xF0000F0000F00000L, 62, 64)", BIGINT, 3L);</technical_language>

Target:
public void testBitwiseSrl() { assertFunction("bitwise_logical_shift_right(7, 2, 4)", BIGINT, 1L); assertFunction("bitwise_logical_shift_right(7, 2, 64)", BIGINT, 7L >>> 2L); assertFunction("bitwise_logical_shift_right(-4, 6, 64)", BIGINT, -4L >>> 6L); assertFunction("bitwise_logical_shift_right(-8, 2, 5)", BIGINT, 6L); assertFunction(format("bitwise_logical_shift_right(%s, 62, 64)", 0xF0000F0000F00000L), BIGINT, 3L); assertFunction(format("bitwise_logical_shift_right(%s, 62, 4)", 0xF0000F0000F00000L), BIGINT, 0L); assertFunction(format("bitwise_logical_shift_right(%s, 1, 4)", 0xF0000F0000F00000L), BIGINT, 0L); assertInvalidFunction("bitwise_logical_shift_right(7, -3, 2)", INVALID_FUNCTION_ARGUMENT); }
Source:
<code>public Map<String, PartitionStatistics> getPartitionStatistics(String databaseName, String tableName, Set<String> partitionNames) { return Collections.unmodifiableMap( <START> partitionNames.stream().collect(Collectors.toMap(identity(), (p) -> PartitionStatistics.empty()))); <END> }</code><technical_language>nit: put previous line</technical_language>

Target:
public Map<String, PartitionStatistics> getPartitionStatistics(String databaseName, String tableName, Set<String> partitionNames) { return partitionNames.stream().collect(toImmutableMap(identity(), (p) -> PartitionStatistics.empty())); }
Source:
<code>public void ovfUpdate_timer() { ITEMS_COUNT_PER_UPDATE = reloadConfigValue(); log.info("OvfDataUpdater: Attempting to update VMs/Templates Ovf."); List<storage_pool> storagePools = getStoragePoolDao().getAllByStatus(StoragePoolStatus.Up); for (storage_pool pool : storagePools) { try { initProccessedInfoLists(); log.infoFormat("OvfDataUpdater: Attempting to update VM OVFs in Data Center {0}", <START> pool.getname()); <END> updateOvfForVmsOfStoragePool(pool.getId()); log.infoFormat("OvfDataUpdater: Attempting to update template OVFs in Data Center {0}", pool.getname()); updateOvfForTemplatesOfStoragePool(pool.getId()); log.infoFormat("OvfDataUpdater: Attempting to remove uneeded template/vm OVFs in Data Center {0}", pool.getname()); removeOvfForTemplatesAndVmsOfStoragePool(pool.getId()); } catch (Exception ex) { addAuditLogError(pool.getname()); log.errorFormat("Exception while trying to update VMs/Templates ovf in Data Center {0}, the exception is {1}", pool.getname(), ex.getMessage()); log.debug(ex.getStackTrace()); } } proccessedIdsInfo = null; proccessedOvfGenerationsInfo = null; }</code><technical_language>move log a line</technical_language>

Target:
public void ovfUpdate_timer() { itemsCountPerUpdate = reloadConfigValue(); log.info("OvfDataUpdater: Attempting to update VMs/Templates Ovf."); List<storage_pool> storagePools = getStoragePoolDao().getAllByStatus(StoragePoolStatus.Up); for (storage_pool pool : storagePools) { try { log.infoFormat("OvfDataUpdater: Attempting to update VM OVFs in Data Center {0}", pool.getname()); initProccessedInfoLists(); updateOvfForVmsOfStoragePool(pool.getId()); log.infoFormat("OvfDataUpdater: Attempting to update template OVFs in Data Center {0}", pool.getname()); updateOvfForTemplatesOfStoragePool(pool.getId()); log.infoFormat("OvfDataUpdater: Attempting to remove uneeded template/vm OVFs in Data Center {0}", pool.getname()); removeOvfForTemplatesAndVmsOfStoragePool(pool.getId()); } catch (Exception ex) { addAuditLogError(pool.getname()); log.errorFormat("Exception while trying to update VMs/Templates ovf in Data Center {0}, the exception is {1}", pool.getname(), ex.getMessage()); log.debug(ex.getStackTrace()); } } proccessedIdsInfo = null; proccessedOvfGenerationsInfo = null; }
Source:
<code><START> public boolean shouldAlertUpgrade(ArrayList<RpmVersion> isos, String hostOs) <END> { boolean alert = false; Version hostVersion = new Version(hostOs[1].trim()); String release_host = hostOs[2].trim(); for (RpmVersion iso : isos) { if (hostVersion.getMajor() == iso.getMajor()) { if (iso.getMinor() > hostVersion.getMinor() || iso.getBuild() > hostVersion.getBuild()) { alert = true; break; } String rpmFromIso = iso.getRpmName(); int isoIndex = iso.getRpmName().indexOf(".iso"); if (isoIndex != -1) { rpmFromIso = iso.getRpmName().substring(0, isoIndex); } String rpmRelease = RpmVersionUtils.splitRpmToParts(rpmFromIso)[2]; if (RpmVersionUtils.compareRpmPart(rpmRelease, release_host) > 0) { alert = true; break; } } } return alert; }</code><technical_language>I totally agree</technical_language>

Target:
protected static boolean shouldAlertUpgrade(ArrayList<RpmVersion> isos, String[] hostOs) { boolean alert = false; Version hostVersion = new Version(hostOs[1].trim()); String release_host = hostOs[2].trim(); for (RpmVersion iso : isos) { if (hostVersion.getMajor() == iso.getMajor()) { if (iso.getMinor() > hostVersion.getMinor() || iso.getBuild() > hostVersion.getBuild()) { alert = true; break; } String rpmFromIso = iso.getRpmName(); int isoIndex = iso.getRpmName().indexOf(".iso"); if (isoIndex != -1) { rpmFromIso = iso.getRpmName().substring(0, isoIndex); } if (RpmVersionUtils.compareRpmPart(RpmVersionUtils.splitRpmToParts(rpmFromIso)[2], release_host) > 0) { alert = true; break; } } } return alert; }
Source:
<code>private void toggleTwitterPreference() { if (!isAdded()) return; View view = getView(); if (view != null) { <START> View twitterCard = getView().findViewById(R.id.card_view_twitter); <END> for (int i = 0; i < mPublicizeButtons.size(); i++) { PublicizeButton publicizeButton = mPublicizeButtons.get(i); if (publicizeButton.getId().equals(TWITTER_ID) && publicizeButton.isEnabled()) { twitterCard.setVisibility(View.VISIBLE); return; } } twitterCard.setVisibility(View.GONE); } }</code><technical_language>view instead of getView()</technical_language>

Target:
private void toggleTwitterPreference() { if (!isAdded()) return; View view = getView(); if (view != null) { View twitterCard = view.findViewById(R.id.card_view_twitter); for (int i = 0; i < mPublicizeButtons.size(); i++) { PublicizeButton publicizeButton = mPublicizeButtons.get(i); if (publicizeButton.getId().equals(TWITTER_ID) && publicizeButton.isEnabled()) { twitterCard.setVisibility(View.VISIBLE); return; } } twitterCard.setVisibility(View.GONE); } }
Source:
<code>synchronized private Long updateAllowance(String key) { String derivedKey = getKeyForWindow(key); <START> StatefulRedisConnection<String, String> connection = redisClient.connect(); <END> Long count = connection.sync().incr(derivedKey); if (count == 1) { connection.sync().expire(derivedKey, perMillis / 1000); } return count; }</code><technical_language>Do need close this connection lettuce takes care of ? Java docs connect() opens new connection Redis <LINK_0> Jedis, get connection pool. Is this useful</technical_language>

Target:
synchronized private Long updateAllowance(String key) { String derivedKey = getKeyForWindow(key); Long count = redisClientManager.getRedisConnection().sync().incr(derivedKey); if (count == 1) { redisClientManager.getRedisConnection().sync().expire(derivedKey, perMillis / 1000); } return count; }
Source:
<code>protected <KIn> Set<KIn> filterLocalPrimaryOwner(Set<KIn> nodeLocalKeys, DistributionManager dm) { Set<KIn> selectedKeys = new HashSet<KIn>(); for (KIn key : nodeLocalKeys) { <START> Address primaryLocation = dm != null ? dm.getPrimaryLocation(key) : localAddress; <END> if (primaryLocation != null && primaryLocation.equals(localAddress)) { selectedKeys.add(key); } } return selectedKeys; }</code><technical_language>StateTransferManager ClusteringDependentLogic here, ClusteringDependentLogic.InvalidationLogic.getPrimaryOwner()</technical_language>

Target:
protected <KIn> Set<KIn> filterLocalPrimaryOwner(Set<KIn> nodeLocalKeys, DistributionManager dm) { Set<KIn> selectedKeys = new HashSet<KIn>(); for (KIn key : nodeLocalKeys) { Address primaryLocation = dm != null ? dm.getPrimaryLocation(key) : cdl.getAddress(); if (primaryLocation != null && primaryLocation.equals(cdl.getAddress())) { selectedKeys.add(key); } } return selectedKeys; }
Source:
<code><START> public void setAdvancedRecentChangesCheckbox() { <END> selectTab(PreferencesPageObject.tabNames.UNDER); waitForElementClickableByElement(useAdvancedRecentChangesCheckbox); useAdvancedRecentChangesCheckbox.click(); PageObjectLogging.log("Use_advanced_recent_changes_checkbox", "Use_advanced_recent_changes_checkbox clicked", true); }</code><technical_language>fluent chaining nice</technical_language>

Target:
public PreferencesPageObject setAdvancedRecentChangesCheckbox() { selectTab(PreferencesPageObject.tabNames.UNDER); waitForElementClickableByElement(useAdvancedRecentChangesCheckbox); useAdvancedRecentChangesCheckbox.click(); PageObjectLogging.log("Use_advanced_recent_changes_checkbox", "Use_advanced_recent_changes_checkbox clicked", true); return this; }
Source:
<code>public static void setUp() throws Exception { System.setProperty(Constants.Properties.VXQUERY_PROPERTIES_FILE, "src/test/resources/vxquery.properties"); startLocalHyracks(); CCConfig ccConfig = clusterControllerService.getCCConfig(); System.setProperty(Constants.Properties.HYRACKS_CLIENT_IP, ccConfig.clientNetIpAddress); System.setProperty(Constants.Properties.HYRACKS_CLIENT_PORT, String.valueOf(ccConfig.clientNetPort)); <START> application = new VXQueryApplication(); <END> application.start(); restServer = application.getRestServer(); }</code><technical_language>VXQueryApplication instantiated explicitly. ClusterController start it</technical_language>

Target:
public static void setUp() throws Exception { vxqueryLocalCluster.init(new VXQueryConfig()); vxQueryService = vxqueryLocalCluster.getVxQueryService(); restIpAddress = vxqueryLocalCluster.getIpAddress(); restPort = vxqueryLocalCluster.getRestPort(); }
Source:
<code>public boolean isSsoIntegrationEnabled() { try { <START> final Predicate ssoEnabledPredicate = ssoEnabledConfiguration == null ? null : PredicateUtils.fromJSON(ssoEnabledConfiguration); <END> return ssoIntegrationSupported && ssoEnabledPredicate != null && ssoEnabledPredicate.evaluate(configHelper.calculateExistingConfigurations(ambariManagementController, cluster)); } catch (AmbariException e) { throw new AmbariRuntimeException("Error while evaulating if SSO integration is enabled", e); } }</code><technical_language>This compatible existing implementation. If is not, issues existing mpacks support this feature. I suggest a property for predicate declaration deprecated write a message log if encountered</technical_language>

Target:
public boolean isSsoIntegrationEnabled() { try { return ssoIntegrationSupported && ssoEnabledConfiguration != null && ssoEnabledConfiguration.evaluate(configHelper.calculateExistingConfigurations(ambariManagementController, cluster)); } catch (AmbariException e) { throw new AmbariRuntimeException("Error while evaulating if SSO integration is enabled", e); } }
Source:
<code>public static long fromInfluxDBTimeFormat(final String time) { try { <START> if (time.length() == 20) { <END> return FORMATTER_SECONDS.get().parse(time).getTime(); } return FORMATTER_MILLIS.get().parse(time).getTime(); } catch (Exception e) { throw new RuntimeException("unexpected date format", e); } }</code><technical_language>introduce a final static variable for this purpose</technical_language>

Target:
public static long fromInfluxDBTimeFormat(final String time) { try { if (time.length() == TIME_IN_SECOND_LENGTH) { return FORMATTER_SECONDS.get().parse(time).getTime(); } return FORMATTER_MILLIS.get().parse(time).getTime(); } catch (Exception e) { throw new RuntimeException("unexpected date format", e); } }
Source:
<code>public void deleteSelectedInstances(@PathVariable Long entityId, @PathVariable String instanceIds) throws ParseException { List<Long> instanceIdsList = new ArrayList(); <START> JSONParser parser = new JSONParser(); <END> Object instanceIdsJson = parser.parse(instanceIds); JSONObject instanceIdsJsonObject = (JSONObject) instanceIdsJson; Iterator iterator = instanceIdsJsonObject.keySet().iterator(); while (iterator.hasNext()) { String key = (String) iterator.next(); String value = instanceIdsJsonObject.get(key).toString(); instanceIdsList.add(Long.parseLong(value)); } instanceService.deleteSelectedInstances(entityId, instanceIdsList); }</code><technical_language>please com.google.gson library</technical_language>

Target:
public void deleteSelectedInstances(@PathVariable Long entityId, @PathVariable String instanceIds) { List<Long> instanceIdsList = new ArrayList(); JsonParser parser = new JsonParser(); JsonObject instanceIdsJsonObject = parser.parse(instanceIds).getAsJsonObject(); Set<Map.Entry<String, JsonElement>> entrySet = instanceIdsJsonObject.entrySet(); for (Map.Entry<String, JsonElement> entry : entrySet) { String value = instanceIdsJsonObject.get(entry.getKey()).toString(); value = value.substring(1).substring(0, 2); instanceIdsList.add(Long.parseLong(value)); } instanceService.deleteSelectedInstances(entityId, instanceIdsList); }
Source:
<code>public String read(int addr, WR3223Commands command) throws IOException { if (inputStream.available() > 0) { inputStream.skipBytes(inputStream.available()); } byte[] message = new byte[8]; message[0] = EOT; setControllerAddressToMessage(message, addr, 1); setCommandToMessage(message, command, 5); message[7] = ENQ; outputStream.write(message); outputStream.flush(); if (logger.isDebugEnabled()) { logger.debug("Write data: {}", bytesToHexString(message)); } byte[] answer = readAnswer(); int chkSum = inputStream.read(); if (logger.isDebugEnabled()) { logger.debug("Read data: with checksum {}.", bytesToHexString(answer), Integer.toHexString(chkSum)); } if (answer[0] == STX && answer[answer.length - 1] == ETX) { if (chkSum == buildCheckSum(answer, 1, answer.length - 1)) { if (command.name().equals(toString(answer, 1, 2))) { return toString(answer, 3, answer.length - 2); } else { <START> logger.error("Wrong command receive. Expected but got {}.", command.name(), <END> toString(answer, 1, 2)); } } else { logger.error("Checksum error. Expected but got {}.", chkSum, buildCheckSum(answer, 1, answer.length - 1)); } } else { logger.error("Start/end of the controller answer is wrong."); } return null; }</code><technical_language>"received"</technical_language>

Target:
public String read(int addr, WR3223Commands command) throws IOException { if (inputStream.available() > 0) { inputStream.skipBytes(inputStream.available()); } byte[] message = new byte[8]; message[0] = EOT; setControllerAddressToMessage(message, addr, 1); setCommandToMessage(message, command, 5); message[7] = ENQ; outputStream.write(message); outputStream.flush(); if (logger.isDebugEnabled()) { logger.debug("Write data: {}", bytesToHexString(message)); } byte[] answer = readAnswer(); int chkSum = inputStream.read(); if (logger.isDebugEnabled()) { logger.debug("Read data: with checksum {}.", bytesToHexString(answer), Integer.toHexString(chkSum)); } if (answer[0] == STX && answer[answer.length - 1] == ETX) { if (chkSum == buildCheckSum(answer, 1, answer.length - 1)) { if (command.name().equals(toString(answer, 1, 2))) { return toString(answer, 3, answer.length - 2); } else { logger.error("Wrong command received. Expected but got {}.", command.name(), toString(answer, 1, 2)); } } else { logger.error("Checksum error. Expected but got {}.", chkSum, buildCheckSum(answer, 1, answer.length - 1)); } } else { logger.error("Start/end of the controller answer is wrong."); } return null; }