auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private DataTableType createDataTableType(Method method) { Class returnType = TypeResolver.resolveRawArguments(DataTableDefinitionBody.class, body.getClass())[0]; Type[] parameterTypes = method.getGenericParameterTypes(); Type parameterType = parameterTypes[0]; if (Map.class.equals(parameterType)) { return new DataTableType( returnType, (TableEntryTransformer<Object>) this::execute ); } else { return new DataTableType( returnType, <START> (TableTransformer<Object>) this::execute <END> ); } }</code><technical_language>[Coveralls is coverage for this branch](<LINK_0> [JavaDataTableTypeDefinition.createDataTableType](<LINK_1> I some options missing</technical_language>

Target:
private DataTableType createDataTableType(Method method) { Class returnType = TypeResolver.resolveRawArguments(DataTableEntryDefinitionBody.class, body.getClass())[0]; Type[] parameterTypes = method.getGenericParameterTypes(); Type parameterType = parameterTypes[0]; if (DataTable.class.equals(parameterType)) { return new DataTableType( returnType, (TableTransformer<Object>) this::execute); } if (List.class.equals(parameterType)) { return new DataTableType(returnType, (TableRowTransformer<Object>) this::execute); } if (Map.class.equals(parameterType)) { return new DataTableType(returnType, (TableEntryTransformer<Object>) this::execute); } if (String.class.equals(parameterType)) { return new DataTableType(returnType, (TableCellTransformer<Object>) this::execute); } return new DataTableType(returnType, (TableTransformer<Object>) this::execute); }
Source:
<code>public String toString() { <START> return Objects.toStringHelper(CreateJobResponse.class) <END> .add("status", status) .add("errors", errors) .add("id", id) .toString(); }</code><technical_language>call getClass(), this invariably copied later, do right thing? others also</technical_language>

Target:
public String toString() { return Objects.toStringHelper(getClass()) .add("status", status) .add("errors", errors) .add("id", id) .toString(); }
Source:
<code>private boolean isPublisherAheadByMax() { boolean ahead = false; if (backPressureEnabled) { <START> int blocks = MAX_COUNT_OF_INMEM_BLOCKS + 1; <END> synchronized (DataList.this) { for (Block curr = this; !ahead && (curr != null); curr = curr.next) { ahead = (--blocks <= 0); } } } return ahead; }</code><technical_language>release called Subscriber disconnects iterator is closed, is Subscriber holds Publisher. is necessary do 2 stage processing similar is done in areSubscribersBehindByMax: find block positive reference count if Publisher is max block of it</technical_language>

Target:
private boolean isPublisherAheadByMax() { boolean ahead = false; if (backPressureEnabled) { int blocks = MAX_COUNT_OF_INMEM_BLOCKS; synchronized (DataList.this) { Block curr = this.next; while ((curr != null) && (curr.refCount.get() == 0)) { curr = curr.next; } while (!ahead && (curr != null)) { ahead = (--blocks == 0); curr = curr.next; } } } return ahead; }
Source:
<code>public void prepareRun(BatchSourceContext context) throws Exception { Job job = context.getHadoopJob(); Configuration conf = job.getConfiguration(); ConfigHelper.setInputColumnFamily(conf, config.keyspace, config.columnFamily); ConfigHelper.setInputInitialAddress(conf, config.initialAddress); ConfigHelper.setInputPartitioner(conf, config.partitioner); ConfigHelper.setInputRpcPort(conf, config.port); Preconditions.checkArgument(!(Strings.isNullOrEmpty(config.username) ^ Strings.isNullOrEmpty(config.password)), <START> "You must either set both username and password or neither username or password. " + <END> "Currently, they are username: " + config.username + " and password: " + config.password); if (!Strings.isNullOrEmpty(config.username)) { ConfigHelper.setInputKeyspaceUserNameAndPassword(conf, config.username, config.password); } if (!Strings.isNullOrEmpty(config.properties)) { for (String pair : config.properties.split(",")) { conf.set(pair.split(":")[0], pair.split(":")[1]); } } CqlConfigHelper.setInputCql(conf, config.query); job.setInputFormatClass(CqlInputFormat.class); }</code><technical_language>username password. (assuming is meant. set both, none; right?)</technical_language>

Target:
public void prepareRun(BatchSourceContext context) throws Exception { Job job = context.getHadoopJob(); Configuration conf = job.getConfiguration(); ConfigHelper.setInputColumnFamily(conf, config.keyspace, config.columnFamily); ConfigHelper.setInputInitialAddress(conf, config.initialAddress); ConfigHelper.setInputPartitioner(conf, config.partitioner); ConfigHelper.setInputRpcPort(conf, config.port); Preconditions.checkArgument(!(Strings.isNullOrEmpty(config.username) ^ Strings.isNullOrEmpty(config.password)), "You must either set both username and password or neither username nor password. " + "Currently, they are username: " + config.username + " and password: " + config.password); if (!Strings.isNullOrEmpty(config.username)) { ConfigHelper.setInputKeyspaceUserNameAndPassword(conf, config.username, config.password); } if (!Strings.isNullOrEmpty(config.properties)) { for (String pair : config.properties.split(",")) { conf.set(pair.split(":")[0], pair.split(":")[1]); } } CqlConfigHelper.setInputCql(conf, config.query); job.setInputFormatClass(CqlInputFormat.class); }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_manage_appointment_blocks); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { <START> getSupportActionBar().setElevation(0); <END> getSupportActionBar().setDisplayHomeAsUpEnabled(true); } ManageAppointmentBlocksFragment manageAppointmentBlocksFragment = (ManageAppointmentBlocksFragment) getSupportFragmentManager().findFragmentById(R.id.manageAppointmentBlocksContentFrame); if (manageAppointmentBlocksFragment == null) { manageAppointmentBlocksFragment = ManageAppointmentBlocksFragment.newInstance(); } if (!manageAppointmentBlocksFragment.isActive()) { addFragmentToActivity(getSupportFragmentManager(), manageAppointmentBlocksFragment, R.id.manageAppointmentBlocksContentFrame); } mPresenter = new ManageAppointmentBlocksPresenter(manageAppointmentBlocksFragment); }</code><technical_language>checked actionBar is null, actionBar instead of getSupportActionBar() prevent chance of error</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_manage_appointment_blocks); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setElevation(0); actionBar.setDisplayHomeAsUpEnabled(true); } ManageAppointmentBlocksFragment manageAppointmentBlocksFragment = (ManageAppointmentBlocksFragment) getSupportFragmentManager().findFragmentById(R.id.manageAppointmentBlocksContentFrame); if (manageAppointmentBlocksFragment == null) { manageAppointmentBlocksFragment = ManageAppointmentBlocksFragment.newInstance(); } if (!manageAppointmentBlocksFragment.isActive()) { addFragmentToActivity(getSupportFragmentManager(), manageAppointmentBlocksFragment, R.id.manageAppointmentBlocksContentFrame); } mPresenter = new ManageAppointmentBlocksPresenter(manageAppointmentBlocksFragment); }
Source:
<code>default <T> @Nullable T getFieldValue(@NonNull Class<T> type, @NonNull String @NonNull ... fieldName) { ITmfEventField field = getField(fieldName); if (field == null) { return null; } Object value = field.getValue(); if (value == null) { return null; } if (type.isAssignableFrom(value.getClass())) { @SuppressWarnings("unchecked") T ret = (T) value; return ret; } String strVal = String.valueOf(value); if (type.equals(String.class)) { @SuppressWarnings("unchecked") T ret = (T) strVal; return ret; } <START> if (type.equals(Long.class)) { <END> Long longVal = Longs.tryParse(strVal); if (longVal != null) { @SuppressWarnings("unchecked") T ret = (T) longVal; return ret; } return null; } if (type.equals(Integer.class)) { Integer intVal = Ints.tryParse(strVal); if (intVal != null) { @SuppressWarnings("unchecked") T ret = (T) intVal; return ret; } return null; } return null; }</code><technical_language>a Number, issue a long is int is if is a long, asking for Integer.class find it? I sense type is a number, butyou need floating point numbers handled (tryParse...)</technical_language>

