auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> public void afterDatastoreRef() { <END> S3DatasetDefinition definition = new S3DatasetDefinition(); RuntimeInfo runtimeInfo = definition.getRuntimeInfo(this); try (SandboxedInstance sandboxedInstance = RuntimeUtil.createRuntimeClass(runtimeInfo, getClass().getClassLoader())) { IS3DatasetRuntime runtime = (IS3DatasetRuntime) sandboxedInstance.getInstance(); runtime.initialize(null, this); this.bucket.setPossibleValues(new ArrayList<String>(runtime.listBuckets())); } catch (Exception e) { TalendRuntimeException.build(ComponentsErrorCode.IO_EXCEPTION, e).throwIt(); } }</code><technical_language>is some issue afterDatastoreRef learned salesforce 1. connection failed, dataset created 2. function running long time, dataset display this time, user happen empty page a try beforeBucket</technical_language>

Target:
public void afterDatastoreRef() { if(!this.bucket.getPossibleValues().isEmpty()) { return; } S3DatasetDefinition definition = new S3DatasetDefinition(); RuntimeInfo runtimeInfo = definition.getRuntimeInfo(this); try (SandboxedInstance sandboxedInstance = RuntimeUtil.createRuntimeClass(runtimeInfo, getClass().getClassLoader())) { IS3DatasetRuntime runtime = (IS3DatasetRuntime) sandboxedInstance.getInstance(); runtime.initialize(null, this); this.bucket.setPossibleValues(new ArrayList<String>(runtime.listBuckets())); } catch (Exception e) { LOGGER.warn(e.getClass() + " : " + e.getMessage()); } }
Source:
<code><START> public static String getPermString(int perms) { <END> StringBuilder p = new StringBuilder(); if ((perms & ZooDefs.Perms.CREATE) != 0) { p.append('c'); } if ((perms & ZooDefs.Perms.DELETE) != 0) { p.append('d'); } if ((perms & ZooDefs.Perms.READ) != 0) { p.append('r'); } if ((perms & ZooDefs.Perms.WRITE) != 0) { p.append('w'); } if ((perms & ZooDefs.Perms.ADMIN) != 0) { p.append('a'); } return p.toString(); }</code><technical_language>considered caching values in some way? I 2 options this faster: 1. dynamic caching of generated values, 2. static caching of values in a static hashmap (32 values if mistaken)</technical_language>

Target:
public static String getPermString(int perms) { String permString = permCache.get(perms); if (permString != null) { return permString; } permString = constructPermString(perms); if (!permString.isEmpty()) { permCache.put(perms, permString); } return permString; }
Source:
<code>public static JobContextImpl fromConfigWithDefaults(Config config) { JobConfig jobConfig = new JobConfig(config); String jobName = <START> jobConfig.getName().orElseThrow(() -> new IllegalArgumentException("Job name is not defined in configuration")); <END> String jobId = jobConfig.getJobId(); return new JobContextImpl(config, jobName, jobId); }</code><technical_language>message "Config job.name is missing"</technical_language>

Target:
public static JobContextImpl fromConfigWithDefaults(Config config) { JobConfig jobConfig = new JobConfig(config); String jobName = jobConfig.getName() .orElseThrow(() -> new IllegalArgumentException(String.format("Config %s is missing", JobConfig.JOB_NAME))); String jobId = jobConfig.getJobId(); return new JobContextImpl(config, jobName, jobId); }
Source:
<code>public OutputStream newOutputStream(int index) throws IOException { synchronized (DiskLruCache.this) { <START> if (index >= valueCount || index < 0) { <END> throw new IllegalArgumentException("Expected index " + index + " to " + "be greater than 0 and less than the maximum value count " + "of " + valueCount); } if (entry.currentEditor != this) { throw new IllegalStateException(); } if (!entry.readable) { written[index] = true; } File dirtyFile = entry.getDirtyFile(index); FileOutputStream outputStream; try { outputStream = new FileOutputStream(dirtyFile); } catch (FileNotFoundException e) { directory.mkdirs(); try { outputStream = new FileOutputStream(dirtyFile); } catch (FileNotFoundException e2) { return NULL_OUTPUT_STREAM; } } return new FaultHidingOutputStream(outputStream); } }</code><technical_language>This check of synchronized block. grabbing a lock throw exception. Also, super pick: flip order of conditions zero check is first</technical_language>

Target:
public OutputStream newOutputStream(int index) throws IOException { if (index < 0 || index >= valueCount) { throw new IllegalArgumentException("Expected index " + index + " to " + "be greater than 0 and less than the maximum value count " + "of " + valueCount); } synchronized (DiskLruCache.this) { if (entry.currentEditor != this) { throw new IllegalStateException(); } if (!entry.readable) { written[index] = true; } File dirtyFile = entry.getDirtyFile(index); FileOutputStream outputStream; try { outputStream = new FileOutputStream(dirtyFile); } catch (FileNotFoundException e) { directory.mkdirs(); try { outputStream = new FileOutputStream(dirtyFile); } catch (FileNotFoundException e2) { return NULL_OUTPUT_STREAM; } } return new FaultHidingOutputStream(outputStream); } }
Source:
<code>public void testSelectQueryTypes() throws SQLException, IOException { Properties properties = new Properties(); properties.setProperty("common.max_count", "1000"); properties.setProperty("common.max_retry", "3"); properties.setProperty("default.driver", "org.h2.Driver"); properties.setProperty("default.url", getJdbcConnection()); properties.setProperty("default.user", ""); properties.setProperty("default.password", ""); JDBCInterpreter t = new JDBCInterpreter(properties); t.open(); String sqlQuery = "select * from test_table"; InterpreterResult interpreterResult = t.interpret(sqlQuery, interpreterContext); assertEquals(InterpreterResult.Code.SUCCESS, interpreterResult.code()); assertEquals(Collections.nCopies(2, ColumnDef.TYPE.STRING), <START> interpreterResult.message().get(0).getColumnTypes()); <END> }</code><technical_language>interpreter is closed, put in finally block</technical_language>

