auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void addRanges(String keyspaceName, ReplicaCollection<?> replicas) { Keyspace keyspace = Keyspace.open(keyspaceName); AbstractReplicationStrategy strat = keyspace.getReplicationStrategy(); if(strat instanceof LocalStrategy) { logger.info("Not adding ranges for Local Strategy keyspace={}", keyspaceName); return; } boolean useStrictSource = useStrictSourcesForRanges(strat); EndpointsByReplica fetchMap = calculateRangesToFetchWithPreferredEndpoints(replicas, keyspace, useStrictSource); for (Map.Entry<Replica, Replica> entry : fetchMap.flattenEntries()) logger.info("{}: range exists on for keyspace {}", description, entry.getKey(), entry.getValue(), keyspaceName); Multimap<InetAddressAndPort, FetchReplica> workMap; if (useStrictSource || strat == null || strat.getReplicationFactor().allReplicas == 1 || strat.getReplicationFactor().hasTransientReplicas()) { workMap = convertPreferredEndpointsToWorkMap(fetchMap); } else { workMap = getOptimizedWorkMap(fetchMap, sourceFilters, keyspaceName); } <START> assert toFetch.put(keyspaceName, workMap) == null : "Keyspace is already added to fetch map"; <END> if (logger.isTraceEnabled()) { for (Map.Entry<InetAddressAndPort, Collection<FetchReplica>> entry : workMap.asMap().entrySet()) { for (FetchReplica r : entry.getValue()) logger.trace("{}: range source local range for keyspace {}", description, r.remote, r.local, keyspaceName); } } }</code><technical_language>If asserts disabled this work :-P</technical_language>

Target:
public void addRanges(String keyspaceName, ReplicaCollection<?> replicas) { Keyspace keyspace = Keyspace.open(keyspaceName); AbstractReplicationStrategy strat = keyspace.getReplicationStrategy(); if(strat instanceof LocalStrategy) { logger.info("Not adding ranges for Local Strategy keyspace={}", keyspaceName); return; } boolean useStrictSource = useStrictSourcesForRanges(strat); EndpointsByReplica fetchMap = calculateRangesToFetchWithPreferredEndpoints(replicas, keyspace, useStrictSource); for (Map.Entry<Replica, Replica> entry : fetchMap.flattenEntries()) logger.info("{}: range exists on for keyspace {}", description, entry.getKey(), entry.getValue(), keyspaceName); Multimap<InetAddressAndPort, FetchReplica> workMap; if (useStrictSource || strat == null || strat.getReplicationFactor().allReplicas == 1 || strat.getReplicationFactor().hasTransientReplicas()) { workMap = convertPreferredEndpointsToWorkMap(fetchMap); } else { workMap = getOptimizedWorkMap(fetchMap, sourceFilters, keyspaceName); } if (toFetch.put(keyspaceName, workMap) != null) throw new IllegalArgumentException("Keyspace is already added to fetch map"); if (logger.isTraceEnabled()) { for (Map.Entry<InetAddressAndPort, Collection<FetchReplica>> entry : workMap.asMap().entrySet()) { for (FetchReplica r : entry.getValue()) logger.trace("{}: range source local range for keyspace {}", description, r.remote, r.local, keyspaceName); } } }
Source:
<code>private Optional<byte[]> getId(byte[] lookupkey, int numIdBytes) throws IOException, InterruptedException { Result result = WithHTable.get(pool, lookupTable, new Get(lookupkey)); final byte[] columnVal = result.getValue(cf, QUALIFIER); int tries = 0; while (tries < MAX_COMPAT_TRIES) { if (columnVal != null) { int statusOrdinal = columnVal[0]; Status status = Status.values()[statusOrdinal]; if (log.isDebugEnabled()) { log.debug("Entry status is " + status); } switch (status) { case ALLOCATED: byte[] id = Util.trailingBytes(columnVal, numIdBytes); if (log.isDebugEnabled()) { log.debug("Already allocated, returning " + Hex.encodeHexString(id)); } return Optional.of(id); <START> case ALLOCATING: <END> Thread.sleep(COMPAT_RETRY_SLEEP); tries++; break; default: throw new RuntimeException("Unexpected column value " + Arrays.toString(columnVal)); } } else { return Optional.absent(); } } throw new RuntimeException(String.format("Row %s was still 'ALLOCATING' after %d millis. Something is wrong.", Bytes.toString(lookupkey), MAX_COMPAT_TRIES * COMPAT_RETRY_SLEEP)); }</code><technical_language>log/meter this stopped hitting it</technical_language>

