auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> public void testSessionCacheForTLS12() throws Exception { <END> if (protocolCipherCombo != ProtocolCipherCombo.TLSV12) { return; } clientSslCtx = wrapContext(SslContextBuilder.forClient() .trustManager(InsecureTrustManagerFactory.INSTANCE) .sslProvider(sslClientProvider()) .sslContextProvider(clientSslContextProvider()) .protocols(protocols()) .ciphers(ciphers()) .build()); SelfSignedCertificate ssc = new SelfSignedCertificate(); serverSslCtx = wrapContext(SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()) .sslProvider(sslServerProvider()) .sslContextProvider(serverSslContextProvider()) .protocols(protocols()) .ciphers(ciphers()) .build()); try { doHandshake("a.netty.io", 9999); assertSessionCache(serverSslCtx.sessionContext(), 1); assertSessionCache(clientSslCtx.sessionContext(), 1); doHandshake("a.netty.io", 9999); assertSessionCache(serverSslCtx.sessionContext(), 1); assertSessionCache(clientSslCtx.sessionContext(), 1); doHandshake("b.netty.io", 9999); assertSessionCache(serverSslCtx.sessionContext(), 2); assertSessionCache(clientSslCtx.sessionContext(), 2); } finally { ssc.delete(); } }</code><technical_language>Consider verifying session reused</technical_language>

Target:
public void testSessionCacheForTLS12() throws Exception { if (protocolCipherCombo != ProtocolCipherCombo.TLSV12) { return; } clientSslCtx = wrapContext(SslContextBuilder.forClient() .trustManager(InsecureTrustManagerFactory.INSTANCE) .sslProvider(sslClientProvider()) .sslContextProvider(clientSslContextProvider()) .protocols(protocols()) .ciphers(ciphers()) .build()); SelfSignedCertificate ssc = new SelfSignedCertificate(); serverSslCtx = wrapContext(SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()) .sslProvider(sslServerProvider()) .sslContextProvider(serverSslContextProvider()) .protocols(protocols()) .ciphers(ciphers()) .build()); try { doHandshakeVerifyReusedAndClose("a.netty.io", 9999, false); assertSessionCache(serverSslCtx.sessionContext(), 1); assertSessionCache(clientSslCtx.sessionContext(), 1); doHandshakeVerifyReusedAndClose("a.netty.io", 9999, true); assertSessionCache(serverSslCtx.sessionContext(), 1); assertSessionCache(clientSslCtx.sessionContext(), 1); doHandshakeVerifyReusedAndClose("b.netty.io", 9999, false); assertSessionCache(serverSslCtx.sessionContext(), 2); assertSessionCache(clientSslCtx.sessionContext(), 2); invalidateSessionsAndAssert(serverSslCtx.sessionContext()); invalidateSessionsAndAssert(clientSslCtx.sessionContext()); } finally { ssc.delete(); } }
Source:
<code>private ArrayList<Integer> getMessageLocationFromParam(JSONObject params) throws ApiException { String fuzzLocation = getParam(params, PARAM_FUZZ_LOCATION, ""); int locationStart; int locationEnd; try { locationStart = Integer.parseInt(fuzzLocation.split(FUZZ_LOCATION_SEPARATOR)[0]); locationEnd = Integer.parseInt(fuzzLocation.split(FUZZ_LOCATION_SEPARATOR)[1]); } catch (IllegalArgumentException e) { LOGGER.error("Couldn't create integer start and end from: " + fuzzLocation, e); throw new ApiException(ApiException.Type.BAD_FORMAT, e); } if (locationStart > locationEnd) locationStart = locationEnd = 0; <START> ArrayList<Integer> locations = new ArrayList<>(); <END> locations.add(locationStart); locations.add(locationEnd); return locations; }</code><technical_language>set this 2 elements</technical_language>

Target:
private Integer[] getMessageLocationFromParam(JSONObject params) throws ApiException { String fuzzLocation = getParam(params, PARAM_FUZZ_LOCATION, ""); int locationStart; int locationEnd; try { locationStart = Integer.parseInt(fuzzLocation.split(FUZZ_LOCATION_SEPARATOR)[0]); locationEnd = Integer.parseInt(fuzzLocation.split(FUZZ_LOCATION_SEPARATOR)[1]); } catch (IllegalArgumentException e) { LOGGER.error("Couldn't create integer start and end from: " + fuzzLocation, e); throw new ApiException(ApiException.Type.BAD_FORMAT, e); } if (locationStart > locationEnd) locationStart = locationEnd = 0; return (new Integer[] {locationStart, locationEnd}); }
Source:
<code>static <T> Iterator<T> tabulate(int n, Function<? super Integer, ? extends T> f) { Objects.requireNonNull(f, "f is null"); <START> return Collections.tabulate(n, f, Iterator.empty(), Iterator::of); <END> }</code><technical_language>lazy Collections.tabulate(n, f) method</technical_language>

Target:
static <T> Iterator<T> tabulate(int n, Function<? super Integer, ? extends T> f) { Objects.requireNonNull(f, "f is null"); return Collections.tabulate(n, f); }
Source:
<code>public void create_multiple_domain_objects_fail_bad_domain_syntacs() { databaseHelper.addObject("" + "inet6num: 2a01:500::/21\n" + "mnt-by: TEST-MNT\n" + "mnt-domains: TEST-MNT\n" + "mnt-domains: XS4ALL-MNT\n" + "source: TEST"); final RpslObject domain = RpslObject.parse("" + "domain: bug!-4.0.1.0.a.2.ip6.arpa\n" + "descr: Reverse delegation for 2a01:500::/22\n" + "admin-c: JAAP-TEST\n" + "tech-c: JAAP-TEST\n" + "zone-c: JAAP-TEST\n" + "nserver: ns1.example.com\n" + "nserver: ns2.example.com\n" + "mnt-by: TEST-MNT\n" + "source: TEST"); try { RestTest.target(getPort(), "whois/domain-objects/TEST") .request() .cookie("crowd.token_key", "valid-token") <START> .post(Entity.entity(mapRpslObjects(new RpslObject[]{domain}), MediaType.APPLICATION_JSON_TYPE), WhoisResources.class); <END> } catch (BadRequestException e) { final WhoisResources response = e.getResponse().readEntity(WhoisResources.class); RestTest.assertErrorCount(response, 1); RestTest.assertErrorMessage(response, 0, "Error", "Syntax error in %s", "bug!-4.0.1.0.a.2.ip6.arpa"); } }</code><technical_language>add fail() call in case exception is thrown</technical_language>