Target:
public void testSelectQueryTypes() throws SQLException, IOException { Properties properties = new Properties(); properties.setProperty("common.max_count", "1000"); properties.setProperty("common.max_retry", "3"); properties.setProperty("default.driver", "org.h2.Driver"); properties.setProperty("default.url", getJdbcConnection()); properties.setProperty("default.user", ""); properties.setProperty("default.password", ""); JDBCInterpreter t = new JDBCInterpreter(properties); try { t.open(); String sqlQuery = "select * from test_table"; InterpreterResult interpreterResult = t.interpret(sqlQuery, interpreterContext); assertEquals(InterpreterResult.Code.SUCCESS, interpreterResult.code()); assertEquals(Collections.nCopies(2, ColumnDef.TYPE.STRING), interpreterResult.message().get(0).getColumnTypes()); } finally { t.close(); } }
Source:
<code>protected void postRunnable(Runnable runnable) { if (runnable != null) { if (getUseSynchronousMode() || handler == null) { runnable.run(); } else { <START> assert handler != null; <END> handler.post(runnable); } } }</code><technical_language>@zxw1962 assert work in production, if change this actual if() statement great</technical_language>

Target:
protected void postRunnable(Runnable runnable) { if (runnable != null) { if (getUseSynchronousMode() || handler == null) { runnable.run(); } else { AssertUtils.asserts(handler != null, "handler should not be null!"); handler.post(runnable); } } }
Source:
<code>public void applyCredentialsFilter(OkHttpClient.Builder clientBuilder) { clientBuilder.addInterceptor(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request originalRequest = chain.request(); HttpUrl url = chain.request().url(); Map<String, String> challengeMap = cache.getCachedChallenge(url); Response response; Pair<Request, HttpMessageSecurity> authenticatedRequestPair; if (challengeMap != null) { authenticatedRequestPair = buildAuthenticatedRequest(originalRequest, challengeMap); } else { response = chain.proceed(buildEmptyRequest(originalRequest)); if (response.code() != 401) { return response; } authenticatedRequestPair = buildAuthenticatedRequest(originalRequest, response); <START> response.close(); <END> } response = chain.proceed(authenticatedRequestPair.getLeft()); if (response.code() == 200) { return authenticatedRequestPair.getRight().unprotectResponse(response); } else { return response; } } }); }</code><technical_language>buildAuthenticatedRequest throw exception if response.close(); hit leak connection</technical_language>

Target:
public void applyCredentialsFilter(OkHttpClient.Builder clientBuilder) { clientBuilder.addInterceptor(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request originalRequest = chain.request(); HttpUrl url = chain.request().url(); Map<String, String> challengeMap = cache.getCachedChallenge(url); Response response; Pair<Request, HttpMessageSecurity> authenticatedRequestPair; if (challengeMap != null) { authenticatedRequestPair = buildAuthenticatedRequest(originalRequest, challengeMap); } else { response = chain.proceed(buildEmptyRequest(originalRequest)); if (response.code() != 401) { return response; } try { authenticatedRequestPair = buildAuthenticatedRequest(originalRequest, response); } finally { response.close(); } } response = chain.proceed(authenticatedRequestPair.getLeft()); if (response.code() == 200) { return authenticatedRequestPair.getRight().unprotectResponse(response); } else { return response; } } }); }
Source:
<code>public List<Long> findPermissionsInDatabaseButStaleInOrMissingFromSolr() { List<Long> indexingRequired = new ArrayList<>(); long rootDvId = dataverseService.findRootDataverse().getId(); for (DvObject dvObject : dvObjectService.findAll()) { Timestamp permissionModificationTime = dvObject.getPermissionModificationTime(); Timestamp permissionIndexTime = dvObject.getPermissionIndexTime(); if (permissionIndexTime == null) { <START> if (dvObject.getId() != rootDvId && !dvObject.isInstanceofDataFile()) { <END> indexingRequired.add(dvObject.getId()); } } else if (permissionModificationTime == null) { logger.info("no permission modification time for dvobject id " + dvObject.getId()); } else if (permissionIndexTime.before(permissionModificationTime)) { indexingRequired.add(dvObject.getId()); } } return indexingRequired; }</code><technical_language>a performance optimization, skipping data files anyway, instead of dvObjectService.findAll() get a list of dataverses datasets. I if performance not, if performance is a problem</technical_language>

Target:
public List<Long> findPermissionsInDatabaseButStaleInOrMissingFromSolr() { List<Long> indexingRequired = new ArrayList<>(); long rootDvId = dataverseService.findRootDataverse().getId(); List<Long> missingDataversePermissionIds = dataverseService.findIdStalePermission(); List<Long> missingDatasetPermissionIds = datasetService.findIdStalePermission(); for (Long id : missingDataversePermissionIds) { if (!id.equals(rootDvId)) { indexingRequired.add(id); } } indexingRequired.addAll(missingDatasetPermissionIds); return indexingRequired; }
Source:
<code>public BinaryObject replaceOriginalFile(InputStream contentStream, String filename, String mimetype, String sha1Checksum, String md5Checksum) { String objectPath = constructOriginalFilePath(); <START> Model fileModel = ModelFactory.createDefaultModel(); <END> Resource resc = fileModel.createResource(objectPath); resc.addProperty(RDF.type, PcdmUse.OriginalFile); return repoObjFactory.updateBinary(fileSetUri, ORIGINAL_FILE, contentStream, filename, mimetype, sha1Checksum, md5Checksum, fileModel); }</code><technical_language>thinking some, I replaceOriginalFile needs providing a model. is changing properties, this is pretty refreshing them. If need replace properties a point other ways do that</technical_language>

Target:
public BinaryObject replaceOriginalFile(InputStream contentStream, String filename, String mimetype, String sha1Checksum, String md5Checksum) { return repoObjFactory.updateBinary(fileSetUri, ORIGINAL_FILE, contentStream, filename, mimetype, sha1Checksum, md5Checksum, null); }
Source:
<code>@Override public void readOnly(boolean readOnly) throws IgniteException { <START> checkReadOnlyModeSupports(); <END> guard(); try { ctx.state().changeGlobalState(readOnly).get(); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } }</code><technical_language>sense of beauty tells this code following: guard(); try { verifyReadOnlyModeSupport(); ctx.state().changeGlobalState(readOnly).get(); } ... Perhaps, verifyReadOnlyModeSupport a part of ctx.state().changeGlobalState(readOnly) method, I here</technical_language>