Target:
private Optional<byte[]> getId(byte[] lookupkey, int numIdBytes) throws IOException, InterruptedException { final TimerContext timer = idGetTime.time(); Result result = WithHTable.get(pool, lookupTable, new Get(lookupkey)); final byte[] columnVal = result.getValue(cf, QUALIFIER); int tries = 0; while (tries < MAX_COMPAT_TRIES) { if (columnVal != null) { int statusOrdinal = columnVal[0]; Status status = Status.values()[statusOrdinal]; if (log.isDebugEnabled()) { log.debug("Entry status is " + status); } switch (status) { case ALLOCATED: byte[] id = Util.trailingBytes(columnVal, numIdBytes); if (log.isDebugEnabled()) { log.debug("Already allocated, returning " + Hex.encodeHexString(id)); } timer.stop(); return Optional.of(id); case ALLOCATING: allocatingSleeps.mark(); Thread.sleep(COMPAT_RETRY_SLEEP); tries++; break; default: throw new RuntimeException("Unexpected column value " + Arrays.toString(columnVal)); } } else { timer.stop(); return Optional.absent(); } } throw new RuntimeException(String.format("Row %s was still 'ALLOCATING' after %d millis. Something is wrong.", Bytes.toString(lookupkey), MAX_COMPAT_TRIES * COMPAT_RETRY_SLEEP)); }
Source:
<code>public Mono<ThroughputResponse> replaceThroughput(ThroughputProperties throughputProperties) { return this.read() .flatMap(response -> this.getDocClientWrapper() .queryOffers(getOfferQuerySpecFromResourceId(response.getProperties() .getResourceId()), new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the " + <START> "resource")); <END> } Offer existingOffer = offerFeedResponse.getResults().get(0); ModelBridgeInternal.updateOfferFromProperties(existingOffer, throughputProperties); return this.getDocClientWrapper() .replaceOffer(existingOffer) .single(); }) .map(ModelBridgeInternal::createThroughputRespose)); }</code><technical_language>is worth including name of database in sdk generated error message</technical_language>

Target:
public Mono<ThroughputResponse> replaceThroughput(ThroughputProperties throughputProperties) { return this.read() .flatMap(response -> this.getDocClientWrapper() .queryOffers(getOfferQuerySpecFromResourceId(response.getProperties() .getResourceId()), new FeedOptions()) .single() .flatMap(offerFeedResponse -> { if (offerFeedResponse.getResults().isEmpty()) { return Mono.error(BridgeInternal .createCosmosClientException( HttpConstants.StatusCodes.BADREQUEST, "No offers found for the " + "resource " + this.getId())); } Offer existingOffer = offerFeedResponse.getResults().get(0); Offer updatedOffer = ModelBridgeInternal.updateOfferFromProperties(existingOffer, throughputProperties); return this.getDocClientWrapper() .replaceOffer(updatedOffer) .single(); }) .map(ModelBridgeInternal::createThroughputRespose)); }
Source:
<code>static ReadCountCollection removeColumnsWithTooManyZeros(final ReadCountCollection readCounts, final int maximumColumnZeros, final Logger logger) { final RealMatrix counts = readCounts.counts(); <START> final Set<String> columnsToKeep = IntStream.range(0, counts.getColumnDimension()).boxed() <END> .filter(i -> countZeroes(counts.getColumn(i)) <= maximumColumnZeros) .map(i -> readCounts.columnNames().get(i)).collect(Collectors.toSet()); final int columnsToDropCount = readCounts.columnNames().size() - columnsToKeep.size(); if (columnsToDropCount == 0) { logger.info( String.format("No count column dropped due to zero counts; there is no column with a large number of targets with zero counts (<= %d of %d) ", maximumColumnZeros, readCounts.targets().size())); return readCounts; } else if (columnsToDropCount == readCounts.columnNames().size()) { throw new UserException.BadInput("The number of zeros per count column is too large resulting in all count columns to be dropped"); } else { logger.info( String.format("Some counts columns dropped, %d of %d, as they have too many targets with zeros (> %d of %d)." , columnsToDropCount, readCounts.columnNames().size(), maximumColumnZeros, readCounts.targets().size())); return readCounts.subsetColumns(columnsToKeep); } }</code><technical_language>Instead of .boxed() . . . map() skip boxed() mapToObj()</technical_language>

Target:
static ReadCountCollection removeColumnsWithTooManyZeros(final ReadCountCollection readCounts, final int maximumColumnZeros, final Logger logger) { final RealMatrix counts = readCounts.counts(); final Set<String> columnsToKeep = IntStream.range(0, counts.getColumnDimension()) .filter(i -> countZeroes(counts.getColumn(i)) <= maximumColumnZeros) .mapToObj(i -> readCounts.columnNames().get(i)).collect(Collectors.toSet()); final int columnsToDropCount = readCounts.columnNames().size() - columnsToKeep.size(); if (columnsToDropCount == 0) { logger.info( String.format("No count column dropped due to zero counts; there is no column with a large number of targets with zero counts (<= %d of %d) ", maximumColumnZeros, readCounts.targets().size())); return readCounts; } else if (columnsToDropCount == readCounts.columnNames().size()) { throw new UserException.BadInput("The number of zeros per count column is too large resulting in all count columns to be dropped"); } else { logger.info( String.format("Some counts columns dropped, %d of %d, as they have too many targets with zeros (> %d of %d)." , columnsToDropCount, readCounts.columnNames().size(), maximumColumnZeros, readCounts.targets().size())); return readCounts.subsetColumns(columnsToKeep); } }
Source:
<code>public void evaluate() throws Throwable { <START> if (null != previous) { <END> previous.evaluate(); } for (FrameworkMethod before : befores) { before.invokeExplosively(target); } next.evaluate(); }</code><technical_language>Is reasonable for caller pass in a null for previous constructor? If not, constructor throw a NullPointerException if is null</technical_language>

Target:
public void evaluate() throws Throwable { for (FrameworkMethod before : befores) { before.invokeExplosively(target); } next.evaluate(); }
Source:
<code>protected void showCaseData(String selection, String[] selectionArgs) { ListView la = (ListView)this.findViewById(R.id.list_view); <START> Cursor c = this.managedQuery(Uri.parse("content://org.commcare.dalvik.case/casedb/case"), null, selection, selectionArgs, null); <END> final SimpleCursorAdapter sca = new SimpleCursorAdapter(this, android.R.layout.two_line_list_item, c, new String[] {"case_name", "case_id"}, new int[] { android.R.id.text1, android.R.id.text2}); la.setOnItemLongClickListener(new OnItemLongClickListener() { public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position, long arg3) { Cursor cursor = sca.getCursor(); cursor.moveToPosition(position); String caseType = cursor.getString(cursor.getColumnIndex("case_type")); CaseMediaActivity.this.showCaseData("case_type = ? AND\nstatus=?", new String[] { caseType,"open" }); return true; } }); la.setAdapter(sca); la.setOnItemClickListener(new OnItemClickListener(){ public void onItemClick(AdapterView<?> arg0, View v, int position, long id) { Cursor cursor = sca.getCursor(); cursor.moveToPosition(position); String caseId = cursor.getString(cursor.getColumnIndex("case_id")); CaseMediaActivity.this.moveToMediaAdapter(caseId); } }); }</code><technical_language>this URI string ("content://...") encoded a constant</technical_language>

Target:
private void showCaseData(String selection, String[] selectionArgs) { ListView la = (ListView)this.findViewById(R.id.list_view); Cursor c = this.managedQuery(Uri.parse(CASE_URI_ROOT + "case"), null, selection, selectionArgs, null); final SimpleCursorAdapter sca = new SimpleCursorAdapter(this, android.R.layout.two_line_list_item, c, new String[] {"case_name", "case_id"}, new int[] { android.R.id.text1, android.R.id.text2}); la.setOnItemLongClickListener(new OnItemLongClickListener() { public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position, long arg3) { Cursor cursor = sca.getCursor(); cursor.moveToPosition(position); String caseType = cursor.getString(cursor.getColumnIndex("case_type")); CaseMediaActivity.this.showCaseData("case_type = ? AND\nstatus=?", new String[] { caseType,"open" }); return true; } }); la.setAdapter(sca); la.setOnItemClickListener(new OnItemClickListener(){ public void onItemClick(AdapterView<?> arg0, View v, int position, long id) { Cursor cursor = sca.getCursor(); cursor.moveToPosition(position); String caseId = cursor.getString(cursor.getColumnIndex("case_id")); CaseMediaActivity.this.moveToMediaAdapter(caseId); } }); }
Source:
<code>public Optional<IgniteableData> createFrom(DataHolder dataHolder) { if (supports(dataHolder)) { <START> final int fireTicks = ((net.minecraft.entity.Entity) dataHolder).fire; <END> final int fireDelay = ((net.minecraft.entity.Entity) dataHolder).fireResistance; return Optional.<IgniteableData>of(new SpongeIgniteableData(fireTicks, fireDelay)); } return Optional.absent(); }</code><technical_language>surround this logic if (dataHolder instanceOf Entity) for future expansions</technical_language>

Target:
public Optional<IgniteableData> createFrom(DataHolder dataHolder) { if (supports(dataHolder)) { if (dataHolder instanceof Entity) { final int fireTicks = ((Entity) dataHolder).fire; final int fireDelay = ((Entity) dataHolder).fireResistance; return Optional.<IgniteableData>of(new SpongeIgniteableData(fireTicks, fireDelay)); } } return Optional.absent(); }
Source:
<code>public Boolean fenceOff(VirtualMachine vm, Host host) { if (host.getHypervisorType() != HypervisorType.Ovm) { s_logger.debug("Don't know how to fence non Ovm hosts " + host.getHypervisorType()); return null; } List<HostVO> hosts = _resourceMgr.listAllHostsInCluster(host.getClusterId()); FenceCommand fence = new FenceCommand(vm, host); for (HostVO h : hosts) { if (h.getHypervisorType() != HypervisorType.Ovm) { continue; } if (h.getStatus() != Status.Up) { continue; } if (h.getId() == host.getId()) { continue; } FenceAnswer answer; try { answer = (FenceAnswer)_agentMgr.send(h.getId(), fence); } catch (AgentUnavailableException e) { if (s_logger.isDebugEnabled()) { s_logger.debug("Moving on to the next host because " + h.toString() + " is unavailable"); } continue; } catch (OperationTimedoutException e) { if (s_logger.isDebugEnabled()) { s_logger.debug("Moving on to the next host because " + h.toString() + " is unavailable"); } continue; <START> } catch (OperationCancelledException e) { <END> if (s_logger.isDebugEnabled()) { s_logger.debug("Moving on to the next host because " + h.toString() + " is unavailable (Operation Cancelled)"); } continue; } if (answer != null && answer.getResult()) { return true; } } if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to fence off " + vm.toString() + " on " + host.toString()); } return false; }</code><technical_language>In case of OperationCancelled is a logic move another host, terminated immediately</technical_language>

Target:
public Boolean fenceOff(VirtualMachine vm, Host host) { if (host.getHypervisorType() != HypervisorType.Ovm) { s_logger.debug("Don't know how to fence non Ovm hosts " + host.getHypervisorType()); return null; } List<HostVO> hosts = _resourceMgr.listAllHostsInCluster(host.getClusterId()); FenceCommand fence = new FenceCommand(vm, host); for (HostVO h : hosts) { if (h.getHypervisorType() != HypervisorType.Ovm) { continue; } if (h.getStatus() != Status.Up) { continue; } if (h.getId() == host.getId()) { continue; } FenceAnswer answer; try { answer = (FenceAnswer)_agentMgr.send(h.getId(), fence); } catch (AgentUnavailableException e) { if (s_logger.isDebugEnabled()) { s_logger.debug("Moving on to the next host because " + h.toString() + " is unavailable"); } continue; } catch (OperationTimedoutException e) { if (s_logger.isDebugEnabled()) { s_logger.debug("Moving on to the next host because " + h.toString() + " is unavailable"); } continue; } catch (OperationCancelledException e) { if (s_logger.isDebugEnabled()) { s_logger.debug("Cancelling because " + h.toString() + " is unavailable (Operation Cancelled)"); } break; } if (answer != null && answer.getResult()) { return true; } } if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to fence off " + vm.toString() + " on " + host.toString()); } return false; }
Source:
<code>public PinotQueryGeneratorContext visitTopN(TopNNode node, PinotQueryGeneratorContext context) { context = node.getSource().accept(this, context); requireNonNull(context, "context is null"); checkSupported(preferBrokerQueries, "Cannot push topn in segment mode"); checkSupported(node.getStep().equals(TopNNode.Step.SINGLE), "Can only push single logical topn in"); return context.withTopN(PushdownUtils.getOrderingScheme(node), node.getCount()).withOutputColumns(node.getOutputVariables()); <START> } <END></code><technical_language>Map<...></technical_language>

Target:
public PinotQueryGeneratorContext visitTopN(TopNNode node, PinotQueryGeneratorContext context) { context = node.getSource().accept(this, context); requireNonNull(context, "context is null"); checkSupported(preferBrokerQueries, "Cannot push topn in segment mode"); checkSupported(node.getStep().equals(TopNNode.Step.SINGLE), "Can only push single logical topn in"); return context.withTopN(getOrderingScheme(node), node.getCount()).withOutputColumns(node.getOutputVariables()); }
Source:
<code>public Client getLocalClient() { final ClientConnectionManager cm = client.getConnectionManager(); final ClientConnection connection = cm.getOwnerConnection(); InetSocketAddress inetSocketAddress = connection != null ? connection.getLocalSocketAddress() : null; ClientPrincipal principal = cm.getPrincipal(); final String uuid = principal != null ? principal.getUuid() : null; <START> return new ClientImpl(uuid, inetSocketAddress, client.getName(), client.getClientConfig().getAttributes()); <END> }</code><technical_language>a copy of clientConfig.attributes wrap in immutable map so: 1) protected accidental modification. need ad hoc wrappings. 2) if a user mutation client config created client, lead funky behavior</technical_language>

Target:
public Client getLocalClient() { final ClientConnectionManager cm = client.getConnectionManager(); final ClientConnection connection = cm.getOwnerConnection(); InetSocketAddress inetSocketAddress = connection != null ? connection.getLocalSocketAddress() : null; ClientPrincipal principal = cm.getPrincipal(); final String uuid = principal != null ? principal.getUuid() : null; return new ClientImpl(uuid, inetSocketAddress, client.getName(), attributes); }
Source:
<code>protected <T extends VMInstanceVO> boolean changeState(final T vm, final Event event, final Long hostId, final ItWorkVO work, final Step step) throws NoTransitionException { Step previousStep = null; if (work != null) { <START> previousStep = work.getStep(); <END> _workDao.updateStep(work, step); } boolean result = false; try { result = stateTransitTo(vm, event, hostId); return result; } finally { if (!result && previousStep != null) { _workDao.updateStep(work, previousStep); } } }</code><technical_language>" work.getStep()" return null? I add a check line 757 previousStep != null. need check there, need (line750)</technical_language>

Target:
protected <T extends VMInstanceVO> boolean changeState(final T vm, final Event event, final Long hostId, final ItWorkVO work, final Step step) throws NoTransitionException { Step previousStep = null; if (work != null) { previousStep = work.getStep(); _workDao.updateStep(work, step); } boolean result = false; try { result = stateTransitTo(vm, event, hostId); return result; } finally { if (!result && work != null) { _workDao.updateStep(work, previousStep); } } }
Source:
<code>public void shouldBlockUntilFailedCompletion() throws Exception { AtomicReference<Exception> testThreadException = new AtomicReference<>(); TestConvertingFutureCallback testCallback = new TestConvertingFutureCallback(); final Throwable expectedError = new Throwable(); runSeparateTestThread(() -> { try { testCallback.waitForGet(); testCallback.onCompletion(expectedError, null); } catch (Exception e) { testThreadException.compareAndSet(null, e); } }); assertFalse(testCallback.isDone()); try { <START> testCallback.get(); <END> } catch (ExecutionException e) { assertEquals(expectedError, e.getCause()); } assertEquals(0, testCallback.numberOfConversions()); assertTrue(testCallback.isDone()); if (testThreadException.get() != null) { throw testThreadException.get(); } }</code><technical_language>ditto, fail()</technical_language>

Target:
public void shouldBlockUntilFailedCompletion() throws Exception { AtomicReference<Exception> testThreadException = new AtomicReference<>(); TestConvertingFutureCallback testCallback = new TestConvertingFutureCallback(); final Throwable expectedError = new Throwable(); executor.submit(() -> { try { testCallback.waitForGet(); testCallback.onCompletion(expectedError, null); } catch (Exception e) { testThreadException.compareAndSet(null, e); } }); assertFalse(testCallback.isDone()); try { testCallback.get(); fail("Expected ExecutionException"); } catch (ExecutionException e) { assertEquals(expectedError, e.getCause()); } assertEquals(0, testCallback.numberOfConversions()); assertTrue(testCallback.isDone()); if (testThreadException.get() != null) { throw testThreadException.get(); } }
Source:
<code>public QueueServiceClientBuilder() { retryPolicy = new RetryPolicy(); logLevel = HttpLogDetailLevel.NONE; policies = new ArrayList<>(); configuration = ConfigurationManager.getConfiguration(); <START> retryPolicy = new RetryPolicy(); <END> logLevel = HttpLogDetailLevel.NONE; }</code><technical_language>Duplicated code</technical_language>

Target:
public QueueServiceClientBuilder() { retryPolicy = new RetryPolicy(); logLevel = HttpLogDetailLevel.NONE; policies = new ArrayList<>(); configuration = ConfigurationManager.getConfiguration(); }
Source:
<code>static long nanoToMicro(long nano) { <START> return (long) Math.ceil(nano / (double) 1000); <END> }</code><technical_language>double math here? This be: return Math.max(1L, nano / 1000L);</technical_language>

Target:
static long nanoToMicro(long nano) { return Math.max(1, (long) Math.ceil(nano / (double) 1000)); }
Source:
<code>private void notifyToLocatorActivity(BDLocation bdloc) { if (mLocationListener != null) { MyLocationData locData = new MyLocationData.Builder() .accuracy(bdloc.getRadius()) <START> .direction(100).latitude(bdloc.getLatitude()) <END> .longitude(bdloc.getLongitude()).build(); Location aLoc = new Location("BaiduMap"); aLoc.setLongitude(bdloc.getLongitude()); aLoc.setLatitude(bdloc.getLatitude()); mLocationListener.onLocationChanged(aLoc); } }</code><technical_language>@droneboost is call .direction(100) needed? If it's, 100 represent</technical_language>

Target:
private void notifyToLocatorActivity(BDLocation bdloc) { if (mLocationListener != null) { Location aLoc = new Location("BaiduMap"); aLoc.setLongitude(bdloc.getLongitude()); aLoc.setLatitude(bdloc.getLatitude()); mLocationListener.onLocationChanged(aLoc); } }
Source:
<code>private byte[] getRemoteDeviceData(XBeeAPIPacket packet) { byte[] data = null; logger.trace("{}Received packet: {}.", toString(), packet); APIFrameType frameType = packet.getFrameType(); switch (frameType) { case AT_COMMAND_RESPONSE: ATCommandResponsePacket atResponse = (ATCommandResponsePacket)packet; if (atResponse.getFrameID() != frameID) return null; if (!atResponse.getCommand().equals(ND_COMMAND)) return null; if (atResponse.getCommandValue() == null || atResponse.getCommandValue().length == 0) { discovering = atResponse.getStatus() != ATCommandStatus.OK; return null; } <START> <END> logger.debug("{}Received self reponse: {}.", toString(), packet); data = atResponse.getCommandValue(); break; default: break; } return data; }</code><technical_language>In line this...typo: java logger.debug("{}Received response: {}.", toString(), packet);</technical_language>

Target:
private byte[] getRemoteDeviceData(XBeeAPIPacket packet) { byte[] data = null; logger.trace("{}Received packet: {}.", xbeeDevice.toString(), packet); APIFrameType frameType = packet.getFrameType(); switch (frameType) { case AT_COMMAND_RESPONSE: ATCommandResponsePacket atResponse = (ATCommandResponsePacket)packet; if (atResponse.getFrameID() != frameID) return null; if (!atResponse.getCommand().equals(ND_COMMAND)) return null; if (atResponse.getCommandValue() == null || atResponse.getCommandValue().length == 0) { discovering = atResponse.getStatus() != ATCommandStatus.OK; return null; } logger.debug("{}Received self response: {}.", xbeeDevice.toString(), packet); data = atResponse.getCommandValue(); break; default: break; } return data; }
Source:
<code>public void close() { instance = null; if (isolatedThread != null) { isolatedThread.setContextClassLoader(previousContextClassLoader); } if (!reusableClassLoader) { ClassLoaderIsolatedSystemProperties.getInstance().stopIsolateClassLoader(sandboxClassLoader); if (sandboxClassLoader instanceof AutoCloseable) { try { ((AutoCloseable) sandboxClassLoader).close(); } catch (Exception e) { new TalendRuntimeException(CommonErrorCodes.UNEXPECTED_EXCEPTION, e); <START> } <END> } } sandboxClassLoader = null; previousContextClassLoader = null; isolatedThread = null; isClosed = true; }</code><technical_language>I TalendRuntimeException.createUnexpectedException(e) is preferred</technical_language>

Target:
public void close() { instance = null; if (isolatedThread != null) { isolatedThread.setContextClassLoader(previousContextClassLoader); } if (!reusableClassLoader) { ClassLoaderIsolatedSystemProperties.getInstance().stopIsolateClassLoader(sandboxClassLoader); if (sandboxClassLoader instanceof AutoCloseable) { try { ((AutoCloseable) sandboxClassLoader).close(); } catch (Exception e) { TalendRuntimeException.createUnexpectedException(e); } } } sandboxClassLoader = null; previousContextClassLoader = null; isolatedThread = null; isClosed = true; }
Source:
<code>protected Metric constructMetric(String metricField, Class<?> cls, EntityDictionary entityDictionary) { Meta metaData = entityDictionary.getAttributeOrRelationAnnotation(cls, Meta.class, metricField); Class<?> fieldType = entityDictionary.getType(cls, metricField); List<Class<? extends Aggregation>> aggregations = Arrays.stream( entityDictionary.getAttributeOrRelationAnnotation( cls, MetricAggregation.class, metricField ).aggregations() ) .collect( Collectors.collectingAndThen( Collectors.toList(), Collections::unmodifiableList ) ); <START> String columnName = metricField; <END> if (entityDictionary.attributeOrRelationAnnotationExists(cls, metricField, javax.persistence.Column.class)) { columnName = entityDictionary .getAttributeOrRelationAnnotation(cls, javax.persistence.Column.class, metricField).name(); } return new AggregatedMetric( this, metricField, metaData, fieldType, aggregations, columnName ); }</code><technical_language>is a function in SQLSchema this</technical_language>

Target:
protected Metric constructMetric(String metricField, Class<?> cls, EntityDictionary entityDictionary) { Meta metaData = entityDictionary.getAttributeOrRelationAnnotation(cls, Meta.class, metricField); Class<?> fieldType = entityDictionary.getType(cls, metricField); List<Class<? extends Aggregation>> aggregations = getAggregations(metricField, cls, entityDictionary); return new AggregatedMetric( this, metricField, metaData, fieldType, aggregations ); }
Source:
<code>public Symbol visitIntervalLiteral(IntervalLiteral node, ExpressionAnalysisContext context) { String value = node.getValue(); <START> if (value == null || value.isEmpty() || value.isBlank()) { <END> throw new IllegalArgumentException("Invalid value " + value); } IntervalParser.Precision start = INTERVAL_FIELDS.get(node.getStartField()); IntervalParser.Precision end = node.getEndField() == null ? null : INTERVAL_FIELDS.get(node.getEndField()); Period period = IntervalParser.apply(value, start, end); if (node.getSign() == IntervalLiteral.Sign.MINUS) { period = period.negated(); } return Literal.newInterval(period); }</code><technical_language>IntervalParser care of empty blank cases</technical_language>

Target:
public Symbol visitIntervalLiteral(IntervalLiteral node, ExpressionAnalysisContext context) { String value = node.getValue(); IntervalParser.Precision start = INTERVAL_FIELDS.get(node.getStartField()); IntervalParser.Precision end = node.getEndField() == null ? null : INTERVAL_FIELDS.get(node.getEndField()); Period period = IntervalParser.apply(value, start, end); if (node.getSign() == IntervalLiteral.Sign.MINUS) { period = period.negated(); } return Literal.newInterval(period); }
Source:
<code>protected void beforeExecute() { <START> builder.addImport(builder.build().getPackageName().replace("queries", "") + getContextType()); <END> addBaseClassAndConstructor(); }</code><technical_language>@schleichardt necessary anymore</technical_language>

Target:
protected void beforeExecute() { addBaseClassAndConstructor(); }
Source:
<code>public void setLocale(String locale) { titleText.setLocale(locale); subtitleText.setLocale(locale); LayoutParams dividerParams = (LayoutParams) divider.getLayoutParams(); dividerParams.gravity = isLangRTL(locale) ? Gravity.RIGHT : Gravity.LEFT; divider.setLayoutParams(dividerParams); FrameLayout.LayoutParams pencilParams = (FrameLayout.LayoutParams) editPencil.getLayoutParams(); pencilParams.gravity = Gravity.BOTTOM | (isLangRTL(locale) ? Gravity.LEFT : Gravity.RIGHT); <START> editPencil.setLayoutParams(pencilParams); <END> int subtitlePadding = editPencil.getWidth(); subtitleText.setPadding(isLangRTL(locale) ? subtitlePadding : 0, subtitleText.getPaddingTop(), isLangRTL(locale) ? 0 : subtitlePadding, subtitleText.getPaddingBottom()); }</code><technical_language>Do need call editPencil.setLayoutParams() if operating LayoutParams editPencil</technical_language>

Target:
public void setLocale(String locale) { titleText.setLocale(locale); subtitleText.setLocale(locale); LinearLayout.LayoutParams dividerParams = (LinearLayout.LayoutParams) divider.getLayoutParams(); dividerParams.gravity = isLangRTL(locale) ? Gravity.RIGHT : Gravity.LEFT; divider.setLayoutParams(dividerParams); FrameLayout.LayoutParams pencilParams = (FrameLayout.LayoutParams) editPencil.getLayoutParams(); pencilParams.gravity = Gravity.BOTTOM | (isLangRTL(locale) ? Gravity.LEFT : Gravity.RIGHT); int subtitlePadding = editPencil.getWidth(); subtitleText.setPadding(isLangRTL(locale) ? subtitlePadding : 0, subtitleText.getPaddingTop(), isLangRTL(locale) ? 0 : subtitlePadding, subtitleText.getPaddingBottom()); }
Source:
<code>public static List<RowExpression> extractPredicates(Form form, RowExpression expression) { if (expression instanceof SpecialFormExpression && ((SpecialFormExpression) expression).getForm() == form) { SpecialFormExpression specialFormExpression = (SpecialFormExpression) expression; if (specialFormExpression.getArguments().size() != 2) { throw new IllegalStateException("logical binary expression requires exactly 2 operands"); } List<RowExpression> predicates = new ArrayList<>(); predicates.addAll(extractPredicates(form, specialFormExpression.getArguments().get(0))); predicates.addAll(extractPredicates(form, specialFormExpression.getArguments().get(1))); <START> return predicates; <END> } return Collections.singletonList(expression); }</code><technical_language>add unmodifiableList</technical_language>

Target:
public static List<RowExpression> extractPredicates(Form form, RowExpression expression) { if (expression instanceof SpecialFormExpression && ((SpecialFormExpression) expression).getForm() == form) { SpecialFormExpression specialFormExpression = (SpecialFormExpression) expression; if (specialFormExpression.getArguments().size() != 2) { throw new IllegalStateException("logical binary expression requires exactly 2 operands"); } List<RowExpression> predicates = new ArrayList<>(); predicates.addAll(extractPredicates(form, specialFormExpression.getArguments().get(0))); predicates.addAll(extractPredicates(form, specialFormExpression.getArguments().get(1))); return Collections.unmodifiableList(predicates); } return Collections.singletonList(expression); }
Source:
<code>private void addSenMLRecord(String recordName, LwM2mResource resource, Object value) { ResourceModel rSpec = model.getResourceModel(objectId, resource.getId()); Type expectedType = rSpec != null ? rSpec.type : resource.getType(); SenMLRecord record = new SenMLRecord(); String bn = requestPath.toString(); String n = recordName == null ? "" : recordName; if (records.isEmpty()) { <START> if (!requestPath.isResource()) { <END> bn += "/"; } record.setBaseName(bn); } record.setName(n); LwM2mPath lwM2mResourcePath = new LwM2mPath(bn + n); Object convertedValue = converter.convertValue(value, resource.getType(), expectedType, lwM2mResourcePath); setResourceValue(convertedValue, expectedType, lwM2mResourcePath, record); records.add(record); }</code><technical_language>I right test is !n.isEmpty()</technical_language>

Target:
private void addSenMLRecord(String recordName, LwM2mResource resource, Object value) { ResourceModel rSpec = model.getResourceModel(objectId, resource.getId()); Type expectedType = rSpec != null ? rSpec.type : resource.getType(); SenMLRecord record = new SenMLRecord(); String bn = requestPath.toString(); String n = recordName == null ? "" : recordName; if (records.isEmpty()) { if (!n.isEmpty()) { bn += "/"; } record.setBaseName(bn); } record.setName(n); LwM2mPath lwM2mResourcePath = new LwM2mPath(bn + n); Object convertedValue = converter.convertValue(value, resource.getType(), expectedType, lwM2mResourcePath); setResourceValue(convertedValue, expectedType, lwM2mResourcePath, record); records.add(record); }
Source:
<code>private void setTemperatureMeasurementTimerInterval(int measurementIntervalValueSeconds) { timer = new CountDownTimer(30000, measurementIntervalValueSeconds * 1000) { @Override public void onTick(long millisUntilFinished) { <START> mDelegate.sendNotificationToDevices(mTemperatureMeasurementCharacteristic); <END> } @Override public void onFinish() { timer.start(); } }.start(); final String message = String.format(getString(R.string.sendingNotifications), measurementIntervalValueSeconds); getActivity().runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show(); } }); }</code><technical_language>I noticed. If connected device this continually show "No Connected Devices" Toast. Another reason for a button for starting notifications</technical_language>