Target:
public void create_multiple_domain_objects_fail_bad_domain_syntacs() { databaseHelper.addObject("" + "inet6num: 2a01:500::/21\n" + "mnt-by: TEST-MNT\n" + "mnt-domains: TEST-MNT\n" + "mnt-domains: TEST2-MNT\n" + "source: TEST"); final RpslObject domain = RpslObject.parse("" + "domain: bug!-4.0.1.0.a.2.ip6.arpa\n" + "descr: Reverse delegation for 2a01:500::/22\n" + "admin-c: JAAP-TEST\n" + "tech-c: JAAP-TEST\n" + "zone-c: JAAP-TEST\n" + "nserver: ns1.example.com\n" + "nserver: ns2.example.com\n" + "mnt-by: TEST-MNT\n" + "source: TEST"); try { RestTest.target(getPort(), "whois/domain-objects/TEST") .request() .cookie("crowd.token_key", "valid-token") .post(Entity.entity(mapRpslObjects(new RpslObject[]{domain}), MediaType.APPLICATION_JSON_TYPE), WhoisResources.class); fail(); } catch (BadRequestException e) { final WhoisResources response = e.getResponse().readEntity(WhoisResources.class); RestTest.assertErrorCount(response, 1); RestTest.assertErrorMessage(response, 0, "Error", "Syntax error in %s", "bug!-4.0.1.0.a.2.ip6.arpa"); } }
Source:
<code>public void testUniqueValue() { <START> assertNull(new Alphametics("A == B").solve()); <END> }</code><technical_language>In cases this I expect throw exception instead of returning null. For error handling diverge a bit canonical data (I remove error cases canonical data for this reason) vary a lot language language want handle invalid input. In opinion throw exception in Java return null forces user deal error instead of relying checking if output is null :)</technical_language>

Target:
public void testUniqueValue() throws UnsolvablePuzzleException { expectedException.expect(UnsolvablePuzzleException.class); new Alphametics("A == B").solve(); }
Source:
<code>private void runAnsibleRemovePlaybook() { AuditLogable logable = new AuditLogableImpl(); logable.setVdsName(getVds().getName()); <START> logable.setVdsId(getVds().getId()); <END> try { AnsibleCommandBuilder command = new AnsibleCommandBuilder() .hostnames(getVds().getHostName()) .playbook(AnsibleConstants.HOST_REMOVE_PLAYBOOK); auditLogDirector.log(logable, AuditLogType.VDS_ANSIBLE_HOST_REMOVE_STARTED); AnsibleReturnValue ansibleReturnValue = ansibleExecutor.runCommand(command); logable.addCustomValue("LogFile", command.logFile().getAbsolutePath()); if (ansibleReturnValue.getAnsibleReturnCode() != AnsibleReturnCode.OK) { auditLogDirector.log(logable, AuditLogType.VDS_ANSIBLE_HOST_REMOVE_FAILED); } else { auditLogDirector.log(logable, AuditLogType.VDS_ANSIBLE_HOST_REMOVE_FINISHED); } } catch (Exception e) { logable.addCustomValue("Message", e.getMessage()); auditLogDirector.log(logable, AuditLogType.VDS_ANSIBLE_HOST_REMOVE_EXECUTION_FAILED); } }</code><technical_language>including correlation id job id this command belongs</technical_language>

Target:
private void runAnsibleRemovePlaybook() { AuditLogable logable = new AuditLogableImpl(); logable.setVdsName(getVds().getName()); logable.setVdsId(getVds().getId()); logable.setCorrelationId(getCorrelationId()); try { AnsibleCommandBuilder command = new AnsibleCommandBuilder() .hostnames(getVds().getHostName()) .playbook(AnsibleConstants.HOST_REMOVE_PLAYBOOK); auditLogDirector.log(logable, AuditLogType.VDS_ANSIBLE_HOST_REMOVE_STARTED); AnsibleReturnValue ansibleReturnValue = ansibleExecutor.runCommand(command); logable.addCustomValue("LogFile", command.logFile().getAbsolutePath()); if (ansibleReturnValue.getAnsibleReturnCode() != AnsibleReturnCode.OK) { auditLogDirector.log(logable, AuditLogType.VDS_ANSIBLE_HOST_REMOVE_FAILED); } else { auditLogDirector.log(logable, AuditLogType.VDS_ANSIBLE_HOST_REMOVE_FINISHED); } } catch (Exception e) { logable.addCustomValue("Message", e.getMessage()); auditLogDirector.log(logable, AuditLogType.VDS_ANSIBLE_HOST_REMOVE_EXECUTION_FAILED); } }
Source:
<code><START> void should_allow_extracting_values_using_multiple_lambda_extractors() { END> AbstractListAssert<?, ?, Object, ?> result = assertThat(luke).extracting(firstName, employee -> employee.getName().getLast()); result.hasSize(2) .containsExactly("Luke", "Skywalker"); }</code><technical_language>remove // FIXME given/when/then</technical_language>

Target:
void should_allow_extracting_values_using_multiple_lambda_extractors() { Function<Employee, Object> lastName = employee -> employee.getName().getLast(); AbstractListAssert<?, ?, Object, ?> result = assertThat(luke).extracting(firstName, lastName); result.hasSize(2) .containsExactly("Luke", "Skywalker"); }
Source:
<code>SQLiteConnection createNewConnection() { try { SQLiteConnection conn; if (this.databaseFilePath != null) { conn = new SQLiteConnection(new File(this.databaseFilePath)); } else { <START> conn = new SQLiteConnection(null); <END> } conn.open(); conn.setBusyTimeout(30*1000); return conn; } catch (SQLiteException ex) { throw new IllegalStateException("Failed to open database.", ex); } }</code><technical_language>pass in null here, call args constructor</technical_language>