Target:
default <T> @Nullable T getFieldValue(@NonNull Class<T> type, @NonNull String @NonNull ... fieldName) { ITmfEventField field = getField(fieldName); if (field == null) { return null; } Object value = field.getValue(); if (value == null) { return null; } if (type.isAssignableFrom(value.getClass())) { @SuppressWarnings("unchecked") T ret = (T) value; return ret; } if (type.equals(String.class)) { @SuppressWarnings("unchecked") T ret = (T) String.valueOf(value); return ret; } if (type.equals(Long.class)) { if (Number.class.isAssignableFrom(value.getClass())) { @SuppressWarnings("unchecked") T ret = (T) ((Long) ((Number) value).longValue()); return ret; } Long longVal = Longs.tryParse(String.valueOf(value)); if (longVal != null) { @SuppressWarnings("unchecked") T ret = (T) longVal; return ret; } return null; } if (type.equals(Integer.class)) { if (Number.class.isAssignableFrom(value.getClass())) { @SuppressWarnings("unchecked") T ret = (T) ((Integer) ((Number) value).intValue()); return ret; } Integer intVal = Ints.tryParse(String.valueOf(value)); if (intVal != null) { @SuppressWarnings("unchecked") T ret = (T) intVal; return ret; } return null; } if (type.equals(Double.class)) { if (Number.class.isAssignableFrom(value.getClass())) { @SuppressWarnings("unchecked") T ret = (T) ((Double) ((Number) value).doubleValue()); return ret; } Double dblVal = Doubles.tryParse(String.valueOf(value)); if (dblVal != null) { @SuppressWarnings("unchecked") T ret = (T) dblVal; return ret; } return null; } return null; }
Source:
<code>public void syncPostBatch(final String topicId, final List<BatchItem> batchItems) throws EventPublishingException { final Producer<String, String> producer = kafkaFactory.takeProducer(); try { final Map<String, String> partitionToBroker = producer.partitionsFor(topicId).stream() .collect(Collectors.toMap(p -> String.valueOf(p.partition()),p -> String.valueOf(p.leader().id()))); batchItems.forEach(item -> { Preconditions.checkNotNull( item.getPartition(), "BatchItem partition can't be null at the moment of publishing!"); item.setBrokerId(partitionToBroker.get(item.getPartition())); item.setTopic(topicId); }); final List<ProducerSendCommand.NakadiCallback> callbacks = batchItems.stream() .peek(item -> item.setStep(EventPublishingStep.PUBLISHING)) <START> .map(item -> new ProducerSendCommand(producer, item).execute()) <END> .filter(Objects::nonNull) .collect(Collectors.toList()); waitCallbacksCompleted(producer, callbacks, createSendTimeout()); for (final BatchItem batchItem: batchItems) { if (batchItem.getResponse().getPublishingStatus() == EventPublishingStatus.FAILED) throw new EventPublishingException("Error publishing message to kafka"); } } finally { kafkaFactory.releaseProducer(producer); } }</code><technical_language>@adyach I this late feedback. afraid creating ProducerSendCommand item short circuit early. some batches hundreds of events. If batch times out, open circuit caused a single request. If case, is for disable Hystrix? I mean, if hypothesis is proven true open circuits want open, is disable hystrix</technical_language>

Target:
public void syncPostBatch(final String topicId, final List<BatchItem> batchItems) throws EventPublishingException { final Producer<String, String> producer = kafkaFactory.takeProducer(); try { final Map<String, String> partitionToBroker = producer.partitionsFor(topicId).stream() .collect(Collectors.toMap(p -> String.valueOf(p.partition()),p -> String.valueOf(p.leader().id()))); batchItems.forEach(item -> { Preconditions.checkNotNull( item.getPartition(), "BatchItem partition can't be null at the moment of publishing!"); item.setBrokerId(partitionToBroker.get(item.getPartition())); item.setTopic(topicId); }); final List<ProducerSendCommand.NakadiCallback> callbacks = batchItems.stream() .peek(item -> item.setStep(EventPublishingStep.PUBLISHING)) .map(item -> new ProducerSendCommand(producer, item).execute()) .filter(Objects::nonNull) .collect(Collectors.toList()); waitCallbacksCompleted(producer, callbacks, createSendTimeout()); for (final BatchItem batchItem: batchItems) { if (batchItem.getResponse().getPublishingStatus() == EventPublishingStatus.FAILED) throw new EventPublishingException("Error publishing message to kafka"); } } catch (final HystrixRuntimeException hre) { LOG.debug("Failed to send bacth to kafka due to {}", hre.getFailureType(), hre); throw new EventPublishingException("Error publishing message to kafka", hre); } finally { kafkaFactory.releaseProducer(producer); } }
Source:
<code>public boolean exists() { OverriddenBooleanValue overriden = null; if ( decorator != null ) { <START> overriden = decorator.decorateExists( this, new EventMetadata( ) ); <END> } if ( ( overriden != null ) && overriden.overrides() ) { return overriden.getResult(); } else { return provider.exists( resource ); } }</code><technical_language>some point need a variant of exists() accepts EventMetadata parameter, in case existence decorator needs if a path special properties scope of some package type. critical now</technical_language>