Target:
private void setTemperatureMeasurementTimerInterval(int measurementIntervalValueSeconds) { mTimer = new Timer(); mTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { getActivity().runOnUiThread(new Runnable() { @Override public void run() { mDelegate.sendNotificationToDevices(mTemperatureMeasurementCharacteristic); } }); } }, 0 , measurementIntervalValueSeconds * 1000); }
Source:
<code>public boolean mousePressed(Minecraft mc, int x, int y) { boolean b = parent.blockMouseInput ? false : super.mousePressed(mc, x, y); if (b) <START> parent.tileentity.setInputMode(side, EnumConnectionType.values()[(mode.ordinal() + 1) % 4]); <END> return b; }</code><technical_language>enum's length</technical_language>

Target:
public boolean mousePressed(Minecraft mc, int x, int y) { boolean b = !parent.blockMouseInput && super.mousePressed(mc, x ,y); if (b) { List<EnumConnectionType> supported = EnumConnectionType.getSupportedList(parent.getCircuitData().maximumIOSize()); EnumConnectionType next = supported.get((supported.indexOf(mode) + 1) % supported.size()); parent.tileentity.setInputMode(side, next); } return b; }
Source:
<code>private static Object tryToMakeCompatibleArray( final Class<?> expectedComponentClz, final Class<?> inputComponentClz, Object param) throws VoltTypeException { int inputLength = Array.getLength(param); if (inputComponentClz == expectedComponentClz) { return param; } else if (inputLength == 0) { return Array.newInstance(expectedComponentClz, 0); } else if ((inputComponentClz == byte[].class || inputComponentClz == Byte[].class) && (expectedComponentClz == String.class)) { String[] values = new String[inputLength]; for (int i = 0; i < inputLength; i++) { try { values[i] = new String((byte[]) Array.get(param, i), "UTF-8"); } catch (UnsupportedEncodingException ex) { throw new VoltTypeException( "tryScalarMakeCompatible: Unsupported encoding:" + expectedComponentClz.getName() + " to provided " + inputComponentClz.getName()); } } return values; } else if ((inputComponentClz == String.class) && (expectedComponentClz == byte[].class || expectedComponentClz == Byte[].class )) { byte[][] values = new byte[inputLength][]; Byte[][] boxvalues = new Byte[inputLength][]; for (int i = 0; i < inputLength; i++) { values[i] = Encoder.hexDecode((String) Array.get(param, i)); <START> boxvalues[i] = ArrayUtils.toObject( values[i] ); <END> } if (expectedComponentClz == byte[].class) return values; else return boxvalues; } else { throw new VoltTypeException( "tryScalarMakeCompatible: Unable to match parameter array:" + expectedComponentClz.getName() + " to provided " + inputComponentClz.getName()); } }</code><technical_language>populating values boxvalues of needed. refactor this more efficient</technical_language>