Target:
@Override public void readOnly(boolean readOnly) throws IgniteException { guard(); try { verifyReadOnlyModeSupport(); ctx.state().changeGlobalState(readOnly).get(); } catch (IgniteCheckedException e) { throw U.convertException(e); } finally { unguard(); } }
Source:
<code>private boolean monitorTellsToContinue(@Nullable DeliveryStage stage) { <START> if(stage == null) { <END> return true; } if(monitor.shouldStopAfter(stage)) { throw new DeliveryStoppedByMonitorException(); } return true; }</code><technical_language>Please fix formatting</technical_language>

Target:
private boolean monitorTellsToContinue(@Nullable DeliveryStage stage) { if (stage == null) { return true; } return monitor.shouldContinueAfter(stage); }
Source:
<code>private void init(SourceManager sourceManager) { try { <START> DataManager dm = (DataManager) Services.getService(DataManager.class); <END> DataSourceFactory dsf = dm.getDataSourceFactory(); String crsName = "Unknown"; int epsgCode = -1; final int validType = SourceManager.VECTORIAL | SourceManager.RASTER | SourceManager.WMS | SourceManager.SYSTEM_TABLE; for (String sourceName : sourceNames) { int type = sourceManager.getSource(sourceName).getType(); if ((validType & type) == 0) { DataBaseRow row = new DataBaseRow(sourceName, sourceName, "public", "gid", "the_geom", crsName, epsgCode, Boolean.TRUE); data.add(row); } else if ((type & SourceManager.VECTORIAL) == SourceManager.VECTORIAL) { DataSource ds = dsf.getDataSource(sourceName); ds.open(); String geomField = ds.getFieldName(ds.getSpatialFieldIndex()); CoordinateReferenceSystem crs = ds.getCRS(); if (crs != null) { crsName = crs.getName(); epsgCode = crs.getEPSGCode(); } ds.close(); DataBaseRow row = new DataBaseRow(sourceName, sourceName, "public", "gid", geomField, crsName, epsgCode, Boolean.TRUE); row.setSpatial(true); data.add(row); } } } catch (NoSuchTableException ex) { LOGGER.error(I18N.tr("This table does not exist."), ex); } catch (DataSourceCreationException ex) { LOGGER.error(I18N.tr("The required DataSource could not be created."), ex); } catch (DriverException e) { LOGGER.error(I18N.tr("Cannot connect to the database."), e); } }</code><technical_language>useless cast. of in monomap... this is java 1.4 anymore ;-) cc @nicolas-f :p</technical_language>

Target:
private void init(SourceManager sourceManager) { try { DataManager dm = Services.getService(DataManager.class); DataSourceFactory dsf = dm.getDataSourceFactory(); String crsName = "Unknown"; int epsgCode = -1; final int validType = SourceManager.VECTORIAL | SourceManager.RASTER | SourceManager.WMS | SourceManager.SYSTEM_TABLE; for (String sourceName : sourceNames) { int type = sourceManager.getSource(sourceName).getType(); if ((validType & type) == 0) { DataBaseRow row = new DataBaseRow(sourceName, sourceName, "public", "gid", "the_geom", crsName, epsgCode, Boolean.TRUE); data.add(row); } else if ((type & SourceManager.VECTORIAL) == SourceManager.VECTORIAL) { DataSource ds = dsf.getDataSource(sourceName); ds.open(); String geomField = ds.getFieldName(ds.getSpatialFieldIndex()); CoordinateReferenceSystem crs = ds.getCRS(); if (crs != null) { crsName = crs.getName(); epsgCode = crs.getEPSGCode(); } ds.close(); DataBaseRow row = new DataBaseRow(sourceName, sourceName, "public", "gid", geomField, crsName, epsgCode, Boolean.TRUE); row.setSpatial(true); data.add(row); } } } catch (NoSuchTableException ex) { LOGGER.error(I18N.tr("This table does not exist."), ex); } catch (DataSourceCreationException ex) { LOGGER.error(I18N.tr("The required DataSource could not be created."), ex); } catch (DriverException e) { LOGGER.error(I18N.tr("Cannot connect to the database."), e); } }
Source:
<code>private UniqueIDType createTerrestrialProgrammeCridIdentifier(Broadcast broadcast) { UniqueIDType otherId = new UniqueIDType(); otherId.setAuthority(BROADCAST_AUTHORITY); Optional<Alias> alias = aliasWithNamespace(broadcast.getAliases(), TERRESTRIAL_PROGRAMME_CRID_NS); if (alias.isPresent()) { otherId.setValue(alias.get().getValue()); } <START> return otherId; <END> }</code><technical_language>error case here? return OtherIdentifier authority value. Is right? error if programme CRID</technical_language>

Target:
private UniqueIDType createTerrestrialProgrammeCridIdentifier(Broadcast broadcast) { UniqueIDType otherId = new UniqueIDType(); otherId.setAuthority(BROADCAST_AUTHORITY); Optional<Alias> alias = aliasWithNamespace(broadcast.getAliases(), TERRESTRIAL_PROGRAMME_CRID_NS); if (!alias.isPresent()) { throw new RuntimeException("Terrestrial Programme Crid Identifier not present for broadcast " + broadcast.getCanonicalUri()); } otherId.setValue(alias.get().getValue()); return otherId; }
Source:
<code>public void testTraceSet() { openTrace(trace1); openTrace(trace2); selectTrace(trace2); ITmfTrace[] expected = new ITmfTrace[] { trace2 }; Collection<ITmfTrace> actual = tm.getActiveTraceSet(); assertEquals(1, actual.size()); <START> assertArrayEquals(expected, actual.toArray(new ITmfTrace[1])); <END> }</code><technical_language>Collection.equals() compares contents, need of exact type. compare "actual" a Collections.singleton(trace2) here</technical_language>