Target:
public boolean exists() { return exists( new EventMetadata() ); }
Source:
<code>public void testFLTEquivalence() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { TmfTimestampTransformLinear precise = new TmfTimestampTransformLinear(Math.PI, 0); TmfTimestampTransformLinearFast fast = new TmfTimestampTransformLinearFast(Math.PI, 0); Field field = fast.getClass().getDeclaredField("fDeltaMax"); field.setAccessible(true); <START> long deltaMax = field.getLong(fast); <END> long start = (ts - (ts % deltaMax) - 10); checkTime(precise, fast, 20, start, 1); }</code><technical_language>hardcode start time, instead of reflection</technical_language>

Target:
public void testFLTEquivalence() throws SecurityException, IllegalArgumentException { TmfTimestampTransformLinearFast fast = new TmfTimestampTransformLinearFast(Math.PI, 0); TmfTimestampTransformLinearFast fast2 = new TmfTimestampTransformLinearFast(Math.PI, 0); long deltaMax = getPrivateFieldLong(fast, "fDeltaMax"); long start = (ts - (ts % deltaMax) - 10); checkTime(fast, fast2, 20, start, 1); }
Source:
<code>public void testDeleteAsyncQuery() { ArgumentCaptor<FilterExpression> filterCaptor = ArgumentCaptor.forClass(FilterExpression.class); cleanerThread.deleteAsyncQuery(); verify(asyncQueryDao, times(1)).deleteAsyncQueryAndResultCollection(filterCaptor.capture()); <START> Long date = System.currentTimeMillis() - (cleanerThread.getQueryCleanupDays() * 24 * 3600 * 1000); <END> assertEquals("asyncQuery.createdOn LE [" + new Date(date) + "]", filterCaptor.getValue().toString()); }</code><technical_language>for this test fail of a 1ms gap this date is calculated delete filter is generated. need find a brittle approach</technical_language>

Target:
public void testDeleteAsyncQuery() { when(dateUtil.calculateFilterDate(Calendar.DATE, cleanerThread.getQueryCleanupDays())).thenReturn(testDate); ArgumentCaptor<FilterExpression> filterCaptor = ArgumentCaptor.forClass(FilterExpression.class); cleanerThread.deleteAsyncQuery(); verify(asyncQueryDao, times(1)).deleteAsyncQueryAndResultCollection(filterCaptor.capture()); assertEquals("asyncQuery.createdOn LE [" + testDate + "]", filterCaptor.getValue().toString()); }
Source:
<code>private Tumor getTumor(JSONObject jsonObject, String oncoTreeCode){ <START> Tumor tumor = new Tumor(); <END> if (jsonObject.containsKey(oncoTreeCode)){ JSONObject tumorObj = (JSONObject)jsonObject.get(oncoTreeCode); tumor.setNciCode((String)tumorObj.get("nciCode")); tumor.setNciMainType((String)tumorObj.get("nciMainType")); tumor.setTumorName((String)tumorObj.get("tumorName")); JSONArray trialsArr = (JSONArray)tumorObj.get("trials"); Trial[] trials = getTrials(trialsArr); tumor.setTrials(trials); } return tumor; }</code><technical_language>matching slash</technical_language>