Target:
private static Object tryToMakeCompatibleArray( final Class<?> expectedComponentClz, final Class<?> inputComponentClz, Object param) throws VoltTypeException { int inputLength = Array.getLength(param); if (inputComponentClz == expectedComponentClz) { return param; } else if (inputLength == 0) { return Array.newInstance(expectedComponentClz, 0); } else if (isByteArrayClass(inputComponentClz) && (expectedComponentClz == String.class)) { String[] values = new String[inputLength]; for (int i = 0; i < inputLength; i++) { try { values[i] = new String((byte[]) Array.get(param, i), "UTF-8"); } catch (UnsupportedEncodingException ex) { throw new VoltTypeException( "tryScalarMakeCompatible: Unsupported encoding:" + expectedComponentClz.getName() + " to provided " + inputComponentClz.getName()); } } return values; } else if ((inputComponentClz == String.class) && (expectedComponentClz == byte[].class)) { byte[][] values = new byte[inputLength][]; for (int i = 0; i < inputLength; i++) { values[i] = Encoder.hexDecode((String) Array.get(param, i)); } return values; } else if ((inputComponentClz == String.class) && (expectedComponentClz == Byte[].class)) { Byte[][] boxvalues = new Byte[inputLength][]; for (int i = 0; i < inputLength; i++) { boxvalues[i] = ArrayUtils.toObject( Encoder.hexDecode((String) Array.get(param, i)) ); } return boxvalues; } else { throw new VoltTypeException( "tryScalarMakeCompatible: Unable to match parameter array:" + expectedComponentClz.getName() + " to provided " + inputComponentClz.getName()); } }
Source:
<code>public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.save_pin) { if (client.getPosition() == null) { Toaster.show(findViewById(android.R.id.content), <START> getString(R.string.you_should_drop_client_pin)); <END> return false; } mPinPointClientPresenter.updateGpsData(clientId, new GpsCoordinatesRequest(client .getPosition())); } return super.onOptionsItemSelected(item); }</code><technical_language>change string name drop_client_pin</technical_language>