Target:
public void testTraceSet() { openTrace(trace1); openTrace(trace2); selectTrace(trace2); Collection<ITmfTrace> expected = Collections.singleton(trace2); Collection<ITmfTrace> actual = tm.getActiveTraceSet(); assertEquals(1, actual.size()); assertEquals(expected, actual); }
Source:
<code>public void close() { log.trace("txid: close()", txid); if (summaryLog.isTraceEnabled()) { TxStats stats = tx.getStats(); String className = "N/A"; if (clazz != null) className = clazz.getSimpleName(); <START> summaryLog.trace("txid: thread : time: #read:TODO #ret: #set: #collisions: waitTime: %s committed: class: {}", txid, Thread <END> .currentThread().getId(), stats.getTime(), stats.getEntriesReturned(), stats.getEntriesSet(), stats.getCollisions(), stats.getLockWaitTime(), committed, className); } tx.close(); }</code><technical_language>This TODO in logs is a confusing. putting in code instead creating issue</technical_language>

Target:
public void close() { log.trace("txid: close()", txid); if (summaryLog.isTraceEnabled()) { TxStats stats = tx.getStats(); String className = "N/A"; if (clazz != null) className = clazz.getSimpleName(); summaryLog.trace("txid: thread : time: #ret: #set: #collisions: waitTime: %s committed: class: {}", txid, Thread .currentThread().getId(), stats.getTime(), stats.getEntriesReturned(), stats.getEntriesSet(), stats.getCollisions(), stats.getLockWaitTime(), committed, className); } tx.close(); }
Source:
<code>public void onBlockImpl(BlockSummary blockSummary) { try { logger.debug("onBlock: " + blockSummary.getBlock().getShortDescr()); if (bestBlock != null && blockSummary.getBlock().getNumber() < bestBlock.getNumber() - 16) { logger.debug("Ignoring block as too old: " + blockSummary.getBlock().getShortDescr()); return; } if (contractAddressFilter.matchBloom(new Bloom(blockSummary.getBlock().getLogBloom()))) { for (int i = 0; i < blockSummary.getReceipts().size(); i++) { TransactionReceipt receipt = blockSummary.getReceipts().get(i); if (contractAddressFilter.matchBloom(receipt.getBloomFilter())) { if (!pendings.containsKey(new ByteArrayWrapper(receipt.getTransaction().getHash()))) { ENDING state pendingState.trackTransaction(receipt.getTransaction()); } } } } <START> if (blockSummary.getTotalDifficulty().compareTo(lastTotDiff) > 0) { <END> lastTotDiff = blockSummary.getTotalDifficulty(); bestBlock = blockSummary.getBlock(); newBestBlock(blockSummary.getBlock()); } } catch (Exception e) { logger.error("Unexpected error while processing onBlock", e); } }</code><technical_language>a idea supply BlockSummary ImportStatus imported block is not. This small feature useful in other places save keeping this redundant code data structures</technical_language>

Target:
public void onBlockImpl(BlockSummary blockSummary) { if (!initialized) throw new RuntimeException("Event listener should be initialized"); try { logger.debug("onBlock: " + blockSummary.getBlock().getShortDescr()); if (bestBlock != null && blockSummary.getBlock().getNumber() < bestBlock.getNumber() - MAX_IN_REQUEST) { logger.debug("Ignoring block as too old: " + blockSummary.getBlock().getShortDescr()); return; } if (logFilter.matchBloom(new Bloom(blockSummary.getBlock().getLogBloom()))) { for (int i = 0; i < blockSummary.getReceipts().size(); i++) { TransactionReceipt receipt = blockSummary.getReceipts().get(i); if (logFilter.matchBloom(receipt.getBloomFilter())) { if (!pendings.containsKey(receipt.getTransaction().getHash())) { ENDING state pendingState.trackTransaction(receipt.getTransaction()); } } } } if (blockSummary.betterThan(lastTotDiff)) { lastTotDiff = blockSummary.getTotalDifficulty(); bestBlock = blockSummary.getBlock(); newBestBlock(blockSummary.getBlock()); } } catch (Exception e) { logger.error("Unexpected error while processing onBlock", e); } }
Source:
<code>public void logAndThrowRestLiServiceException(HttpStatus status, String msg, Exception e) { String id = UUID.randomUUID().toString(); id = id.substring(0, Math.min(6, id.length())); String cause = e == null ? "None" : e.getMessage(); <START> if (status.getCode() > 500) { <END> _logger.error("[{}] {}", id, msg, e); } else { _logger.warn("[{}] {}, cause={}", id, msg, cause); } throw new RestLiServiceException(status, String.format("msg=%s; cause=%s; instance=%s; id=%s;", msg, cause, _instance, id)); }</code><technical_language>is 500 included</technical_language>

Target:
public void logAndThrowRestLiServiceException(HttpStatus status, String msg, Exception e) { String id = UUID.randomUUID().toString(); id = id.substring(0, Math.min(6, id.length())); String cause = e == null ? "None" : e.getMessage(); if (status.getCode() >= HttpStatus.S_500_INTERNAL_SERVER_ERROR.getCode()) { _logger.error("[{}] {}", id, msg, e); } else { _logger.warn("[{}] {}, cause={}", id, msg, cause); } throw new RestLiServiceException(status, String.format("msg=%s; cause=%s; instance=%s; id=%s;", msg, cause, _instance, id)); }
Source:
<code>public void refreshItems() { if (getDataManager() != null) { try { clearItems(); <START> for (Identifiable item : getDataManager().getObjects(getBaseClass())) { <END> putItem(item.getId(), item); driversByUniqueId.put(((Driver) item).getUniqueId(), (Driver) item); } } catch (SQLException error) { Log.warning(error); } } refreshUserItems(); }</code><technical_language>I rename Identifiable. sounds interface, a class. BaseModel that. Extensible is a bad name. rename ExtendedModel that</technical_language>

Target:
public void refreshItems() { if (getDataManager() != null) { try { clearItems(); for (BaseModel item : getDataManager().getObjects(getBaseClass())) { putItem(item.getId(), item); driversByUniqueId.put(((Driver) item).getUniqueId(), (Driver) item); } } catch (SQLException error) { Log.warning(error); } } refreshUserItems(); }
Source:
<code>public synchronized List<IDockerImage> getImages(final boolean force) { synchronized (imageLock) { List<IDockerImage> latestImages = this.images; if (this.state == EnumDockerConnectionState.CLOSED) { return Collections.emptyList(); } else if (this.state == EnumDockerConnectionState.UNKNOWN) { try { open(true); <START> latestImages = getImages(force); <END> } catch (DockerException e) { Activator.log(e); } } else if (!isImagesLoaded() || force) { try { latestImages = listImages(); } catch (DockerException e) { this.images = Collections.emptyList(); Activator.log(e); } } return latestImages; } }</code><technical_language>This is change required. Locking is over-kill. want lock read write accessing of this.images field. So, if simply assign result latestImages is a local variable, is fine minimize chance of a lock wait</technical_language>