Target:
private Tumor getTumor(JSONObject jsonObject, String oncoTreeCode){ Tumor tumor = new Tumor(); if (jsonObject.containsKey(oncoTreeCode)){ JSONObject tumorObj = (JSONObject)jsonObject.get(oncoTreeCode); Gson gson = new Gson(); tumor = gson.fromJson(tumorObj.toString(), Tumor.class); } return tumor; }
Source:
<code><START> protected Bitmap getBitmapFromResourceId(int resourceId) { <END> return BitmapFactory.decodeResource(context.getResources(), resourceId); }</code><technical_language>suggestion /* package */ Bitmap getBitmapFromResourceId(int resourceId) {</technical_language>

Target:
Bitmap getBitmapFromResourceId(int resourceId) { return BitmapFactory.decodeResource(mContext.getResources(), resourceId); }
Source:
<code>public void onSetDead(CallbackInfo ci) { net.minecraft.entity.Entity mcEntity = (net.minecraft.entity.Entity) (Object) this; if (!this.world.isRemote && (!(mcEntity instanceof EntityLivingBase) || (mcEntity instanceof EntityArmorStand))) { IMixinWorldServer spongeWorld = (IMixinWorldServer) this.world; final CauseTracker causeTracker = spongeWorld.getCauseTracker(); PhaseData phaseData = causeTracker.getCurrentPhaseData(); Cause.Builder causeBuilder = Cause.builder(); Optional<Object> sourceOptional = phaseData.context.getSource(Object.class); sourceOptional.ifPresent(source -> { causeBuilder.named(NamedCause.source(source)); if (source instanceof Projectile) { ProjectileSource projectileSource = ((Projectile) source).getShooter(); causeBuilder.named(NamedCause.of(NamedCause.THROWER, projectileSource)); } }); <START> Optional<ItemStack> usedItemOptional = phaseData.context.firstNamed("ItemUsed", ItemStack.class); <END> usedItemOptional.ifPresent(item -> causeBuilder.named(NamedCause.of("ItemUsed", item))); phaseData.context.getOwner().ifPresent(owner -> causeBuilder.named(NamedCause.owner(owner))); this.destructCause = causeBuilder.build(); } }</code><technical_language>constants InternalNamedCauses, avoids issues refactoring changes</technical_language>

Target:
private void onSetDead(CallbackInfo ci) { if (ShouldFire.DESTRUCT_ENTITY_EVENT && !((IMixinWorld) this.world).isFake() && !(EntityUtil.toNative(this) instanceof EntityLiving)) { MessageChannel originalChannel = MessageChannel.TO_NONE; try (final CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) { DestructEntityEvent event = SpongeEventFactory.createDestructEntityEvent( frame.getCurrentCause(), originalChannel, Optional.of(originalChannel), new MessageEvent.MessageFormatter(), this, true ); this.destructEvent = event; } } }
Source:
<code>public static int getTcpBacklog(int tcpBacklog) { return AccessController.doPrivileged(new PrivilegedAction<Integer>() { @Override <START> public Integer run() { <END> int somaxconn = tcpBacklog; File file = new File(TCP_BACKLOG_SETTING_LOCATION); BufferedReader in = null; try { if (file.exists()) { in = new BufferedReader(new InputStreamReader(new FileInputStream(file), Charset.forName("UTF-8"))); somaxconn = Integer.parseInt(in.readLine()); } } catch (SecurityException | IOException | NumberFormatException e) { } finally { if (in != null) { try { in.close(); } catch (Exception e) { } } } return somaxconn; } }); }</code><technical_language>do feel implementation: java try { final File file = new File(TCP_BACKLOG_SETTING_LOCATION); return Integer.parseInt(Files.toString(file, Charsets.UTF_8)); } catch (SecurityException | IOException | NumberFormatException e) { } return tcpBacklog; a bit shorter</technical_language>

Target:
public static int getTcpBacklog(int tcpBacklog) { return AccessController.doPrivileged(new PrivilegedAction<Integer>() { @Override public Integer run() { int somaxconn = tcpBacklog; try { String setting = Files.toString(new File(TCP_BACKLOG_SETTING_LOCATION), Charsets.UTF_8); somaxconn = Integer.parseInt(setting.trim()); } catch (SecurityException | IOException | NumberFormatException | NullPointerException e) { } finally { return somaxconn; } } }); }
Source:
<code>protected void init() throws IOException { _selector = Selector.open(); try { _clientConnection = SocketChannel.open(); LOGGER.info("Connecting to " + _host + ":" + _port); final InetSocketAddress peerAddr = new InetSocketAddress(_host, _port); _clientConnection.connect(peerAddr); <START> Thread.sleep(3600000); <END> } catch (final IOException e) { _selector.close(); throw e; } catch (InterruptedException e) { LOGGER.debug(e.getMessage()); } }</code><technical_language>@bhaisaab I recommend extracting this a variable; waiting time big, is necessary wait hour? Thanks</technical_language>

Target:
protected void init() throws IOException { _selector = Selector.open(); try { _clientConnection = SocketChannel.open(); LOGGER.info("Connecting to " + _host + ":" + _port); final InetSocketAddress peerAddr = new InetSocketAddress(_host, _port); _clientConnection.connect(peerAddr); Thread.sleep(Long.MAX_VALUE); } catch (final IOException e) { _selector.close(); throw e; } catch (InterruptedException e) { LOGGER.debug(e.getMessage()); } }
Source:
<code>@NonNull public static AppContentProviderEndpoint of(@NonNull Uri uri) { int code = URI_TO_CODE.match(uri); <START> if (code == -1) { <END> throw new IllegalArgumentException("uri=" + uri); } return of(code); }</code><technical_language>considered UriMatcher.NO_MATCH instead of -1 here</technical_language>

Target:
@NonNull public static AppContentProviderEndpoint of(@NonNull Uri uri) { int code = URI_TO_CODE.match(uri); if (code == UriMatcher.NO_MATCH) { throw new IllegalArgumentException("uri=" + uri); } return of(code); }
Source:
<code>public void setUp() throws Exception { junitPlayer = PlayerBuilder.create("JUnit").defaultValues().get(); <START> instance = new GameService(new ClientProperties(), fafService, forgedAllianceService, mapService, <END> preferencesService, gameUpdater, notificationService, i18n, executor, playerService, reportingService, eventBus, iceAdapter, modService, platformService, discordRichPresenceService, replayService); Preferences preferences = new Preferences(); when(preferencesService.getPreferences()).thenReturn(preferences); when(fafService.connectionStateProperty()).thenReturn(new SimpleObjectProperty<>()); when(replayService.start(anyInt(), any())).thenReturn(completedFuture(LOCAL_REPLAY_PORT)); when(iceAdapter.start()).thenReturn(completedFuture(GPG_PORT)); when(playerService.getCurrentPlayer()).thenReturn(Optional.of(junitPlayer)); doAnswer(invocation -> { try { ((Runnable) invocation.getArgument(0)).run(); } catch (Exception e) { e.printStackTrace(); } return null; }).when(executor).execute(any()); instance.afterPropertiesSet(); verify(fafService).addOnMessageListener(eq(GameInfoMessage.class), gameInfoMessageListenerCaptor.capture()); }</code><technical_language>need for changing this do u change it</technical_language>

Target:
public void setUp() throws Exception { junitPlayer = PlayerBuilder.create("JUnit").defaultValues().get(); ClientProperties clientProperties = new ClientProperties(); instance = new GameService(clientProperties, fafService, forgedAllianceService, mapService, preferencesService, gameUpdater, notificationService, i18n, executor, playerService, reportingService, eventBus, iceAdapter, modService, platformService, discordRichPresenceService, replayService); Preferences preferences = new Preferences(); when(preferencesService.getPreferences()).thenReturn(preferences); when(fafService.connectionStateProperty()).thenReturn(new SimpleObjectProperty<>()); when(replayService.start(anyInt(), any())).thenReturn(completedFuture(LOCAL_REPLAY_PORT)); when(iceAdapter.start()).thenReturn(completedFuture(GPG_PORT)); when(playerService.getCurrentPlayer()).thenReturn(Optional.of(junitPlayer)); doAnswer(invocation -> { try { ((Runnable) invocation.getArgument(0)).run(); } catch (Exception e) { e.printStackTrace(); } return null; }).when(executor).execute(any()); instance.afterPropertiesSet(); verify(fafService).addOnMessageListener(eq(GameInfoMessage.class), gameInfoMessageListenerCaptor.capture()); }
Source:
<code><START> public void shouldTimeout() { <END> try { webTestClient.get() .uri("/timeout/{timeout}", 3) .exchange(); Assert.fail(); } catch (ReadTimeoutException ignore) { } }</code><technical_language>this sounds a bit hacky, create a junit rule call record rule.expect(ReadTimeoutException.class)</technical_language>

Target:
public void shouldTimeout() { exception.expect(ReadTimeoutException.class); webTestClient.get() .uri("/timeout/{timeout}", 3) .exchange(); }
Source:
<code>public void testCardinalityManyColumns() { <START> long blockSize = 254; <END> long uniqueElts = 1000 * blockSize; String projection = getCardinalityProjection(getUniqueElements((int) blockSize, uniqueElts)); double error = uniqueElts * 0.05; functionAssertions.assertFunctionWithError(projection, BIGINT, uniqueElts, error); }</code><technical_language>block size int avoid cast</technical_language>

Target:
public void testCardinalityManyColumns() { int blockSize = 254; long uniqueElements = 1000 * blockSize; double error = uniqueElements * 0.05; String projection = getCardinalityProjection(getUniqueElements(blockSize, uniqueElements)); functionAssertions.assertFunctionWithError(projection, BIGINT, uniqueElements, error); }
Source:
<code><START> private static File[] splitDexPath(String path) { <END> List<File> result = splitPaths(path, null, false); return result.toArray(new File[result.size()]); }</code><technical_language>is rationale for changing this return type File[] ? I easier this.dexFiles a List<File> getDexFiles() return a List<File></technical_language>

Target:
private static List<File> splitDexPath(String path) { return splitPaths(path, null, false); }
Source:
<code>private void endTransaction(BinlogEventV4 e) { LOG.info("Ending transaction " + _scn); if (_eventsInTransaction.size() > 0) { DatastreamProducerRecordBuilder builder = new DatastreamProducerRecordBuilder(); builder.setPartition(0); String checkpoint = MysqlCheckpoint.createCheckpointString(_sourceId, _scn, _currFileName, _mostRecentSeenEventPosition); builder.setSourceCheckpoint(checkpoint); _eventsInTransaction.forEach(builder::addEvent); Optional<Long> eventTimestamp = Optional.ofNullable(_eventsInTransaction.get(0)) .map(firstEvent -> firstEvent.metadata) .map(metadata -> metadata.get(DatastreamEventMetadata.EVENT_TIMESTAMP)) .map(metaVal -> Long.valueOf(metaVal.toString())); if (eventTimestamp.isPresent()) { builder.setEventsTimestamp(eventTimestamp.get()); } else { String errorMsg = "Datastream event " + _eventsInTransaction.get(0).toString() + " was missing event timestamp metadata."; LOG.error(errorMsg); <START> throw new IllegalStateException(errorMsg); <END> } _producer.send(builder.build(), (metadata, exception) -> { if (exception == null) { LOG.debug(String.format("Sending event succeeded, metadata:{%s}", metadata)); } else { LOG.error(String.format("Sending event failed, metadata:{%s}", metadata), exception); } }); } resetTransactionData(); }</code><technical_language>nit: I a DatastreamRuntimeException is more appropriate</technical_language>

Target:
private void endTransaction(BinlogEventV4 e) { LOG.info("Ending transaction " + _scn); if (_eventsInTransaction.size() > 0) { DatastreamProducerRecordBuilder builder = new DatastreamProducerRecordBuilder(); builder.setPartition(0); String checkpoint = MysqlCheckpoint.createCheckpointString(_sourceId, _scn, _currFileName, _mostRecentSeenEventPosition); builder.setSourceCheckpoint(checkpoint); _eventsInTransaction.forEach(builder::addEvent); Optional<Long> eventTimestamp = Optional.ofNullable(_eventsInTransaction.get(0)) .map(firstEvent -> firstEvent.metadata) .map(metadata -> metadata.get(DatastreamEventMetadata.EVENT_TIMESTAMP)) .map(metaVal -> Long.valueOf(metaVal.toString())); if (eventTimestamp.isPresent()) { builder.setEventsTimestamp(eventTimestamp.get()); } else { String errorMsg = "Datastream event " + _eventsInTransaction.get(0).toString() + " was missing event timestamp metadata."; LOG.error(errorMsg); throw new DatastreamRuntimeException(errorMsg); } _producer.send(builder.build(), (metadata, exception) -> { if (exception == null) { LOG.debug(String.format("Sending event succeeded, metadata:{%s}", metadata)); } else { LOG.error(String.format("Sending event failed, metadata:{%s}", metadata), exception); } }); } resetTransactionData(); }
Source:
<code>protected void resetSnapshotIndex(RaftMemberContext member, AppendResponse response) { final long snapshotIndex = response.lastSnapshotIndex(); if (member.getSnapshotIndex() != snapshotIndex) { member.setSnapshotIndex(snapshotIndex); <START> log.trace("Reset snapshot index for to {}", member, snapshotIndex); <END> } }</code><technical_language>warn @kuujo suggested</technical_language>

Target:
protected void resetSnapshotIndex(RaftMemberContext member, AppendResponse response) { final long snapshotIndex = response.lastSnapshotIndex(); if (member.getSnapshotIndex() != snapshotIndex) { member.setSnapshotIndex(snapshotIndex); log.warn("Reset snapshot index for to {}", member, snapshotIndex); } }
Source:
<code>public void testFlashBrick() { checkIfBrickAtPositionShowsString(0, R.string.brick_when_started); checkIfBrickAtPositionShowsString(brickPosition, R.string.brick_flash); checkIfSpinnerOnBrickAtPositionShowsString(R.id.brick_flash_spinner, brickPosition, R.string.brick_flash_on); onView(withId(R.id.brick_flash_spinner)).perform(click()); <START> onView(withText(R.string.brick_flash_off)).perform(click()); <END> onView(withText(R.string.brick_flash_off)).check(matches(isDisplayed())); onView(withId(R.id.brick_flash_spinner)).perform(click()); onView(withText(R.string.brick_flash_on)).perform(click()); onView(withText(R.string.brick_flash_on)).check(matches(isDisplayed())); }</code><technical_language>please reference brick spinner accessing, in line 66</technical_language>

Target:
public void testFlashBrick() { checkIfBrickAtPositionShowsString(0, R.string.brick_when_started); checkIfBrickAtPositionShowsString(brickPosition, R.string.brick_flash); checkIfSpinnerOnBrickAtPositionShowsString(R.id.brick_flash_spinner, brickPosition, R.string.brick_flash_on); clickSelectCheckSpinnerValueOnBrick(R.id.brick_flash_spinner, brickPosition, R.string .brick_flash_off); checkIfSpinnerOnBrickAtPositionShowsString(R.id.brick_flash_spinner, brickPosition, R.string.brick_flash_off); clickSelectCheckSpinnerValueOnBrick(R.id.brick_flash_spinner, brickPosition, R.string .brick_flash_on); checkIfSpinnerOnBrickAtPositionShowsString(R.id.brick_flash_spinner, brickPosition, R.string.brick_flash_on); }
Source:
<code>public void positionedRead() throws Exception { AlluxioURI path = new AlluxioURI(mFilePath); FileSystemTestUtils.createByteFile( mFileSystem, mFilePath, WritePType.MUST_CACHE, PAGE_SIZE_BYTES); try (FileInStream stream = mFileSystem.openFile(path)) { byte[] buffer = new byte[PAGE_SIZE_BYTES / 4]; int bytesRead = stream.positionedRead(PAGE_SIZE_BYTES / 10, buffer, 0, buffer.length); assertEquals(buffer.length, bytesRead); assertTrue(BufferUtils.equalIncreasingByteArray(PAGE_SIZE_BYTES / 10, buffer.length, buffer)); } URIStatus status = mFileSystem.getStatus(path); try (ReadableByteChannel channel = mCacheManager.get(new PageId(status.getFileId(), 0))) { assertNotNull(channel); assertTrue(BufferUtils.equalIncreasingByteArray( PAGE_SIZE_BYTES, ByteStreams.toByteArray(Channels.newInputStream(channel)))); } mClusterResource.get().stopWorkers(); <START> try (InputStream stream = mFileSystem.openFile(path)) { <END> assertTrue(BufferUtils.equalIncreasingByteArray( PAGE_SIZE_BYTES, ByteStreams.toByteArray(stream))); } }</code><technical_language>removed try (ReadableByteChannel channel = mCacheManager.get(new PageId(status.getFileId(), 0))) {...} asserting pages read</technical_language>

Target:
public void positionedRead() throws Exception { AlluxioURI path = new AlluxioURI(mFilePath); FileSystemTestUtils.createByteFile( mFileSystem, mFilePath, WritePType.MUST_CACHE, PAGE_SIZE_BYTES); try (FileInStream stream = mFileSystem.openFile(path)) { byte[] buffer = new byte[PAGE_SIZE_BYTES / 4]; int bytesRead = stream.positionedRead(PAGE_SIZE_BYTES / 10, buffer, 0, buffer.length); assertEquals(buffer.length, bytesRead); assertTrue(BufferUtils.equalIncreasingByteArray(PAGE_SIZE_BYTES / 10, buffer.length, buffer)); } mClusterResource.get().stopWorkers(); try (InputStream stream = mFileSystem.openFile(path)) { assertTrue(BufferUtils.equalIncreasingByteArray( PAGE_SIZE_BYTES, ByteStreams.toByteArray(stream))); } }
Source:
<code>protected boolean canDoAction() { boolean retValue = isVmExist(); if (retValue) { List<VM> listVms = getVmDAO().getForDisk(_oldDisk.getId()).get(Boolean.TRUE); sharedLockMap = listVms.isEmpty() ? null : new HashMap<Guid, String>(); for (VM vm : listVms) { <START> sharedLockMap.put(vm.getId(), LockingGroup.VM.name()); <END> if (vm.getstatus() != VMStatus.Down) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_VM_STATUS_ILLEGAL); return false; } } retValue = acquireLockInternal() && isDiskExist(_oldDisk) && checkCanPerformRegularUpdate(); } return retValue; }</code><technical_language>acquireLockInternal() here, a check</technical_language>