Target:
public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.save_pin) { if (client.getPosition() == null) { Toaster.show(findViewById(android.R.id.content), getString(R.string.drop_client_pin)); return false; } mPinPointClientPresenter.updateGpsData(clientId, new GpsCoordinatesRequest(client .getPosition())); } return super.onOptionsItemSelected(item); }
Source:
<code>private int getModelOrderFromConnectedEdges(final LNode n) { List<LPort> ports = n.getPorts(); if (ports.size() > 0) { <START> LEdge edge = null; <END> for (LPort lPort : ports) { if (lPort.getIncomingEdges().size() > 0) { edge = lPort.getIncomingEdges().get(0); break; } } if (edge == null) { return Integer.MAX_VALUE; } return edge.getProperty(InternalProperties.MODEL_ORDER); } return Integer.MAX_VALUE; }</code><technical_language>"filter.findFirst" pattern again. I find more readable</technical_language>

Target:
private int getModelOrderFromConnectedEdges(final LNode n) { LPort sourcePort = n.getPorts().stream().filter(p -> !p.getIncomingEdges().isEmpty()).findFirst().orElse(null); if (sourcePort != null) { LEdge edge = sourcePort.getIncomingEdges().get(0); if (edge != null) { return edge.getProperty(InternalProperties.MODEL_ORDER); } } return Integer.MAX_VALUE; }
Source:
<code>public void testInvocation() throws Exception { MockRoutingTableChangeListener routingTableChangeListener = new TestRoutingTableProvider().new MockRoutingTableChangeListener(); _routingTableProvider_default.addRoutingTableChangeListener(routingTableChangeListener, null); AssertJUnit.assertTrue(routingTableChangeListener.routingTableChangeReceived); <START> } <END></code><technical_language>Assert.assertTrue? need import AssertJUnit</technical_language>