Target:
public List<IDockerImage> getImages(final boolean force) { List<IDockerImage> latestImages; synchronized (imageLock) { latestImages = this.images; } if (this.state == EnumDockerConnectionState.CLOSED) { return Collections.emptyList(); } else if (this.state == EnumDockerConnectionState.UNKNOWN) { try { open(true); latestImages = getImages(force); } catch (DockerException e) { Activator.log(e); } } else if (!isImagesLoaded() || force) { try { latestImages = listImages(); } catch (DockerException e) { synchronized (imageLock) { this.images = Collections.emptyList(); } Activator.log(e); } } return latestImages; }
Source:
<code>public final Instance runOnDemand() throws IOException { <START> Instance instance = null; <END> final AmazonEC2Client client = new AmazonEC2Client( this.credentials ); client.setEndpoint(this.region); final RunInstancesRequest request = this.createRequest(); final List<Instance> instances = client.runInstances( request ).getReservation().getInstances(); if ((instances != null) && !instances.isEmpty()) { instance = instances.get(0); } InstanceState state = instance.getState(); if (state.getCode() < 16) { final DescribeInstanceStatusRequest statusreq = new DescribeInstanceStatusRequest(); statusreq.withInstanceIds(instance.getInstanceId()); while (state.getCode() < 16) { try { TimeUnit.SECONDS.sleep(Tv.FIFTEEN); } catch (final InterruptedException ex) { continue; } final DescribeInstanceStatusResult instanceStatus = client .describeInstanceStatus(statusreq); state = instanceStatus.getInstanceStatuses().get(0) .getInstanceState(); } } return instance; }</code><technical_language>please create null instance, unable get instance, throw IllegalStateException description of happened</technical_language>

Target:
public final Instance runOnDemand() throws IOException { final AmazonEC2Client client = new AmazonEC2Client( this.credentials ); client.setEndpoint(this.region); final List<Instance> instances = client.runInstances( new RunInstancesRequest() .withKeyName(this.keyname) .withMinCount(1) .withMaxCount(1) .withInstanceType(this.type) ).getReservation().getInstances(); if (instances.isEmpty()) { throw new IllegalStateException( "No Instance was available in the RunInstanceRequest reply!" ); } final Instance instance = instances.get(0); InstanceState state = instance.getState(); if (state.getCode() < RUNNING_STATE) { final DescribeInstanceStatusRequest req = new DescribeInstanceStatusRequest(); req.withInstanceIds(instance.getInstanceId()); while (state.getCode() < RUNNING_STATE) { try { TimeUnit.SECONDS.sleep(Tv.FIFTEEN); } catch (final InterruptedException ex) { throw new IllegalArgumentException(ex); } final DescribeInstanceStatusResult instanceStatus = client .describeInstanceStatus(req); state = instanceStatus.getInstanceStatuses().get(0) .getInstanceState(); } } return instance; }
Source:
<code>void testBinary() { ToCloudEventTransformer transformer = new ToCloudEventTransformer(SOURCE, ToCloudEventTransformer.Result.BINARY); transformer.setSubjectExpression(new LiteralExpression("some_subject")); GenericMessage<String> message = new GenericMessage<>("test"); Message<?> result = transformer.transform(message); assertThat(result.getHeaders()) <START> .containsEntry("ce_type", String.class.getName()) <END> .containsEntry("ce_source", SOURCE.toString()) .containsEntry("ce_id", message.getHeaders().getId().toString()) .containsEntry("ce_subject", "some_subject") .containsKeys("ce_time", "ce_specversion") .doesNotContainKeys("ce_datacontenttype", MessageHeaders.CONTENT_TYPE, "ce_content_type"); assertThat(result.getPayload()) .isInstanceOf(byte[].class) .isEqualTo("\"test\"".getBytes()); }</code><technical_language>note need ce-* ce_ if this is for http</technical_language>

Target:
void testBinary() { ToCloudEventTransformer transformer = new ToCloudEventTransformer(SOURCE, ToCloudEventTransformer.Result.BINARY); transformer.setSubjectExpression(new LiteralExpression("some_subject")); Message<String> message = MessageBuilder.withPayload("test") .setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.TEXT_PLAIN) .build(); Message<?> result = transformer.transform(message); assertThat(result.getHeaders()) .containsEntry(CloudEventHeaders.TYPE, String.class.getName()) .containsEntry(CloudEventHeaders.SOURCE, SOURCE.toString()) .containsEntry(CloudEventHeaders.ID, message.getHeaders().getId().toString()) .containsEntry(CloudEventHeaders.SUBJECT, "some_subject") .containsEntry(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.TEXT_PLAIN_VALUE) .containsKeys(CloudEventHeaders.TIME, CloudEventHeaders.SPEC_VERSION) .doesNotContainKeys( CloudEventHeaders.DATA_CONTENT_TYPE, "ce_content_type"); assertThat(result.getPayload()) .isInstanceOf(byte[].class) .isEqualTo("test".getBytes()); }
Source:
<code>public String getFeedbackSessionName() { if (displayableFsName == null) { displayableFsName = sanitizeForHtml(bundle.feedbackSession.feedbackSessionName); <START> } <END> return displayableFsName; }</code><technical_language>done in initCommonVariables()? times called front-end, effective do if check time</technical_language>