Target:
SQLiteConnection createNewConnection() { try { SQLiteConnection conn; if (this.databaseFilePath != null) { conn = new SQLiteConnection(new File(this.databaseFilePath)); } else { conn = new SQLiteConnection(); } conn.open(); conn.setBusyTimeout(30*1000); return conn; } catch (SQLiteException ex) { throw new IllegalStateException("Failed to open database.", ex); } }
Source:
<code>private static void addUsbSlots(VmBase vm, int numOfSlots) { for (int index = 1; index <= numOfSlots; index++) { VmDeviceUtils.addManagedDevice(new VmDeviceId(Guid.NewGuid(), vm.getId()), VmDeviceType.REDIR, VmDeviceType.SPICEVMC, getUsbSlotSpecParams(), true, false, <START> ""); <END> } }</code><technical_language>please remove alias setting (should encapsulated in addManagedDevice</technical_language>

Target:
private static void addUsbSlots(VmBase vm, int numOfSlots) { for (int index = 1; index <= numOfSlots; index++) { VmDeviceUtils.addManagedDevice(new VmDeviceId(Guid.NewGuid(), vm.getId()), VmDeviceType.REDIR, VmDeviceType.SPICEVMC, getUsbSlotSpecParams(), true, false); } }
Source:
<code>public void batch_mutate(String kvsMethodName, Map<ByteBuffer, Map<String, List<Mutation>>> mutation_map, ConsistencyLevel consistency_level) throws InvalidRequestException, UnavailableException, TimedOutException, TException { <START> int numberOfMutations = mutation_map.size(); <END> try (CloseableTrace trace = startLocalTrace("client.batch_mutate(number of mutations {}, consistency {})" + " on kvs.{}", numberOfMutations, consistency_level, kvsMethodName)) { KvsProfilingLogger.maybeLog( (KvsProfilingLogger.CallableCheckedException<Void, TException>) () -> { client.batch_mutate(mutation_map, consistency_level); return null; }, (logger, timer) -> logger.log("client.batch_mutate({}, {}) on kvs.{}", SafeArg.of("number of mutations", numberOfMutations), SafeArg.of("consistency", consistency_level.toString()), SafeArg.of("kvsMethodName", kvsMethodName))); } }</code><technical_language>this is slightly inaccurate, number of keys. number of mutations sum of sizes of List<Mutations>s, I</technical_language>

Target:
public void batch_mutate(String kvsMethodName, Map<ByteBuffer, Map<String, List<Mutation>>> mutation_map, ConsistencyLevel consistency_level) throws InvalidRequestException, UnavailableException, TimedOutException, TException { int numberOfRowsMutated = mutation_map.size(); try (CloseableTrace trace = startLocalTrace("client.batch_mutate(number of rows mutated {}, consistency {})" + " on kvs.{}", numberOfRowsMutated, consistency_level, kvsMethodName)) { KvsProfilingLogger.maybeLog( (KvsProfilingLogger.CallableCheckedException<Void, TException>) () -> { client.batch_mutate(mutation_map, consistency_level); return null; }, (logger, timer) -> logger.log("client.batch_mutate({}, {}) on kvs.{}", SafeArg.of("number of mutations", numberOfRowsMutated), SafeArg.of("consistency", consistency_level.toString()), SafeArg.of("kvsMethodName", kvsMethodName))); } }
Source:
<code>public String getPlural() { if (plural == null) { this.plural = getPlural(getClass()); } return plural; <START> } <END></code><technical_language>I this if part of constructor getter</technical_language>

Target:
public String getPlural() { return plural; }
Source:
<code>public IPropertyDescriptor[] getPropertyDescriptors() { List<IPropertyDescriptor> descriptors= new ArrayList<IPropertyDescriptor>(); if (fSourceLookup.getCallsite() != null) { descriptors.add(new PropertyDescriptor(ID_FILE_NAME, NAME_FILE_NAME)); if (fSourceLookup.getCallsite().getFunctionName() != null) { descriptors.add(new PropertyDescriptor(ID_FUNCTION_NAME, NAME_FUNCTION_NAME)); <START> } <END> descriptors.add(new PropertyDescriptor(ID_LINE_NUMBER, NAME_LINE_NUMBER)); } return descriptors.toArray(new IPropertyDescriptor[0]); }</code><technical_language>I put line number function name, match toString</technical_language>

Target:
public IPropertyDescriptor[] getPropertyDescriptors() { List<IPropertyDescriptor> descriptors= new ArrayList<IPropertyDescriptor>(); if (fSourceLookup.getCallsite() != null) { descriptors.add(new PropertyDescriptor(ID_FILE_NAME, NAME_FILE_NAME)); descriptors.add(new PropertyDescriptor(ID_LINE_NUMBER, NAME_LINE_NUMBER)); if (fSourceLookup.getCallsite().getFunctionName() != null) { descriptors.add(new PropertyDescriptor(ID_FUNCTION_NAME, NAME_FUNCTION_NAME)); } } return descriptors.toArray(new IPropertyDescriptor[0]); }
Source:
<code>private void init() { Fabric.with(this, new Crashlytics()); LocationMemory.getInstance().init(getApplicationContext()); D2.init(this); SdkQueries.createDBIndexes(); <START> if (PopulateDB.hasMandatoryTables()) { <END> PostMigration.launchPostMigration(); } if (!BuildConfig.multiuser) { Log.i(TAG, "Pull on SplashScreen ..."); PullController pullController = new PullController( getApplication().getApplicationContext()); PullUseCase pullUseCase = new PullUseCase(pullController); PullFilters pullFilters = new PullFilters(); pullFilters.setDemo(true); pullUseCase.execute(pullFilters, new PullUseCase.Callback() { @Override public void onComplete() { Log.d(this.getClass().getSimpleName(), "pull complete"); } @Override public void onStep(PullStep step) { Log.d(this.getClass().getSimpleName(), step.toString()); } @Override public void onError(String message) { Log.e(this.getClass().getSimpleName(), message); } @Override public void onNetworkError() { Log.e(this.getClass().getSimpleName(), "Network Error"); } @Override public void onPullConversionError() { Log.e(this.getClass().getSimpleName(), "Pull Conversion Error"); } @Override public void onCancel() { Log.e(this.getClass().getSimpleName(), "Pull oncancel"); } }); } }</code><technical_language>@manuelplazaspalacio this provoked postmigration is executed is moment mandatory tables data, populate in pull login</technical_language>

Target:
private void init() { Fabric.with(this, new Crashlytics()); LocationMemory.getInstance().init(getApplicationContext()); D2.init(this); SdkQueries.createDBIndexes(); PopulateDB.initDBQuery(); PostMigration.launchPostMigration(); if (!BuildConfig.multiuser) { Log.i(TAG, "Pull on SplashScreen ..."); PullController pullController = new PullController( getApplication().getApplicationContext()); PullUseCase pullUseCase = new PullUseCase(pullController); PullFilters pullFilters = new PullFilters(); pullFilters.setDemo(true); pullUseCase.execute(pullFilters, new PullUseCase.Callback() { @Override public void onComplete() { Log.d(this.getClass().getSimpleName(), "pull complete"); } @Override public void onStep(PullStep step) { Log.d(this.getClass().getSimpleName(), step.toString()); } @Override public void onError(String message) { Log.e(this.getClass().getSimpleName(), message); } @Override public void onNetworkError() { Log.e(this.getClass().getSimpleName(), "Network Error"); } @Override public void onPullConversionError() { Log.e(this.getClass().getSimpleName(), "Pull Conversion Error"); } @Override public void onCancel() { Log.e(this.getClass().getSimpleName(), "Pull oncancel"); } }); } }
Source:
<code>public void setValue(PColumn column, byte[] byteValue) { deleteRow = null; byte[] family = column.getFamilyName().getBytes(); byte[] qualifier = column.getName().getBytes(); PDataType type = column.getDataType(); if (byteValue == null || byteValue.length == 0) { if (!column.isNullable()) { throw new ConstraintViolationException(name.getString() + "." + column.getName().getString() + " may not be null"); } removeIfPresent(setValues, family, qualifier); unsetValues.deleteColumns(family, qualifier, ts); } else { <START> Integer byteSize; <END> if (type.isArrayType()) { byteSize = byteValue.length; } else { byteSize = column.getByteSize(); } if (type.isFixedWidth() && byteValue.length <= byteSize) { byteValue = SchemaUtil.padChar(byteValue, byteSize); } else if (byteSize != null && byteValue.length > byteSize) { throw new ConstraintViolationException(name.getString() + "." + column.getName().getString() + " may not exceed " + byteSize + " bytes (" + type.toObject(byteValue) + ")"); } removeIfPresent(unsetValues, family, qualifier); setValues.add(family, qualifier, ts, byteValue); } }</code><technical_language>This necessary. column.getByteSize() return null for arrays size constraint check</technical_language>

Target:
public void setValue(PColumn column, byte[] byteValue) { deleteRow = null; byte[] family = column.getFamilyName().getBytes(); byte[] qualifier = column.getName().getBytes(); PDataType type = column.getDataType(); if (byteValue == null || byteValue.length == 0) { if (!column.isNullable()) { throw new ConstraintViolationException(name.getString() + "." + column.getName().getString() + " may not be null"); } removeIfPresent(setValues, family, qualifier); unsetValues.deleteColumns(family, qualifier, ts); } else { Integer byteSize = column.getByteSize(); if (byteSize != null && type.isFixedWidth() && byteValue.length <= byteSize) { byteValue = SchemaUtil.padChar(byteValue, byteSize); } else if (byteSize != null && byteValue.length > byteSize) { throw new ConstraintViolationException(name.getString() + "." + column.getName().getString() + " may not exceed " + byteSize + " bytes (" + type.toObject(byteValue) + ")"); } removeIfPresent(unsetValues, family, qualifier); setValues.add(family, qualifier, ts, byteValue); } }
Source:
<code>private void manageIntent(Intent intent) { if (isTestRunning()) { Toast.makeText(this, getString(R.string.OONIRun_TestRunningError), Toast.LENGTH_LONG).show(); finish(); } else if (Intent.ACTION_VIEW.equals(intent.getAction())) { Uri uri = intent.getData(); String mv = uri == null ? null : uri.getQueryParameter("mv"); String tn = uri == null ? null : uri.getQueryParameter("tn"); String ta = uri == null ? null : uri.getQueryParameter("ta"); loadScreen(mv, tn, ta); } <START> else { <END> Bundle bundle = intent.getExtras(); String mv = bundle == null ? null : intent.getExtras().getString("mv"); String tn = bundle == null ? null : intent.getExtras().getString("tn"); String ta = bundle == null ? null : intent.getExtras().getString("ta"); loadScreen(mv, tn, ta); } }</code><technical_language>I this code is needed sending JSON in this currently. If determine this code is needed, remove it. for clarifying refactoring</technical_language>

Target:
private void manageIntent(Intent intent) { if (isTestRunning()) { Toast.makeText(this, getString(R.string.OONIRun_TestRunningError), Toast.LENGTH_LONG).show(); finish(); } else if (Intent.ACTION_VIEW.equals(intent.getAction())) { Uri uri = intent.getData(); String mv = uri == null ? null : uri.getQueryParameter("mv"); String tn = uri == null ? null : uri.getQueryParameter("tn"); String ta = uri == null ? null : uri.getQueryParameter("ta"); loadScreen(mv, tn, ta); } }
Source:
<code>public void testReplyToConsumersReduced() throws Exception { CachingConnectionFactory cf = new CachingConnectionFactory("localhost"); DirectReplyToMessageListenerContainer container = new DirectReplyToMessageListenerContainer(cf); container.setBeanName("reducing"); container.setIdleEventInterval(100); container.afterPropertiesSet(); container.start(); ChannelHolder channelHolder1 = container.getChannelHolder(); ChannelHolder channelHolder2 = container.getChannelHolder(); assertTrue(activeConsumerCount(container, 2)); container.releaseConsumerFor(channelHolder2, false, null); <START> Thread.sleep(500); <END> assertTrue(channelHolder1.getChannel().isOpen()); container.releaseConsumerFor(channelHolder1, false, null); assertTrue(activeConsumerCount(container, 0)); container.stop(); cf.destroy(); }</code><technical_language>I understand this is quick simple fix, experience shows rely system clock: guarantee CPU get access target process this timeout. In end sporadic test failures. sleep short period check state of component assert afterward. If some argument proceed this simple sleep, here. Thanks</technical_language>

Target:
public void testReplyToConsumersReduced() throws Exception { CachingConnectionFactory cf = new CachingConnectionFactory("localhost"); DirectReplyToMessageListenerContainer container = new DirectReplyToMessageListenerContainer(cf); container.setBeanName("reducing"); container.setIdleEventInterval(100); CountDownLatch latch = new CountDownLatch(5); container.setApplicationEventPublisher(e -> { if (e instanceof ListenerContainerIdleEvent) { latch.countDown(); } }); container.afterPropertiesSet(); container.start(); ChannelHolder channelHolder1 = container.getChannelHolder(); ChannelHolder channelHolder2 = container.getChannelHolder(); assertTrue(activeConsumerCount(container, 2)); container.releaseConsumerFor(channelHolder2, false, null); assertTrue(latch.await(10, TimeUnit.SECONDS)); assertTrue(channelHolder1.getChannel().isOpen()); container.releaseConsumerFor(channelHolder1, false, null); assertTrue(activeConsumerCount(container, 0)); container.stop(); cf.destroy(); }
Source:
<code>public void testSerializeRequest(){ Map<String, ?> metadata = new HashMap<String, Object>() {{ this.put("firstKey", "firstValue"); this.put("secondKey", "secondValue"); }}; CommandMessage message = new GenericCommandMessage<>("payload", metadata); Command command = testSubject.serialize(message, "routingKey", 1); CommandMessage<?> deserialize = testSubject.deserialize(command); <START> assertEquals(message.getIdentifier(), deserialize.getIdentifier()); <END> assertEquals(message.getIdentifier(), deserialize.getIdentifier()); assertEquals(message.getCommandName(), deserialize.getCommandName()); assertEquals(message.getMetaData(), deserialize.getMetaData()); assertEquals(message.getPayloadType(), deserialize.getPayloadType()); assertEquals(message.getPayload(), deserialize.getPayload()); }</code><technical_language>unintended duplicate assertion added here</technical_language>

Target:
public void testSerializeRequest() { Map<String, ?> metadata = new HashMap<String, Object>() {{ this.put("firstKey", "firstValue"); this.put("secondKey", "secondValue"); }}; CommandMessage message = new GenericCommandMessage<>("payload", metadata); Command command = testSubject.serialize(message, "routingKey", 1); CommandMessage<?> deserialize = testSubject.deserialize(command); assertEquals(message.getIdentifier(), deserialize.getIdentifier()); assertEquals(message.getCommandName(), deserialize.getCommandName()); assertEquals(message.getMetaData(), deserialize.getMetaData()); assertEquals(message.getPayloadType(), deserialize.getPayloadType()); assertEquals(message.getPayload(), deserialize.getPayload()); }
Source:
<code>private void endInput() { <START> stats.setNumBytesRead(in.getCount()); <END> in = null; }</code><technical_language>streamPosition() here, length of file endInput is invoked. do assignment method in onPackFooter trailer hash is read. lets avoid CountingInputStream altogether</technical_language>

Target:
private void endInput() { stats.setNumBytesRead(this.streamPosition()); in = null; }
Source:
<code>protected void createSelection(Composite container) { Label lblSelect = new Label(container, SWT.NONE); lblSelect.setText("Select synoptics:"); List<String> columnNames = Arrays.asList("Name"); items = createTable(container, SWT.BORDER | SWT.V_SCROLL | SWT.MULTI, columnNames); <START> List<String> names = (List<String>) SynopticInfo.names(available); <END> setItems(names); }</code><technical_language>Similar is API issue List Collection here</technical_language>

Target:
protected void createSelection(Composite container) { Label lblSelect = new Label(container, SWT.NONE); lblSelect.setText("Select synoptics:"); List<String> columnNames = Arrays.asList("Name"); items = createTable(container, SWT.BORDER | SWT.V_SCROLL | SWT.MULTI, columnNames); List<String> names = SynopticInfo.names(available); setItems(names); }
Source:
<code>public DataIndexer getDataIndexer(ObjectStream<Event> events) throws IOException { String dataIndexerName = trainingParameters.getStringParameter(DATA_INDEXER_PARAM, DATA_INDEXER_TWO_PASS_VALUE); trainingParameters.put(AbstractDataIndexer.SORT_PARAM, Boolean.toString(isSortAndMerge())); <START> <END> DataIndexer indexer; if (DATA_INDEXER_ONE_PASS_VALUE.equals(dataIndexerName)) { indexer = new OnePassDataIndexer(); } else if (DATA_INDEXER_TWO_PASS_VALUE.equals(dataIndexerName)) { indexer = new TwoPassDataIndexer(); } else { throw new IllegalStateException("Unexpected data indexer name: " + dataIndexerName); } indexer.init(trainingParameters); indexer.index(events); return indexer; }</code><technical_language>Is cutoff missing in new code</technical_language>

Target:
public DataIndexer getDataIndexer(ObjectStream<Event> events) throws IOException { trainingParameters.put(AbstractDataIndexer.SORT_PARAM, Boolean.toString(isSortAndMerge())); if (trainingParameters.getIntParameter(CUTOFF_PARAM, -1) == -1) { trainingParameters.put(CUTOFF_PARAM, "5"); } DataIndexer indexer = DataIndexerFactory.getDataIndexer(trainingParameters, reportMap); indexer.index(events); return indexer; }
Source:
<code>public final void installService(DeploymentPhaseContext ctx, String implementationClassName, T instance) { AbstractExtensionManagerService<T> service = createService(implementationClassName, instance); ServiceName extensionServiceName = ServiceName.JBOSS.append(service.getServiceTypeName(), implementationClassName.replaceAll("\\.", "_")); <START> logger.info("Registering Deployed Cache Store service for store " + implementationClassName); <END> ServiceBuilder<T> serviceBuilder = ctx.getServiceTarget().addService(extensionServiceName, service); serviceBuilder.setInitialMode(ServiceController.Mode.ACTIVE); serviceBuilder.addDependency(DeployedCacheStoreFactoryService.SERVICE_NAME, DeployedCacheStoreFactory.class, service.getDeployedCacheStoreFactory()); serviceBuilder.install(); }</code><technical_language>Please externalize this Messages</technical_language>

Target:
public final void installService(DeploymentPhaseContext ctx, String implementationClassName, T instance) { AbstractExtensionManagerService<T> service = createService(implementationClassName, instance); ServiceName extensionServiceName = ServiceName.JBOSS.append(service.getServiceTypeName(), implementationClassName.replaceAll("\\.", "_")); InfinispanLogger.ROOT_LOGGER.installDeployedCacheStore(implementationClassName); ServiceBuilder<T> serviceBuilder = ctx.getServiceTarget().addService(extensionServiceName, service); serviceBuilder.setInitialMode(ServiceController.Mode.ACTIVE); serviceBuilder.addDependency(DeployedCacheStoreFactoryService.SERVICE_NAME, DeployedCacheStoreFactory.class, service.getDeployedCacheStoreFactory()); serviceBuilder.install(); }
Source:
<code>public List<ComparablePair<Long,KeyExtent>> computeBusiest(Collection<Tablet> tablets) { HashMap<KeyExtent,Long> counts = new HashMap<>(); ArrayList<ComparablePair<Long,KeyExtent>> tabletsWithDelta = new ArrayList<>(); for (Tablet tablet : tablets) { KeyExtent extent = tablet.getExtent(); long count = extractCount(tablet); if (count == 0) continue; counts.put(extent, count); Long lastCount = lastCounts.get(extent); if (lastCount == null) lastCount = 0L; long delta = count - lastCount; if (delta <= 0) continue; <START> tabletsWithDelta.add(new ComparablePair<>(delta, extent)); <END> } lastCounts = counts; return Ordering.natural().greatestOf(tabletsWithDelta, numBusiestTabletsToLog); }</code><technical_language>Instead of continue, this code simplifies to: java if (delta > 0) { tabletsWithDelta.add(new ComparablePair<>(delta, extent)); }</technical_language>

Target:
public List<ComparablePair<Long,KeyExtent>> computeBusiest(Collection<Tablet> tablets) { HashMap<KeyExtent,Long> counts = new HashMap<>(); ArrayList<ComparablePair<Long,KeyExtent>> tabletsWithDelta = new ArrayList<>(); for (Tablet tablet : tablets) { KeyExtent extent = tablet.getExtent(); long count = extractCount(tablet); if (count == 0) continue; counts.put(extent, count); Long lastCount = lastCounts.get(extent); if (lastCount == null) lastCount = 0L; long delta = count - lastCount; if (delta > 0) tabletsWithDelta.add(new ComparablePair<>(delta, extent)); } lastCounts = counts; return Ordering.natural().greatestOf(tabletsWithDelta, numBusiestTabletsToLog); }
Source:
<code>public int prolepticYear(final Era era, final int yearOfEra) { if (!(era instanceof InternationalFixedEra)) { throw new ClassCastException("Invalid era: " + era); } <START> if (0 > yearOfEra) { <END> throw new DateTimeException("Invalid year of era: " + yearOfEra); } return yearOfEra; }</code><technical_language>This line is backwards. Please "Yoda conditions"</technical_language>

Target:
public int prolepticYear(final Era era, final int yearOfEra) { if (!(era instanceof InternationalFixedEra)) { throw new ClassCastException("Invalid era: " + era); } YEAR_RANGE.checkValidIntValue(yearOfEra, ChronoField.YEAR_OF_ERA); return yearOfEra; }
Source:
<code>public void readFromNbt(NBTTagCompound compound) { if (this instanceof IMixinCustomDataHolder) { if (compound.hasKey(NbtDataUtil.CUSTOM_MANIPULATOR_TAG_LIST, NbtDataUtil.TAG_LIST)) { final NBTTagList list = compound.getTagList(NbtDataUtil.CUSTOM_MANIPULATOR_TAG_LIST, NbtDataUtil.TAG_COMPOUND); final ImmutableList.Builder<DataView> builder = ImmutableList.builder(); if (list != null && list.tagCount() != 0) { for (int i = 0; i < list.tagCount(); i++) { final NBTTagCompound internal = list.getCompoundTagAt(i); builder.add(NbtTranslator.getInstance().translateFrom(internal)); } } try { final List<DataManipulator<?, ?>> manipulators = DataUtil.deserializeManipulatorList(builder.build()); for (DataManipulator<?, ?> manipulator : manipulators) { offer(manipulator); } } catch (InvalidDataException e) { SpongeImpl.getLogger().error("Could not deserialize custom plugin data! ", e); } } } <START> if (this instanceof IMixinGriefer && ((IMixinGriefer) this).isGriefer() && compound.hasKey("CanGrief")) { <END> ((IMixinGriefer) this).setCanGrief(compound.getBoolean("CanGrief")); } }</code><technical_language>Store string constants in NBTDataUtil please</technical_language>

Target:
public void readFromNbt(NBTTagCompound compound) { if (this instanceof IMixinCustomDataHolder) { if (compound.hasKey(NbtDataUtil.CUSTOM_MANIPULATOR_TAG_LIST, NbtDataUtil.TAG_LIST)) { final NBTTagList list = compound.getTagList(NbtDataUtil.CUSTOM_MANIPULATOR_TAG_LIST, NbtDataUtil.TAG_COMPOUND); final ImmutableList.Builder<DataView> builder = ImmutableList.builder(); if (list != null && list.tagCount() != 0) { for (int i = 0; i < list.tagCount(); i++) { final NBTTagCompound internal = list.getCompoundTagAt(i); builder.add(NbtTranslator.getInstance().translateFrom(internal)); } } try { final List<DataManipulator<?, ?>> manipulators = DataUtil.deserializeManipulatorList(builder.build()); for (DataManipulator<?, ?> manipulator : manipulators) { offer(manipulator); } } catch (InvalidDataException e) { SpongeImpl.getLogger().error("Could not deserialize custom plugin data! ", e); } } } }
Source:
<code>private ImmutableHolidayCalendar(String name, SortedSet<LocalDate> holidays, Set<DayOfWeek> weekendDays) { ArgChecker.notNull(name, "name"); ArgChecker.notNull(holidays, "holidays"); ArgChecker.notNull(weekendDays, "weekendDays"); this.name = name; this.holidays = ImmutableSortedSet.copyOfSorted(holidays); this.weekendDays = Sets.immutableEnumSet(weekendDays); if (holidays.isEmpty()) { this.range = LocalDateRange.ALL; this.startYear = 0; this.lookup = new int[0]; } else { this.range = LocalDateRange.ofClosed( holidays.first().with(TemporalAdjusters.firstDayOfYear()), holidays.last().with(TemporalAdjusters.lastDayOfYear())); this.startYear = range.getStart().getYear(); <START> int[] array = new int[(range.getEndExclusive().getYear() - startYear) * 12]; <END> for (LocalDate date : holidays) { int index = (date.getYear() - startYear) * 12 + date.getMonthValue() - 1; array[index] |= (1 << (date.getDayOfMonth() - 1)); } LocalDate date = LocalDate.of(startYear, 1, 1); for (int i = 0; i < array.length; i++) { int monthLen = date.lengthOfMonth(); for (int j = 0; j < monthLen; j++) { if (weekendDays.contains(date.getDayOfWeek())) { array[i] |= (1 << j); } date = date.plusDays(1); } for (int j = monthLen; j < 32; j++) { array[i] |= (1 << j); } } this.lookup = array; } }</code><technical_language>I this is correct if clearer: range is set included date is day of year, sorange.getEndExclusive() in next year easy overlook inclusive/exclusive difference. if put day in a var in size calculation (with a +1 of course), clearer</technical_language>

Target:
private ImmutableHolidayCalendar(String name, SortedSet<LocalDate> holidays, Set<DayOfWeek> weekendDays) { ArgChecker.notNull(name, "name"); ArgChecker.notNull(holidays, "holidays"); ArgChecker.notNull(weekendDays, "weekendDays"); this.name = name; this.holidays = ImmutableSortedSet.copyOfSorted(holidays); this.weekendDays = Sets.immutableEnumSet(weekendDays); if (holidays.isEmpty()) { this.range = LocalDateRange.ALL; this.startYear = 0; this.lookup = new int[0]; } else { this.range = LocalDateRange.ofClosed( holidays.first().with(TemporalAdjusters.firstDayOfYear()), holidays.last().with(TemporalAdjusters.lastDayOfYear())); this.startYear = range.getStart().getYear(); int endYearExclusive = range.getEndExclusive().getYear(); this.lookup = buildLookupArray(holidays, weekendDays, startYear, endYearExclusive); } }
Source:
<code>private void startProcessesCleaner() { Scheduler.get() .scheduleFixedDelay( () -> { for (Iterator<Map.Entry<String, Pair<ProgressReportDto, Long>>> it = progresses.entrySet().iterator(); it.hasNext(); ) { <START> Map.Entry<String, Pair<ProgressReportDto, Long>> entry = it.next(); <END> long lastUpdate = entry.getValue().getSecond(); ProgressReportDto progress = entry.getValue().getFirst(); if ((currentTimeMillis() - lastUpdate) > DELAY_MS) { it.remove(); progressResolver.removeProgress(progress); String currentTaskId = currentProgress.getId(); String taskId = progress.getId(); if (currentTaskId.equals(taskId)) { updateCurrentTask(); } } } return !progresses.isEmpty(); }, DELAY_MS); }</code><technical_language>I a bit worried accessing progresses threads</technical_language>

Target:
private void startProcessesCleaner() { Scheduler.get() .scheduleFixedDelay( () -> { for (Iterator<Map.Entry<String, Pair<ProgressReportDto, Long>>> it = progresses.entrySet().iterator(); it.hasNext(); ) { Map.Entry<String, Pair<ProgressReportDto, Long>> entry = it.next(); long lastUpdate = entry.getValue().getSecond(); ProgressReportDto progress = entry.getValue().getFirst(); if ((currentTimeMillis() - lastUpdate) > DELAY_MS) { it.remove(); backgroundLoader.removeProgress(progress); String currentTaskId = currentProgress.getId(); String taskId = progress.getId(); if (currentTaskId.equals(taskId)) { updateCurrentProgress(); } } } return !progresses.isEmpty(); }, DELAY_MS); }
Source:
<code>public void doMovesRightTest() { <START> Point q = new Point(-3.0, -3.0); <END> Enemy enemy = new Enemy(q, null); units.add(enemy); simpleLevel = new Level(players, units, emptyGrid); simpleArtificialIntelligence = new ArtificialIntelligence(simpleLevel); simpleArtificialIntelligence.aiMover(); simpleLevel.tick(); assertTrue(enemy.getLocation().getX() > q.getX()); }</code><technical_language>Abbreviation Alert <naming</technical_language>

Target:
public void doMovesRightTest() { point = new Point(-3.0, -3.0); Enemy enemy = new Enemy(point, null); units.add(enemy); simpleLevel = new Level(players, units, emptyGrid); simpleArtificialIntelligence = new ArtificialIntelligence(simpleLevel); simpleArtificialIntelligence.aiMover(); simpleLevel.tick(); assertTrue(enemy.getLocation().getX() > point.getX()); }
Source:
<code>static List<TooSlowLog.SlowLogPayload> getFilteredLogs( AdminProtos.SlowLogResponseRequest request, List<TooSlowLog.SlowLogPayload> logPayloadList) { <START> if (isFilterProvided(request)) { <END> logPayloadList = filterLogs(request, logPayloadList); } int limit = Math.min(request.getLimit(), logPayloadList.size()); return logPayloadList.subList(0, limit); }</code><technical_language>need for this if implement logic I suggested.</technical_language>

Target:
static List<TooSlowLog.SlowLogPayload> getFilteredLogs( AdminProtos.SlowLogResponseRequest request, List<TooSlowLog.SlowLogPayload> logPayloadList) { int totalFilters = getTotalFiltersCount(request); if (totalFilters > 0) { logPayloadList = filterLogs(request, logPayloadList, totalFilters); } int limit = Math.min(request.getLimit(), logPayloadList.size()); return logPayloadList.subList(0, limit); }
Source:
<code>public static Object object(Map<String, Object> arguments) { ConfigBag config = ConfigBag.newInstance(arguments); String typeName = BrooklynYamlTypeInstantiator.InstantiatorFromKey.extractTypeName("object", config).orNull(); Map<String,Object> fields = Maybe.fromNullable((Map<String, Object>) config.getStringKey("object.fields")) .or(MutableMap.<String, Object>of()); try { <START> Class<?> type = Class.forName(typeName); <END> if (!Reflections.hasNoArgConstructor(type)) { throw new IllegalStateException(String.format("Cannot construct %s bean: No public no-arg constructor available present", type)); } if (fields.isEmpty() || DslUtils.resolved(fields.values())) { try { Object bean = Reflections.invokeConstructorWithArgs(type).get(); BeanUtils.populate(bean, fields); return bean; } catch (Exception e) { throw Exceptions.propagate(e); } } else { return new DslObject(type, fields); } } catch (ClassNotFoundException e) { throw Exceptions.propagate(e); } }</code><technical_language>Is this right class loader? @grkvlt "we get access right class loader, unfortunately; code for sensor"</technical_language>

Target:
public static Object object(Map<String, Object> arguments) { ConfigBag config = ConfigBag.newInstance(arguments); String typeName = BrooklynYamlTypeInstantiator.InstantiatorFromKey.extractTypeName("object", config).orNull(); Map<String,Object> objectFields = (Map<String, Object>) config.getStringKeyMaybe("object.fields").or(MutableMap.of()); Map<String,Object> brooklynConfig = (Map<String, Object>) config.getStringKeyMaybe("brooklyn.config").or(MutableMap.of()); try { Class<?> type = Class.forName(typeName); if (!Reflections.hasNoArgConstructor(type)) { throw new IllegalStateException(String.format("Cannot construct %s bean: No public no-arg constructor available", type)); } if ((objectFields.isEmpty() || DslUtils.resolved(objectFields.values())) && (brooklynConfig.isEmpty() || DslUtils.resolved(brooklynConfig.values()))) { return DslObject.create(type, objectFields, brooklynConfig); } else { return new DslObject(type, objectFields, brooklynConfig); } } catch (ClassNotFoundException e) { throw Exceptions.propagate(e); } }
Source:
<code>public void initialize() { final Map<Long, NeuralNetworkData> workloadMap = memoryStore.getAll(); final Collection<NeuralNetworkData> workload = workloadMap.values(); <START> LOG.log(Level.INFO, "Number of input instances = {0}", workload.size()); <END> }</code><technical_language>purpose of this stuff in initialize()</technical_language>

Target:
public void initialize() { }
Source:
<code>public final Type getType() { if (beginA == endA && beginB < endB) return Type.INSERT; if (beginA < endA && beginB == endB) return Type.DELETE; <START> if (isEmpty()) <END> return Type.EMPTY; return Type.REPLACE; }</code><technical_language>Surprising suggest this. I guess spent this method call for call for free of inlining. Right</technical_language>

Target:
public final Type getType() { if (beginA == endA && beginB < endB) return Type.INSERT; if (beginA < endA && beginB == endB) return Type.DELETE; if (beginA == endA && beginB == endB) return Type.EMPTY; return Type.REPLACE; }
Source:
<code>@Override protected void onEntityRemoved(Entity member) { try { ((MongoDBReplicaSetImpl) entity).serverRemoved((MongoDBServer) member); } catch (Exception e) { <START> ServiceStateLogic.ServiceNotUpLogic.updateNotUpIndicator((EntityLocal)member, "Failed to update replicaset", e); <END> } }</code><technical_language>Likewise</technical_language>

Target:
@Override protected void onEntityRemoved(Entity member) { ((MongoDBReplicaSetImpl) entity).serverRemoved((MongoDBServer) member); }
Source:
<code>public LinkedIdentifierColumn(MainTableColumnModel model, CellFactory cellFactory, BibDatabaseContext database, DialogService dialogService) { super(model); this.database = database; this.cellFactory = cellFactory; this.dialogService = dialogService; Node headerGraphic = IconTheme.JabRefIcons.WWW.getGraphicNode(); Tooltip.install(headerGraphic, new Tooltip(Localization.lang("Linked identifiers"))); this.setGraphic(headerGraphic); this.getStyleClass().add(MainTableColumnFactory.STYLE_ICON_COLUMN); MainTableColumnFactory.setExactWidth(this, ColumnPreferences.ICON_COLUMN_WIDTH); this.setResizable(false); this.setCellValueFactory(cellData -> cellData.getValue().getLinkedIdentifiers()); new ValueTableCellFactory<BibEntryTableViewModel, Map<Field, String>>() <START> .withGraphic(values -> createIdentifierGraphic(values)) <END> .withTooltip(this::createIdentifierTooltip) .withMenu(this::createIdentifierMenu) .withOnMouseClickedEvent((entry, linkedFiles) -> event -> { if ((event.getButton() == MouseButton.PRIMARY) && (linkedFiles.size() == 1)) { try { for (Field field : linkedFiles.keySet()) { JabRefDesktop.openExternalViewer(database, linkedFiles.get(field), field); } } catch (IOException e) { dialogService.showErrorDialogAndWait(Localization.lang("Unable to open link."), e); } } }) .install(this); }</code><technical_language>code .withGraphic(this::createIdentifierGraphic) work</technical_language>

Target:
public LinkedIdentifierColumn(MainTableColumnModel model, CellFactory cellFactory, BibDatabaseContext database, DialogService dialogService) { super(model); this.database = database; this.cellFactory = cellFactory; this.dialogService = dialogService; Node headerGraphic = IconTheme.JabRefIcons.WWW.getGraphicNode(); Tooltip.install(headerGraphic, new Tooltip(Localization.lang("Linked identifiers"))); this.setGraphic(headerGraphic); this.getStyleClass().add(MainTableColumnFactory.STYLE_ICON_COLUMN); MainTableColumnFactory.setExactWidth(this, ColumnPreferences.ICON_COLUMN_WIDTH); this.setResizable(false); this.setCellValueFactory(cellData -> cellData.getValue().getLinkedIdentifiers()); new ValueTableCellFactory<BibEntryTableViewModel, Map<Field, String>>() .withGraphic(this::createIdentifierGraphic) .withTooltip(this::createIdentifierTooltip) .withMenu(this::createIdentifierMenu) .withOnMouseClickedEvent((entry, linkedFiles) -> event -> { if ((event.getButton() == MouseButton.PRIMARY) && (linkedFiles.size() == 1)) { try { for (Field field : linkedFiles.keySet()) { JabRefDesktop.openExternalViewer(database, linkedFiles.get(field), field); } } catch (IOException e) { dialogService.showErrorDialogAndWait(Localization.lang("Unable to open link."), e); } } }) .install(this); }
Source:
<code>void test(DataSource dataSource) throws SQLException { <START> Connection connection = null; <END> try { connection = dataSource.getConnection(); } }</code><technical_language>I prefer a compiling code here: void test(DataSource dataSource) { Connection connection = null; try { connection = dataSource.getConnection(); // Noncompliant } catch (SQLException e) { // do } }</technical_language>

Target:
void test(DataSource dataSource) throws SQLException { Connection connection = null; try { connection = dataSource.getConnection(); } catch (Exception ex) { ex.printStackTrace(); } }
Source:
<code>static <START> MessageNano createFromParcel(Parcel <END> in) { String className = in.readString(); byte[] data = in.createByteArray(); MessageNano proto = null; try { Class<?> clazz = Class.forName(className); Object instance = clazz.newInstance(); proto = (MessageNano) instance; MessageNano.mergeFrom(proto, data); } catch (ClassNotFoundException e) { Log.e(TAG, "Exception trying to create proto from parcel", e); } catch (IllegalAccessException e) { Log.e(TAG, "Exception trying to create proto from parcel", e); } catch (InstantiationException e) { Log.e(TAG, "Exception trying to create proto from parcel", e); } catch (InvalidProtocolBufferNanoException e) { Log.e(TAG, "Exception trying to create proto from parcel", e); } return proto; }</code><technical_language>able genericize this cast return</technical_language>

Target:
static <T extends MessageNano> T createFromParcel(Parcel in) { String className = in.readString(); byte[] data = in.createByteArray(); MessageNano proto = null; try { Class<?> clazz = Class.forName(className); Object instance = clazz.newInstance(); proto = (MessageNano) instance; MessageNano.mergeFrom(proto, data); } catch (ClassNotFoundException e) { Log.e(TAG, "Exception trying to create proto from parcel", e); } catch (IllegalAccessException e) { Log.e(TAG, "Exception trying to create proto from parcel", e); } catch (InstantiationException e) { Log.e(TAG, "Exception trying to create proto from parcel", e); } catch (InvalidProtocolBufferNanoException e) { Log.e(TAG, "Exception trying to create proto from parcel", e); } return (T) proto; }
Source:
<code>public TChange getChangeAtIndex(int index) { if (index < 0 || index >= this.getCount()) { <START> throw new IndexOutOfBoundsException("index is out of range."); <END> } return this.changes.get(index); }</code><technical_language>give a more suitable message IndexOutOfBoundsException simply index is out of range. this message extra information</technical_language>

Target:
public TChange getChangeAtIndex(int index) { if (index < 0 || index >= this.getCount()) { throw new IndexOutOfBoundsException( String.format("index %d is out of range [0..%d[.", index, this.getCount())); } return this.changes.get(index); }