Target:
protected boolean canDoAction() { boolean retValue = isVmExist(); if (retValue) { List<VM> listVms = getVmDAO().getForDisk(_oldDisk.getId()).get(Boolean.TRUE); buidSharedLockMap(listVms); acquireLockInternal(); for (VM vm : listVms) { if (vm.getstatus() != VMStatus.Down) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_VM_STATUS_ILLEGAL); return false; } } retValue = isDiskExist(_oldDisk) && checkCanPerformRegularUpdate(); } return retValue; }
Source:
<code>public static Collection<Tile> parseClusterRecordsFromTileMetricsV3( final Collection<File> tileMetricsOutFiles, final Map<Integer, File> phasingMetricsFiles, final ReadStructure readStructure ) throws FileNotFoundException { Map<Integer, Map<Integer, Collection<TilePhasingValue>>> phasingValues = getTilePhasingValues(phasingMetricsFiles, readStructure); <START> for (File tileMetricsOutFile : tileMetricsOutFiles) { <END> TileMetricsOutReader tileMetricsIterator = new TileMetricsOutReader(tileMetricsOutFile, TileMetricsOutReader.TileMetricsVersion.THREE); final Collection<IlluminaTileMetrics> tileMetrics = determineLastValueForLaneTileMetricsCode(tileMetricsIterator); final Map<String, ? extends Collection<IlluminaTileMetrics>> locationToMetricsMap = partitionTileMetricsByLocation(tileMetrics); if (v3TileMetricsHasClusterRecordsFirstPass(locationToMetricsMap)) { final float density = tileMetricsIterator.getDensity(); return getTileClusterRecordsV3(locationToMetricsMap, phasingValues, density); } } for (File tileMetricsOutFile : tileMetricsOutFiles) { TileMetricsOutReader tileMetricsIterator = new TileMetricsOutReader(tileMetricsOutFile, TileMetricsOutReader.TileMetricsVersion.THREE); final float density = tileMetricsIterator.getDensity(); final Collection<IlluminaTileMetrics> tileMetrics = determineLastValueForLaneTileMetricsCode(tileMetricsIterator); final Map<String, ? extends Collection<IlluminaTileMetrics>> locationToMetricsMap = partitionTileMetricsByLocation(tileMetrics); final Collection<Tile> tiles = getTileClusterRecordsV3(locationToMetricsMap, phasingValues, density); if (!tiles.isEmpty()) { return tiles; } } final String pathsString = tileMetricsOutFiles .stream() .map(File::getAbsolutePath) .collect(Collectors.joining(", ")); throw new RuntimeException("None of the following input files contained cluster records:" + pathsString); }</code><technical_language>this loop</technical_language>