Target:
public String getFeedbackSessionName() { return displayableFsName; }
Source:
<code>public void validatePendingStatus(final List<TransactionDto> transactionDtos) { errors = new MapBindingResult(new HashMap<String, String>(), TransactionDto.class.getName()); <START> final long pendingTransactionCount = transactionDtos.stream() <END> .filter(transactionDto -> TransactionStatus.PENDING.getValue().equalsIgnoreCase(transactionDto.getTransactionStatus())).count(); if (pendingTransactionCount != transactionDtos.size()) { this.errors.reject("transaction.wrong.transaction.status", ""); throw new ApiRequestValidationException(errors.getAllErrors()); } }</code><technical_language>more ellegant a negation of Predicate final Predicate<TransactionDto> isPendingStatus = i -> i.getTransactionStatus().equals(TransactionStatus.PENDING.getValue()); if (transactionDtos.stream().filter(isPendingStatus.negate()).count() > 0) {</technical_language>

Target:
public void validatePendingStatus(final List<TransactionDto> transactionDtos) { errors = new MapBindingResult(new HashMap<String, String>(), TransactionDto.class.getName()); final Predicate<TransactionDto> isPendingStatus = transactionDto -> transactionDto.getTransactionStatus().equals(TransactionStatus.PENDING.getValue()); if (transactionDtos.stream().filter(isPendingStatus.negate()).count() > 0) { this.errors.reject("transaction.wrong.transaction.status", ""); throw new ApiRequestValidationException(errors.getAllErrors()); } }
Source:
<code>public void activate() { <START> logger.debug("Plex binding actived"); <END> }</code><technical_language>please decrease remove this statement</technical_language>

Target:
public void activate() { logger.trace("Plex binding actived"); }
Source:
<code>public <T extends IBuildSource> T getBuildSource() { switch (asString("spec.source.type")) { case BuildSourceType.GIT: <START> return (T) new GitBuildSource(asString("spec.source.git.uri"), asString("spec.source.git.ref"), <END> asString("spec.source.contextDir")); case BuildSourceType.BINARY: return (T) new BinaryBuildSource(asString("spec.source.binary.asFile"), asString("spec.source.contextDir")); default: } return null; }</code><technical_language>constants in BuildConfig</technical_language>

Target:
public <T extends IBuildSource> T getBuildSource() { switch (asString("spec.source.type")) { case BuildSourceType.GIT: return (T) new GitBuildSource(asString(BUILDCONFIG_SOURCE_URI), asString(BUILDCONFIG_SOURCE_REF), asString(BUILDCONFIG_SOURCE_CONTEXTDIR)); case BuildSourceType.BINARY: return (T) new BinaryBuildSource(asString(BUILDCONFIG_SOURCE_BINARY_ASFILE), asString(BUILDCONFIG_SOURCE_CONTEXTDIR)); default: } return null; }
Source:
<code>public void parse() { List<String> rawSetupDefinitions = new ArrayList<String>(); List<String> lSetupDefinitions = new ArrayList<String>(); String line = ""; long startPos; long endPos; try { RandomAccessFile raf = new RandomAccessFile(file.getRawLocation() .makeAbsolute().toFile(), "r"); startPos = findStart(raf); endPos = findEnd(raf, startPos); raf.seek(startPos); while ((line = raf.readLine()) != null && raf.getFilePointer() < endPos) { rawSetupDefinitions.add(line); } lSetupDefinitions = prepareOptions(rawSetupDefinitions); for (String str : lSetupDefinitions) { parseLine(str); } <START> } catch (Exception e) { <END> StubbyLog.logError(e); } }</code><technical_language>Do catch exception actual exceptions thrown. want runtime exceptions catched way</technical_language>

Target:
public void parse() { List<String> rawSetupDefinitions = new ArrayList<String>(); List<String> lSetupDefinitions = new ArrayList<String>(); String line = ""; long startPos; long endPos; try { RandomAccessFile raf = new RandomAccessFile(file.getRawLocation() .makeAbsolute().toFile(), "r"); startPos = findStart(raf); endPos = findEnd(raf, startPos); raf.seek(startPos); while ((line = raf.readLine()) != null && raf.getFilePointer() < endPos) { rawSetupDefinitions.add(line); } lSetupDefinitions = prepareOptions(rawSetupDefinitions); for (String str : lSetupDefinitions) { parseLine(str); } raf.close(); } catch (FileNotFoundException e) { StubbyLog.logError(e); } catch (IOException e) { StubbyLog.logError(e); } }
Source:
<code>public void testValidateKafkaTopicName() { <START> Assert.fail("Should fail now"); <END> KafkaMessageChannelBinder.validateTopicName("foo:bar"); }</code><technical_language>This is a debug statement I suppose - fail test</technical_language>

Target:
public void testValidateKafkaTopicName() { KafkaMessageChannelBinder.validateTopicName("foo:bar"); }
Source:
<code>public SAMRecordComparator getComparatorInstance() { <START> if (comparatorSupplier != null) { <END> return comparatorSupplier.get(); } return null; }</code><technical_language>nan</technical_language>

Target:
public SAMRecordComparator getComparatorInstance() { return comparatorSupplier.get(); }
Source:
<code>private void addTaskContainers(AbstractTask oldTask, AbstractTask newTask) { for (AbstractTaskContainer container : oldTask.getParentContainers()) { <START> addTask(newTask, container); <END> } for (ITask subtask : oldTask.getChildren()) { addTask(subtask, newTask); } }</code><technical_language>this throws exception if task a parent is unmatched container. add a parent if new task parents parent is unmatched</technical_language>

Target:
private void addTaskContainers(AbstractTask oldTask, AbstractTask newTask) { Set<AbstractTaskContainer> containers = oldTask.getParentContainers(); if (containers.isEmpty() || (containers.size() == 1 && containers.iterator().next() instanceof UnmatchedTaskContainer)) { addTask(newTask); } else { for (AbstractTaskContainer container : containers) { addTask(newTask, container); } } for (ITask subtask : oldTask.getChildren()) { addTask(subtask, newTask); } }
Source:
<code>void initTable() { TextColumnWithTooltip<Provider> nameColumn = new TextColumnWithTooltip<Provider>() { @Override public String getValue(Provider object) { return object.getName(); } }; getTable().addColumn(nameColumn, constants.nameProvider()); TextColumnWithTooltip<Provider> descriptionColumn = new TextColumnWithTooltip<Provider>() { @Override public String getValue(Provider object) { return object.getDescription(); } }; getTable().addColumn(descriptionColumn, constants.descriptionProvider()); TextColumnWithTooltip<Provider> urlColumn = new TextColumnWithTooltip<Provider>() { @Override public String getValue(Provider object) { return object.getUrl(); } <START> }; <END> getTable().addColumn(urlColumn, constants.urlProvider()); getTable().addActionButton(new WebAdminButtonDefinition<Provider>(constants.addProvider()) { @Override protected UICommand resolveCommand() { return getMainModel().getAddCommand(); } }); getTable().addActionButton(new WebAdminButtonDefinition<Provider>(constants.removeProvider()) { @Override protected UICommand resolveCommand() { return getMainModel().getRemoveCommand(); } }); }</code><technical_language>constants widths enabling column re-sizing</technical_language>

Target:
void initTable() { getTable().enableColumnResizing(); TextColumnWithTooltip<Provider> nameColumn = new TextColumnWithTooltip<Provider>() { @Override public String getValue(Provider object) { return object.getName(); } }; getTable().addColumn(nameColumn, constants.nameProvider(), "200px"); TextColumnWithTooltip<Provider> descriptionColumn = new TextColumnWithTooltip<Provider>() { @Override public String getValue(Provider object) { return object.getDescription(); } }; getTable().addColumn(descriptionColumn, constants.descriptionProvider(), "300px"); TextColumnWithTooltip<Provider> urlColumn = new TextColumnWithTooltip<Provider>() { @Override public String getValue(Provider object) { return object.getUrl(); } }; getTable().addColumn(urlColumn, constants.urlProvider(), "200px"); getTable().addActionButton(new WebAdminButtonDefinition<Provider>(constants.addProvider()) { @Override protected UICommand resolveCommand() { return getMainModel().getAddCommand(); } }); getTable().addActionButton(new WebAdminButtonDefinition<Provider>(constants.removeProvider()) { @Override protected UICommand resolveCommand() { return getMainModel().getRemoveCommand(); } }); }
Source:
<code>public boolean isVisible() { AccountGroup accountGroup = GroupDescriptions.toAccountGroup(group); if (accountGroup != null && accountGroup.isVisibleToAll()) { <START> return true; <END> } return user instanceof InternalUser || user.getEffectiveGroups().contains(group.getGroupUUID()) || isOwner(); }</code><technical_language>enough coffee in world convince this delta is necessary</technical_language>

Target:
public boolean isVisible() { AccountGroup accountGroup = GroupDescriptions.toAccountGroup(group); return (accountGroup != null && accountGroup.isVisibleToAll()) || user instanceof InternalUser || user.getEffectiveGroups().contains(group.getGroupUUID()) || isOwner(); }
Source:
<code>public static void afterClass() throws CommandFailedException, IOException { client.apply(backup.restore()); <START> client.close(); <END> }</code><technical_language>restore fail exception => client closed in finally block</technical_language>

Target:
public static void afterClass() throws CommandFailedException, IOException { try { client.apply(backup.restore()); } finally { client.close(); } }
Source:
<code>public void stop() { if (serverThread == null) { throw new IllegalStateException("Server is not running"); } serverThread.interrupt(); <START> TrafficCounter.shutdown(); <END> }</code><technical_language>this called in finally instead? TrafficCounter is set in ServerInitializer</technical_language>

Target:
public void stop() { if (serverThread == null) { throw new IllegalStateException("Server is not running"); } serverThread.interrupt(); }
Source:
<code>public void onConfigure(SQLiteDatabase db) { if (db.isReadOnly() || !shouldEnableForeignKeyConstraints()) <START> return <END> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) db.execSQL("PRAGMA foreign_keys=ON;"); else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) db.setForeignKeyConstraintsEnabled(true); }</code><technical_language>this line compile end a semicolon</technical_language>