Target:
public void testInvocation() throws Exception { MockRoutingTableChangeListener routingTableChangeListener = new MockRoutingTableChangeListener(); _routingTableProvider_default .addRoutingTableChangeListener(routingTableChangeListener, null, true); Assert.assertTrue(TestHelper.verify(() -> { if (!routingTableChangeListener.routingTableChangeReceived) { return false; } return true; }, TestHelper.WAIT_DURATION)); }
Source:
<code>public void generateDataBeans() { LicenseHeaders licenseHeader = new LicenseHeaders("ASLv2"); File[] inputFiles = getInputFiles(); try { GoraCompiler.compileSchema(inputFiles, BEAN_DESTINATION_DIR, licenseHeader); <START> } catch (IOException e) { <END> } }</code><technical_language>omitted handling exception. log exception trace</technical_language>

Target:
public static void generateDataBeans() { LicenseHeaders licenseHeader = new LicenseHeaders("ASLv2"); File[] inputFiles = getInputFiles(); try { GoraCompiler.compileSchema(inputFiles, Constants.BEAN_DESTINATION_DIR, licenseHeader); } catch (IOException e) { LOG.info("There is a problem generating Data Beans \n {}", e.getMessage(), e); } }
Source:
<code>private void splitMultipleDeclarations(Node var) { checkState(var.isVar() || var.isLet() || var.isConst()); while (var.getSecondChild() != null) { Node newVar; Node nameToSplit = var.removeFirstChild(); switch (var.getToken()) { default: case VAR: newVar = IR.var(nameToSplit); break; case LET: <START> newVar = IR.var(nameToSplit); <END> break; case CONST: newVar = IR.var(nameToSplit); break; } newVar.useSourceInfoFrom(var); var.getParent().addChildBefore(newVar, var); } }</code><technical_language>create const declarations here</technical_language>