Target:
public static Collection<Tile> parseClusterRecordsFromTileMetricsV3( final Collection<File> tileMetricsOutFiles, final Map<Integer, File> phasingMetricsFiles, final ReadStructure readStructure ) throws FileNotFoundException { final Map<Integer, Map<Integer, Collection<TilePhasingValue>>> phasingValues = getTilePhasingValues(phasingMetricsFiles, readStructure); for (File tileMetricsOutFile : tileMetricsOutFiles) { final TileMetricsOutReader tileMetricsIterator = new TileMetricsOutReader(tileMetricsOutFile, TileMetricsOutReader.TileMetricsVersion.THREE); final float density = tileMetricsIterator.getDensity(); final Collection<IlluminaTileMetrics> tileMetrics = determineLastValueForLaneTileMetricsCode(tileMetricsIterator); final Map<String, ? extends Collection<IlluminaTileMetrics>> locationToMetricsMap = partitionTileMetricsByLocation(tileMetrics); final Collection<Tile> tiles = getTileClusterRecordsV3(locationToMetricsMap, phasingValues, density); if (!tiles.isEmpty()) { return tiles; } } final String pathsString = tileMetricsOutFiles .stream() .map(File::getAbsolutePath) .collect(Collectors.joining(", ")); throw new RuntimeException("None of the following input files contained cluster records: " + pathsString); }
Source:
<code>public long getEnd() { return <START> fXvalues[fXvalues.length]; <END> }</code><technical_language>length - 1</technical_language>