Target:
public void onConfigure(SQLiteDatabase db) { if (db.isReadOnly() || !shouldEnableForeignKeyConstraints()) return; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) db.setForeignKeyConstraintsEnabled(true); else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) db.execSQL("PRAGMA foreign_keys=ON;"); }
Source:
<code>public ShowInContext getShowInContext() { ITreeSelection selection = (ITreeSelection) tree.getSelection(); for (Iterator it = selection.iterator(); it.hasNext();) { if (!(it.next() instanceof IResource)) { return null; } } return new ShowInContext(null, selection); <START> } <END></code><technical_language>additionally this useful for PathNodes: IPath repoPath = getRepositoryPath(); List<IResource> resources = new ArrayList<IResource>(); ITreeSelection selection = (ITreeSelection) tree.getSelection(); for (Iterator = selection.iterator(); it.hasNext();) { Object obj = it.next(); if (obj instanceof IResource) resources.add((IResource) obj); else if (obj instanceof PathNode && repoPath != null) { PathNode pathNode = (PathNode) obj; IResource resource = ResourceUtil.getResourceForLocation(repoPath.append(pathNode.path.toString())); if (resource != null) resources.add(resource); } } return new ShowInContext(null, new StructuredSelection(resources));</technical_language>

Target:
public ShowInContext getShowInContext() { IPath repoPath = getRepositoryPath(); ITreeSelection selection = (ITreeSelection) tree.getSelection(); List<IResource> resources = new ArrayList<IResource>(); for (Iterator it = selection.iterator(); it.hasNext();) { Object obj = it.next(); if (obj instanceof IResource) resources.add((IResource) obj); else if (obj instanceof PathNode && repoPath != null) { PathNode pathNode = (PathNode) obj; IResource resource = ResourceUtil .getResourceForLocation(repoPath.append(pathNode.path .toString())); if (resource != null) resources.add(resource); } } return new ShowInContext(null, new StructuredSelection(resources)); }
Source:
<code>protected void onCreateSessionSafe(Bundle savedInstanceState) { super.onCreateSessionSafe(savedInstanceState); String menuId = getIntent().getStringExtra(SessionFrame.STATE_COMMAND_ID); if (menuId == null) { menuId = Menu.ROOT_MENU_ID; } <START> if (menuId == Menu.ROOT_MENU_ID && DispatchActivity.useRootMenuHomeActivity()) { <END> finish(); return; } MenuList.setupMenuViewInActivity(this, menuId, useGridMenu(menuId), false); }</code><technical_language>== -> .equals</technical_language>