Target:
private void splitMultipleDeclarations(Node var) { checkState(var.isVar() || var.isLet() || var.isConst()); while (var.getSecondChild() != null) { Node newVar = new Node(var.getToken(), var.removeFirstChild()); newVar.useSourceInfoFrom(var); var.getParent().addChildBefore(newVar, var); } }
Source:
<code>public void onPause() { <START> disposables.dispose(); <END> }</code><technical_language>If do disposables = null re-create is null dispose() works well. clear() means re-use it, if want</technical_language>

Target:
public void onPause() { compositeDisposable.clear(); }
Source:
<code>private void registerRepositoryInfoType(NodeTypeManager typeManager) throws RepositoryException { NodeTypeTemplate type = typeManager.createNodeTypeTemplate(); type.setName("cmis:repository"); type.setAbstract(false); type.setMixin(true); type.setOrderableChildNodes(true); type.setQueryable(true); <START> type.setDeclaredSuperTypeNames(new String[]{"nt:folder"}); <END> PropertyDefinitionTemplate vendorName = typeManager.createPropertyDefinitionTemplate(); vendorName.setAutoCreated(false); vendorName.setName("cmis:vendorName"); vendorName.setMandatory(false); type.getPropertyDefinitionTemplates().add(vendorName); PropertyDefinitionTemplate productName = typeManager.createPropertyDefinitionTemplate(); productName.setAutoCreated(false); productName.setName("cmis:productName"); productName.setMandatory(false); type.getPropertyDefinitionTemplates().add(productName); PropertyDefinitionTemplate productVersion = typeManager.createPropertyDefinitionTemplate(); productVersion.setAutoCreated(false); productVersion.setName("cmis:productVersion"); productVersion.setMandatory(false); type.getPropertyDefinitionTemplates().add(productVersion); NodeTypeDefinition[] nodeDefs = new NodeTypeDefinition[] {type}; typeManager.registerNodeTypes(nodeDefs, true); }</code><technical_language>java type.setDeclaredSuperTypeNames(new String[]{JcrConstants.NT_FOLDER});</technical_language>