Target:
public long getEnd() { return fXvalues[Integer.max(0, fXvalues.length - 1)]; }
Source:
<code>private void writeEmailsIntoTextFile(HashSet<String> studentEmailSet, HashSet<String> instructorEmailSet) { try { File newFile = new File(filePathForSaving + this.getCurrentDateForDisplay() + ".txt"); FileOutputStream fos = new FileOutputStream(newFile); OutputStreamWriter osw = new OutputStreamWriter(fos); <START> try (Writer w = new BufferedWriter(osw)) { <END> int studentEmailCount = 0; if (!studentEmailSet.isEmpty()) { for (String email : studentEmailSet) { if (!shouldIncludeTestData && email.endsWith(".tmt")) { continue; } w.write(email + ","); studentEmailCount++; } } int instructorEmailCount = 0; if (!instructorEmailSet.isEmpty()) { for (String email : instructorEmailSet) { if (!shouldIncludeTestData && email.endsWith(".tmt")) { continue; } w.write(email + ","); instructorEmailCount++; } } System.out.print("Student email num: " + studentEmailCount + "\n"); System.out.print("Instructor email num: " + instructorEmailCount + "\n"); } } catch (IOException e) { System.err.println("Problem writing to the file statsTest.txt"); } }</code><technical_language>This is insufficient. FileOutputStream OutputStreamWriter AutoCloseable</technical_language>

Target:
private void writeEmailsIntoTextFile(HashSet<String> studentEmailSet, HashSet<String> instructorEmailSet) { try { File newFile = new File(filePathForSaving + this.getCurrentDateForDisplay() + ".txt"); try (BufferedWriter w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(newFile)))) { int studentEmailCount = 0; for (String email : studentEmailSet) { if (!shouldIncludeTestData && email.endsWith(".tmt")) { continue; } w.write(email + ","); studentEmailCount++; } int instructorEmailCount = 0; for (String email : instructorEmailSet) { if (!shouldIncludeTestData && email.endsWith(".tmt")) { continue; } w.write(email + ","); instructorEmailCount++; } System.out.print("Student email num: " + studentEmailCount + "\n"); System.out.print("Instructor email num: " + instructorEmailCount + "\n"); } } catch (IOException e) { System.err.println("Problem writing to the file statsTest.txt"); } }
Source:
<code><START> private synchronized void createSupplementaryDirectory() { <END> IFolder supplFolder = getTraceSupplementaryFolder(getResourceName()); if (!supplFolder.exists()) { try { supplFolder.create(true, true, new NullProgressMonitor()); } catch (CoreException e) { Activator.getDefault().logError("Error creating resource supplementary file " + supplFolder, e); } } try { fResource.setPersistentProperty(TmfCommonConstants.TRACE_SUPPLEMENTARY_FOLDER, supplFolder.getLocationURI().getPath()); } catch (CoreException e) { Activator.getDefault().logError("Error setting persistant property " + TmfCommonConstants.TRACE_SUPPLEMENTARY_FOLDER, e); } }</code><technical_language>is sychnronized here? synch object is TmfWithFolderElement.this. prevents is createSupplementaryDirectory() createBookmarksFile() of subclass is entered thread time for TmfWithFolderElement object</technical_language>

Target:
private void createSupplementaryDirectory() { IFolder supplFolder = getTraceSupplementaryFolder(getResourceName()); if (!supplFolder.exists()) { try { supplFolder.create(true, true, new NullProgressMonitor()); } catch (CoreException e) { Activator.getDefault().logError("Error creating resource supplementary file " + supplFolder, e); } } try { fResource.setPersistentProperty(TmfCommonConstants.TRACE_SUPPLEMENTARY_FOLDER, supplFolder.getLocationURI().getPath()); } catch (CoreException e) { Activator.getDefault().logError("Error setting persistant property " + TmfCommonConstants.TRACE_SUPPLEMENTARY_FOLDER, e); } }
Source:
<code>protected void executeCommand() { getNetwork().setId(Guid.newGuid()); NetworkUtils.setNetworkVdsmName(getNetwork()); TransactionSupport.executeInNewTransaction(() -> { networkDao.save(getNetwork()); if (getNetwork().isVmNetwork() && getParameters().isVnicProfileRequired()) { vnicProfileDao.save(networkHelper.createVnicProfile(getNetwork())); } networkHelper.addPermissionsOnNetwork(getUserId(), getNetwork().getId()); return null; }); List<NetworkCluster> networkAttachments = getParameters().getNetworkClusterList(); if (networkAttachments != null) { ActionReturnValue attachToClustersResult = attachToClusters(networkAttachments); if (!attachToClustersResult.getSucceeded()) { <START> propagateFailure(attachToClustersResult); <END> return; } } getReturnValue().setActionReturnValue(getNetwork().getId()); setSucceeded(true); }</code><technical_language>I propagation of failure improved. options - 1(preffered me). If attachment of network clusters fails, network command fail added network rollbacked. In this case network attachment in transaction adding network. (Move line 81). 2. if attachment of network fails, network rollbacked. means attachment is nice in this command. Therefore, attachment error propagated AddNetworkCommand marked succeed. attachment error printed audit log (please verify if choose this approach). In this approach I a thread for attachment, AddNetworkCommand need wait for attachment finish work</technical_language>