Target:
protected void onCreateSessionSafe(Bundle savedInstanceState) { super.onCreateSessionSafe(savedInstanceState); String menuId = getIntent().getStringExtra(SessionFrame.STATE_COMMAND_ID); if (menuId == null) { menuId = Menu.ROOT_MENU_ID; } if (menuId.equals(Menu.ROOT_MENU_ID) && DispatchActivity.useRootMenuHomeActivity()) { finish(); return; } MenuList.setupMenuViewInActivity(this, menuId, useGridMenu(menuId), false); }
Source:
<code>public void testObservableWithRetrySameServer() throws Exception { IClientConfig config = DefaultClientConfigImpl.getClientConfigWithDefaultValues().withProperty(CommonClientConfigKey.ConnectTimeout, "1000"); HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("/testAsync/person"); Server badServer = new Server("localhost:12345"); Server goodServer = new Server("localhost:" + port); List<Server> servers = Lists.newArrayList(badServer, badServer, goodServer); BaseLoadBalancer lb = LoadBalancerBuilder.<Server>newBuilder() .withRule(new AvailabilityFilteringRule()) .withPing(new DummyPing()) <START> .buildFixedServerListLoadBalancer(servers); <END> LoadBalancingHttpClient<ByteBuf, ByteBuf> lbObservables = RibbonTransport.newHttpClient(lb, config, new NettyHttpLoadBalancerErrorHandler(1, true)); Observable<Person> observableWithRetries = getPersonObservable(lbObservables.submit(request)); ObserverWithLatch<Person> observer = new ObserverWithLatch<Person>(); observableWithRetries.subscribe(observer); observer.await(); ServerStats stats = lbObservables.getServerStats(badServer); assertEquals(1, stats.getTotalRequestsCount()); assertEquals(0, stats.getActiveRequestsCount()); stats = lbObservables.getServerStats(goodServer); assertEquals(1, stats.getTotalRequestsCount()); }</code><technical_language>original intention of test is a negative test. setting server list (badserver, badserver, badserver, goodserver)</technical_language>

Target:
public void testObservableWithRetrySameServer() throws Exception { IClientConfig config = DefaultClientConfigImpl.getClientConfigWithDefaultValues().withProperty(CommonClientConfigKey.ConnectTimeout, "1000"); HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet("/testAsync/person"); Server badServer = new Server("localhost:12345"); Server goodServer = new Server("localhost:" + port); List<Server> servers = Lists.newArrayList(badServer, badServer, goodServer); BaseLoadBalancer lb = LoadBalancerBuilder.<Server>newBuilder() .withRule(new AvailabilityFilteringRule()) .withPing(new DummyPing()) .buildFixedServerListLoadBalancer(servers); LoadBalancingHttpClient<ByteBuf, ByteBuf> lbObservables = RibbonTransport.newHttpClient(lb, config, new NettyHttpLoadBalancerErrorHandler(1, 0, true)); Observable<Person> observableWithRetries = getPersonObservable(lbObservables.submit(request)); ObserverWithLatch<Person> observer = new ObserverWithLatch<Person>(); observableWithRetries.subscribe(observer); observer.await(); assertNull(observer.obj); assertTrue(observer.error instanceof ClientException); ServerStats stats = lbObservables.getServerStats(badServer); assertEquals(2, stats.getTotalRequestsCount()); assertEquals(0, stats.getActiveRequestsCount()); stats = lbObservables.getServerStats(goodServer); assertEquals(0, stats.getTotalRequestsCount()); }
Source:
<code>public CreateGlusterVolumeCommand(CreateGlusterVolumeParameters params) { <START> super(params); <END> }</code><technical_language>permission is required cluster, cluster initialized in constructor, i suggest moving this line canDoAction here: setVdsGroupId(volume.getClusterId()) (of add a null check volume before) way, if volume cluster supplied, permission checked it, if not, user authorized run action</technical_language>

Target:
public CreateGlusterVolumeCommand(CreateGlusterVolumeParameters params) { super(params); volume = getParameters().getVolume(); }
Source:
<code>protected void onBind() { super.onBind(); <START> logger.info(this.getClass().toString() + " onBind"); END> updateModel(currentErrataModel); getView().getTotalSecurity().setCommand(currentErrataModel.getShowSecurityCommand()); getView().getTotalBugFix().setCommand(currentErrataModel.getShowBugsCommand()); getView().getTotalEnhancement().setCommand(currentErrataModel.getShowEnhancementsCommand()); }</code><technical_language>debug/trace/remove</technical_language>

Target:
protected void onBind() { super.onBind(); updateModel(currentErrataModel); getView().getTotalSecurity().setCommand(currentErrataModel.getShowSecurityCommand()); getView().getTotalBugFix().setCommand(currentErrataModel.getShowBugsCommand()); getView().getTotalEnhancement().setCommand(currentErrataModel.getShowEnhancementsCommand()); }
Source:
<code>public List<MetricFamilySamples> collect() { String UNKNOWN_LABEL_VALUE = "unknown"; List<MetricFamilySamples> mfs = new ArrayList<MetricFamilySamples>(); GaugeMetricFamily jvmInfo = new GaugeMetricFamily( "jvm_info", "jvm version info", Arrays.asList("version", "vendor")); jvmInfo.addMetric(Arrays.asList(System.getProperty("java.runtime.version", UNKNOWN_LABEL_VALUE), System.getProperty("java.vm.vendor", UNKNOWN_LABEL_VALUE)), 1L); mfs.add(jvmInfo); GaugeMetricFamily osInfo = new GaugeMetricFamily( <START> "os_info", <END> "os version info", Arrays.asList("name", "version", "arch")); osInfo.addMetric(Arrays.asList(System.getProperty("os.name", UNKNOWN_LABEL_VALUE), System.getProperty("os.version"), System.getProperty("os.arch", UNKNOWN_LABEL_VALUE)), 1L); mfs.add(osInfo); return mfs; }</code><technical_language>Operating system info is responsibility of application, node exporter</technical_language>

Target:
public List<MetricFamilySamples> collect() { List<MetricFamilySamples> mfs = new ArrayList<MetricFamilySamples>(); GaugeMetricFamily jvmInfo = new GaugeMetricFamily( "jvm_info", "JVM version info", Arrays.asList("version", "vendor")); jvmInfo.addMetric(Arrays.asList(System.getProperty("java.runtime.version", "unknown"), System.getProperty("java.vm.vendor", "unknown")), 1L); mfs.add(jvmInfo); return mfs; }