Target:
private void registerRepositoryInfoType(NodeTypeManager typeManager) throws RepositoryException { NodeTypeTemplate type = typeManager.createNodeTypeTemplate(); type.setName("cmis:repository"); type.setAbstract(false); type.setMixin(true); type.setOrderableChildNodes(true); type.setQueryable(true); type.setDeclaredSuperTypeNames(new String[]{JcrConstants.NT_FOLDER}); PropertyDefinitionTemplate vendorName = typeManager.createPropertyDefinitionTemplate(); vendorName.setAutoCreated(false); vendorName.setName("cmis:vendorName"); vendorName.setMandatory(false); type.getPropertyDefinitionTemplates().add(vendorName); PropertyDefinitionTemplate productName = typeManager.createPropertyDefinitionTemplate(); productName.setAutoCreated(false); productName.setName("cmis:productName"); productName.setMandatory(false); type.getPropertyDefinitionTemplates().add(productName); PropertyDefinitionTemplate productVersion = typeManager.createPropertyDefinitionTemplate(); productVersion.setAutoCreated(false); productVersion.setName("cmis:productVersion"); productVersion.setMandatory(false); type.getPropertyDefinitionTemplates().add(productVersion); NodeTypeDefinition[] nodeDefs = new NodeTypeDefinition[]{type}; typeManager.registerNodeTypes(nodeDefs, true); }
Source:
<code>private void init() { mZoomableController = createZoomableController(); mZoomableController.setListener(mZoomableListener); mTapGestureDetector = new GestureDetector(getContext(), mTapListenerWrapper); <START> mTapGestureDetector.setOnDoubleTapListener(new GestureDetector.OnDoubleTapListener() { <END> @Override public boolean onSingleTapConfirmed(MotionEvent e) { return false; } @Override public boolean onDoubleTap(MotionEvent e) { float maxScaleFactor = ((DefaultZoomableController) mZoomableController).getMaxScaleFactor(); RectF bounds = ((DefaultZoomableController) mZoomableController).getImageBounds(); float x = e.getX(); float y = e.getY(); PointF imagePoint = new PointF((x - bounds.left) / bounds.width(), (y - bounds.top) / bounds.height()); float scaleFactor = mZoomableController.getScaleFactor() < maxScaleFactor ? maxScaleFactor : ((DefaultZoomableController) mZoomableController).getMinScaleFactor(); if (mZoomableController instanceof AbstractAnimatedZoomableController) { ((AbstractAnimatedZoomableController) mZoomableController).zoomToPoint(scaleFactor, imagePoint, new PointF(x, y), DefaultZoomableController.LIMIT_ALL, 200, null); } else { ((DefaultZoomableController) mZoomableController).zoomToPoint(scaleFactor, imagePoint, new PointF(x, y)); } return true; } @Override public boolean onDoubleTapEvent(MotionEvent e) { return false; } }); }</code><technical_language>this settable ZoomableDraweeView instead a separate class for double tap listener</technical_language>

Target:
private void init() { mZoomableController = createZoomableController(); mZoomableController.setListener(mZoomableListener); mTapGestureDetector = new GestureDetector(getContext(), mTapListenerWrapper); }