Target:
protected void executeCommand() { getNetwork().setId(Guid.newGuid()); NetworkUtils.setNetworkVdsmName(getNetwork()); TransactionSupport.executeInNewTransaction(() -> { networkDao.save(getNetwork()); if (getNetwork().isVmNetwork() && getParameters().isVnicProfileRequired()) { vnicProfileDao.save(networkHelper.createVnicProfile(getNetwork())); } networkHelper.addPermissionsOnNetwork(getUserId(), getNetwork().getId()); return null; }); runClusterAttachment(); getReturnValue().setActionReturnValue(getNetwork().getId()); setSucceeded(true); }
Source:
<code><START> public void process(Exchange exchange) throws Exception { <END> List<Exchange> exchanges = prepareExchangeList(exchange); List<Exchange> processGroup = new ArrayList<>(); String partitionDecorator = ""; String suffix = ""; String tableId = configuration.getTableId() == null ? "" : configuration.getTableId(); int totalProcessed = 0; for (Exchange ex: exchanges) { String tmpPartitionDecorator = ex.getIn().getHeader(GoogleBigQueryConstants.PARTITION_DECORATOR, "", String.class); String tmpSuffix = ex.getIn().getHeader(GoogleBigQueryConstants.TABLE_SUFFIX, "", String.class); String tmpTableId = ex.getIn().getHeader(GoogleBigQueryConstants.TABLE_ID, tableId, String.class); if (tmpTableId.isEmpty()) { throw new IllegalArgumentException("tableId need to be specified in one of endpoint configuration or exchange header"); } if (!tmpPartitionDecorator.equals(partitionDecorator) || !tmpSuffix.equals(suffix) || !tmpTableId.equals(tableId)) { if (!processGroup.isEmpty()) { totalProcessed += process(tableId, partitionDecorator, suffix, processGroup, exchange.getExchangeId()); } processGroup.clear(); partitionDecorator = tmpPartitionDecorator; suffix = tmpSuffix; tableId = tmpTableId; } processGroup.add(ex); } if (!processGroup.isEmpty()) { totalProcessed += process(tableId, partitionDecorator, suffix, processGroup, exchange.getExchangeId()); } if (totalProcessed == 0) { logger.debug("The incoming message is either null or empty for exchange {}", exchange.getExchangeId()); } }</code><technical_language>DefaultAsyncProducer default [wraps](<LINK_0> this process(Exchange) method calls async one, reason do</technical_language>

Target:
public void process(Exchange exchange) throws Exception { List<Exchange> exchanges = prepareExchangeList(exchange); List<Exchange> processGroup = new ArrayList<>(); String partitionDecorator = ""; String suffix = ""; String tableId = configuration.getTableId() == null ? "" : configuration.getTableId(); int totalProcessed = 0; for (Exchange ex: exchanges) { String tmpPartitionDecorator = ex.getIn().getHeader(GoogleBigQueryConstants.PARTITION_DECORATOR, "", String.class); String tmpSuffix = ex.getIn().getHeader(GoogleBigQueryConstants.TABLE_SUFFIX, "", String.class); String tmpTableId = ex.getIn().getHeader(GoogleBigQueryConstants.TABLE_ID, tableId, String.class); if (tmpTableId.isEmpty()) { throw new IllegalArgumentException("tableId need to be specified in one of endpoint configuration or exchange header"); } if (!tmpPartitionDecorator.equals(partitionDecorator) || !tmpSuffix.equals(suffix) || !tmpTableId.equals(tableId)) { if (!processGroup.isEmpty()) { totalProcessed += process(tableId, partitionDecorator, suffix, processGroup, exchange.getExchangeId()); } processGroup.clear(); partitionDecorator = tmpPartitionDecorator; suffix = tmpSuffix; tableId = tmpTableId; } processGroup.add(ex); } if (!processGroup.isEmpty()) { totalProcessed += process(tableId, partitionDecorator, suffix, processGroup, exchange.getExchangeId()); } if (totalProcessed == 0) { log.debug("The incoming message is either null or empty for exchange {}", exchange.getExchangeId()); } }
Source:
<code>private static List<Entity> generateLance(String faction, int skill, int quality, List<Integer> unitTypes, String weights, boolean artillery, Campaign campaign) { List<Entity> retval = new ArrayList<>(); for(int i = 0; i < unitTypes.size(); i++) { Entity en = getEntity(faction, skill, quality, unitTypes.get(i), <START> AtBConfiguration.decodeWeightStr(weights, i), artillery, campaign); <END> if(en != null) { retval.add(en); } } return retval; }</code><technical_language>weights unitTypes match in size</technical_language>

Target:
private static List<Entity> generateLance(String faction, int skill, int quality, List<Integer> unitTypes, String weights, boolean artillery, Campaign campaign) { List<Entity> retval = new ArrayList<>(); int unitTypeSize = unitTypes.size(); if(unitTypeSize > weights.length()) { MekHQ.getLogger().error(AtBDynamicScenarioFactory.class, "generateLance", String.format("More unit types (%d) provided than weights (%d). Truncating generated lance.", unitTypes.size(), weights.length())); unitTypeSize = weights.length(); } for(int i = 0; i < unitTypeSize; i++) { Entity en = getEntity(faction, skill, quality, unitTypes.get(i), AtBConfiguration.decodeWeightStr(weights, i), artillery, campaign); if(en != null) { retval.add(en); } } return retval; }