auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected final <C extends SolrUpdateCommand> void scheduleCommand(C command) { if (!isRunning(getCommandGroup())) { throw new IllegalStateException("Attempted to queue a SolrUpdateCommand but " + getClass().getName() + " is not initialized or has been shut down."); } if (command != null) { try { for (int i = 0; i < 5; i++) { <START> if (!commandQueue.contains(FullReindexCommand.DEFAULT_INSTANCE) && !commandQueue.contains(command)) { <END> if (commandQueue.offer(command, getQueueOfferTime(), TimeUnit.MILLISECONDS)) { return; } else if (!isRunning(getCommandGroup())) { throw new IllegalStateException("Attempted to queue a SolrUpdateCommand but " + getClass().getName() + " is not initialized or has been shut down."); } } } throw new IllegalStateException("Unable to add a Solr index update command to the queue within 5 seconds."); } catch (InterruptedException e) { throw new RuntimeException("Unexpected error occurred attempting to add a command to the queue.", e); } } }</code><technical_language>@ktisdell beginning question this condition - do want avoid queueing incremental update commands if a FullReindexCommand is in queue? I logic is totally fine if full reindex is successful, if full reindex fails, left a foreground collection updated. other hand, if _do_ queue incremental updates anyway, repeat a bit of work, _should be_ harmless</technical_language>

Target:
protected final <C extends SolrUpdateCommand> void scheduleCommand(C command) { if (!isRunning(getCommandGroup())) { throw new IllegalStateException("Attempted to queue a SolrUpdateCommand but " + getClass().getName() + " is not initialized or has been shut down."); } if (command != null) { try { for (int i = 0; i < 5; i++) { if (!commandQueue.contains(command)) { if (commandQueue.offer(command, getQueueOfferTime(), TimeUnit.MILLISECONDS)) { return; } else if (!isRunning(getCommandGroup())) { throw new IllegalStateException("Attempted to queue a SolrUpdateCommand but " + getClass().getName() + " is not initialized or has been shut down."); } } } throw new IllegalStateException("Unable to add a Solr index update command to the queue within 5 seconds."); } catch (InterruptedException e) { throw new RuntimeException("Unexpected error occurred attempting to add a command to the queue.", e); } } }
Source:
<code>public Mono<Boolean> acquireInitializationLock(Duration lockExpirationTime) { String lockId = this.getStoreLockName(); CosmosItemProperties containerDocument = new CosmosItemProperties(); containerDocument.id(lockId); BridgeInternal.setProperty(containerDocument, com.azure.data.cosmos.internal.Constants.Properties.TTL, Long.valueOf(lockExpirationTime.getSeconds()).intValue()); return this.client.createItem(this.leaseCollectionLink, containerDocument, new CosmosItemRequestOptions(lockId), false) .map(documentResourceResponse -> { if (documentResourceResponse.item() != null) { this.lockETag = documentResourceResponse.properties().etag(); return true; } else { return false; } }) .onErrorResume(throwable -> { if (throwable instanceof CosmosClientException) { CosmosClientException e = (CosmosClientException) throwable; if (e.statusCode() == ChangeFeedHelper.HTTP_STATUS_CODE_CONFLICT) { logger.info("Lease synchronization document was acquired by a different instance"); return Mono.just(false); } } <START> logger.warn("Unexpected exception thrown", throwable); <END> return Mono.error(throwable); }); }</code><technical_language>error for this too</technical_language>

Target:
public Mono<Boolean> acquireInitializationLock(Duration lockExpirationTime) { String lockId = this.getStoreLockName(); CosmosItemProperties containerDocument = new CosmosItemProperties(); containerDocument.id(lockId); BridgeInternal.setProperty(containerDocument, com.azure.data.cosmos.internal.Constants.Properties.TTL, Long.valueOf(lockExpirationTime.getSeconds()).intValue()); return this.client.createItem(this.leaseCollectionLink, containerDocument, new CosmosItemRequestOptions(lockId), false) .map(documentResourceResponse -> { if (documentResourceResponse.item() != null) { this.lockETag = documentResourceResponse.properties().etag(); return true; } else { return false; } }) .onErrorResume(throwable -> { if (throwable instanceof CosmosClientException) { CosmosClientException e = (CosmosClientException) throwable; if (e.statusCode() == ChangeFeedHelper.HTTP_STATUS_CODE_CONFLICT) { logger.info("Lease synchronization document was acquired by a different instance"); return Mono.just(false); } } logger.error("Unexpected exception thrown", throwable); return Mono.error(throwable); }); }
Source:
<code>public static DatabaseAdaptor buildDatabaseAdaptor() { DatabaseAdaptor da = new DatabaseAdaptor(); if (USE_MARIADB) { <START> da.setUsername(MARIAD_DB.getUsername()); <END> da.setPassword(MARIAD_DB.getPassword()); } da.setDriverInfo(DRIVER_CLASS, DEFAULT_CONNECTION_URL); return da; }</code><technical_language>mariadb instance a username password set?? This code pass in username password MariaDBContainer, possibly set it</technical_language>

Target:
public static DatabaseAdaptor buildDatabaseAdaptor() { DatabaseAdaptor da = new DatabaseAdaptor(); da.setDriverInfo(DRIVER_CLASS, DEFAULT_CONNECTION_URL); return da; }
Source:
<code><START> CompletableFuture<Void> asyncCompleteLocalTransaction(AdvancedCache<?, ?> cache, long timeout) { <END> return blockingHandler.runBlockingOperation(() -> { try { commitLocalTransaction(cache, xid, timeout); } catch (HeuristicMixedException e) { hasCommits = true; hasRollbacks = true; } catch (RollbackException | HeuristicRollbackException e) { hasRollbacks = true; } catch (Throwable t) { hasErrors = true; } }, this).toCompletableFuture(); }</code><technical_language>suggestion CompletionStage<Void> asyncCompleteLocalTransaction(AdvancedCache<?, ?> cache, long timeout) {</technical_language>

Target:
CompletionStage<Void> asyncCompleteLocalTransaction(AdvancedCache<?, ?> cache, long timeout) { return blockingManager.runBlocking(() -> { try { commitLocalTransaction(cache, xid, timeout); } catch (HeuristicMixedException e) { hasCommits = true; hasRollbacks = true; } catch (RollbackException | HeuristicRollbackException e) { hasRollbacks = true; } catch (Throwable t) { hasErrors = true; } }, this); }
Source:
<code>public void init() throws IOException, JAXBException { registerEntities(); transactionTemplate.execute(new TransactionCallback<Object>() { @Override public Object doInTransaction(TransactionStatus status) { try { doInit(); } catch (Exception e) { <START> throw new RuntimeException(e); <END> } return null; } }); }</code><technical_language>+1 : For Sonar recommendation</technical_language>

Target:
public void init() throws IOException, JAXBException { registerEntities(); transactionTemplate.execute((s) -> { try { doInit(); } catch (Exception e) { throw new BeanInitializationException(String.format("Failed to initialize: msg-[%s]", e.getMessage()), e); } return null; }); }
Source:
<code>public void setUp() throws Exception { Log.d(TAG, "setup key at settings"); System.setProperty("dexmaker.dexcache", InstrumentationRegistry.getContext().getCacheDir().getPath()); Log.d(TAG, "setup key at settings"); InstrumentationRegistry.getContext().getCacheDir(); <START> System.setProperty("dexmaker.dexcache", InstrumentationRegistry.getContext().getCacheDir().getPath()); <END> if (AuthenticationSettings.INSTANCE.getSecretKeyData() == null) { SecretKeyFactory keyFactory = SecretKeyFactory .getInstance("PBEWithSHA256And256BitAES-CBC-BC"); final int iterationCount = 100; final int keyLength = 256; SecretKey tempkey = keyFactory.generateSecret(new PBEKeySpec("test".toCharArray(), "abcdedfdfd".getBytes("UTF-8"), iterationCount, keyLength)); SecretKey secretKey = new SecretKeySpec(tempkey.getEncoded(), "AES"); AuthenticationSettings.INSTANCE.setSecretKey(secretKey.getEncoded()); } }</code><technical_language>this is a repeat of line 108, this intended? #Closed</technical_language>

Target:
public void setUp() throws Exception { Log.d(TAG, "setup key at settings"); System.setProperty("dexmaker.dexcache", InstrumentationRegistry.getContext().getCacheDir().getPath()); if (AuthenticationSettings.INSTANCE.getSecretKeyData() == null) { SecretKeyFactory keyFactory = SecretKeyFactory .getInstance("PBEWithSHA256And256BitAES-CBC-BC"); final int iterationCount = 100; final int keyLength = 256; SecretKey tempkey = keyFactory.generateSecret(new PBEKeySpec("test".toCharArray(), "abcdedfdfd".getBytes("UTF-8"), iterationCount, keyLength)); SecretKey secretKey = new SecretKeySpec(tempkey.getEncoded(), "AES"); AuthenticationSettings.INSTANCE.setSecretKey(secretKey.getEncoded()); } }
Source:
<code>private static boolean neitherIsThis(ExpressionTree leftExpression, ExpressionTree rightExpression) { <START> return (!(leftExpression.is(Tree.Kind.IDENTIFIER) && "this".equals(((IdentifierTree) leftExpression).name())) <END> && !(rightExpression.is(Tree.Kind.IDENTIFIER) && "this".equals(((IdentifierTree) rightExpression).name()))); }</code><technical_language>skip parenthesis, miss cases as: myObj == (this). I inline a simpler method checking expression, called for operands: java private static boolean neitherIsThis(ExpressionTree leftExpression, ExpressionTree rightExpression) { return !isThis(leftExpression) && !isThis(rightExpression); } private static boolean isThis(ExpressionTree expression) { ExpressionTree newExpression = ExpressionUtils.skipParentheses(expression); return newExpression.is(Tree.Kind.IDENTIFIER) && "this".equals(((IdentifierTree) newExpression).name(); } surprised this in API already. valuable! a dozen of similar method invocations in checks</technical_language>

Target:
private static boolean neitherIsThis(ExpressionTree leftExpression, ExpressionTree rightExpression) { return !ExpressionUtils.isThis(leftExpression) && !ExpressionUtils.isThis(rightExpression); }
Source:
<code>public int execute(AtlasDbServices fromServices, AtlasDbServices toServices) { <START> if (Stream.of(setup, migrate, validate).filter(Boolean::booleanValue).count() != 1) { <END> printer.error("Exactly one of --setup, --migrate, or --validate should be specified."); return 1; } KeyValueServiceMigrator migrator; migrator = getMigrator(fromServices, toServices); if (setup) { migrator.setup(); } if (migrate) { migrator.migrate(); migrator.cleanup(); } if (validate) { KeyValueServiceValidator validator = new KeyValueServiceValidator(fromServices.getTransactionManager(), toServices.getTransactionManager(), fromServices.getKeyValueService(), threads, batchSize, ImmutableMap.of(), (String message, KeyValueServiceMigrator.KvsMigrationMessageLevel level) -> printer.info(level.toString() + ": " + message), ImmutableSet.of()); validator.validate(true); } return 0; }</code><technical_language>This is necessary, this people running migration (all commands), I revert this</technical_language>

Target:
public int execute(AtlasDbServices fromServices, AtlasDbServices toServices) { if (!setup && !migrate && !validate) { printer.error("At least one of --setup, --migrate, or --validate should be specified."); return 1; } KeyValueServiceMigrator migrator; migrator = getMigrator(fromServices, toServices); if (setup) { migrator.setup(); } if (migrate) { migrator.migrate(); migrator.cleanup(); } if (validate) { KeyValueServiceValidator validator = new KeyValueServiceValidator(fromServices.getTransactionManager(), toServices.getTransactionManager(), fromServices.getKeyValueService(), threads, batchSize, ImmutableMap.of(), (String message, KeyValueServiceMigrator.KvsMigrationMessageLevel level) -> printer.info(level.toString() + ": " + message), ImmutableSet.of()); validator.validate(true); } return 0; }
Source:
<code>private AlluxioURI createTempUfsDir(String ufsPath) throws IOException { String path = mTestFolder.newFolder(ufsPath.split("/")).getPath(); <START> return new AlluxioURI("file:??", null, path); <END> }</code><technical_language>this file for scheme</technical_language>

Target:
private AlluxioURI createTempUfsDir(String ufsPath) throws IOException { String path = mTestFolder.newFolder(ufsPath.split("/")).getPath(); return new AlluxioURI("file", null, path); }
Source:
<code>public Subprocedure buildSubprocedure(String table, String family) { if (rss.isStopping() || rss.isStopped()) { throw new IllegalStateException("Can't start flush region subprocedure on RS: " + rss.getServerName() + ", because stopping/stopped!"); } List<HRegion> involvedRegions; try { involvedRegions = getRegionsToFlush(table); } catch (IOException e1) { throw new IllegalStateException("Failed to figure out if there is region to flush.", e1); } <START> if (involvedRegions == null && involvedRegions.isEmpty()) { <END> LOG.info("no region of is online on the {}.", table, this.rss.getServerName()); return null; } LOG.debug("Launching subprocedure to flush regions for " + table); ForeignExceptionDispatcher exnDispatcher = new ForeignExceptionDispatcher(table); Configuration conf = rss.getConfiguration(); long timeoutMillis = conf.getLong(FLUSH_TIMEOUT_MILLIS_KEY, FLUSH_TIMEOUT_MILLIS_DEFAULT); long wakeMillis = conf.getLong(FLUSH_REQUEST_WAKE_MILLIS_KEY, FLUSH_REQUEST_WAKE_MILLIS_DEFAULT); FlushTableSubprocedurePool taskManager = new FlushTableSubprocedurePool(rss.getServerName().toString(), conf, rss); return new FlushTableSubprocedure(member, exnDispatcher, wakeMillis, timeoutMillis, involvedRegions, table, family, taskManager); }</code><technical_language>||, &&</technical_language>

Target:
public Subprocedure buildSubprocedure(String table, String family) { if (rss.isStopping() || rss.isStopped()) { throw new IllegalStateException("Can't start flush region subprocedure on RS: " + rss.getServerName() + ", because stopping/stopped!"); } List<HRegion> involvedRegions; try { involvedRegions = getRegionsToFlush(table); } catch (IOException e1) { throw new IllegalStateException("Failed to figure out if there is region to flush.", e1); } if (CollectionUtils.isEmpty(involvedRegions)) { LOG.info("no region of is online on the {}.", table, this.rss.getServerName()); return null; } LOG.debug("Launching subprocedure to flush regions for " + table); ForeignExceptionDispatcher exnDispatcher = new ForeignExceptionDispatcher(table); Configuration conf = rss.getConfiguration(); long timeoutMillis = conf.getLong(FLUSH_TIMEOUT_MILLIS_KEY, FLUSH_TIMEOUT_MILLIS_DEFAULT); long wakeMillis = conf.getLong(FLUSH_REQUEST_WAKE_MILLIS_KEY, FLUSH_REQUEST_WAKE_MILLIS_DEFAULT); FlushTableSubprocedurePool taskManager = new FlushTableSubprocedurePool(rss.getServerName().toString(), conf, rss); return new FlushTableSubprocedure(member, exnDispatcher, wakeMillis, timeoutMillis, involvedRegions, table, family, taskManager); }
Source:
<code>public static boolean isFileOpen(File file) { <START> String osName = System.getProperty("os.name", "<None>"); <END> if (osName.startsWith("Windows")) { String fileName = file.getName(); File sameFileName = new File(fileName); return !file.renameTo(sameFileName); } else { String filePath = file.getAbsolutePath(); File nullFile = new File("/dev/null"); ProcessBuilder builder = new ProcessBuilder("lsof", "-c", "java", "-a", "-T", "--", filePath).redirectError(nullFile).redirectOutput(nullFile); try { Process process = builder.start(); int exitValue = process.waitFor(); return exitValue == 0; } catch (InterruptedException | IOException e) { } return false; } }</code><technical_language>commons-lang (<LINK_0></technical_language>

Target:
public static boolean isFileOpen(File file) { if (IS_OS_WINDOWS) { String fileName = file.getName(); File sameFileName = new File(fileName); return !file.renameTo(sameFileName); } else { String filePath = file.getAbsolutePath(); File nullFile = new File("/dev/null"); ProcessBuilder builder = new ProcessBuilder("lsof", "-c", "java", "-a", "-T", "--", filePath).redirectError(nullFile).redirectOutput(nullFile); try { Process process = builder.start(); int exitValue = process.waitFor(); return exitValue == 0; } catch (InterruptedException | IOException e) { } return false; } }
Source:
<code>private void writeResponse(ActionParameters params, UserLayer ulayer) throws ActionException { try { final HttpServletResponse response = params.getResponse(); response.setContentType("text/plain;charset=utf-8"); response.setCharacterEncoding("UTF-8"); JSONObject userLayer = userlayerService.parseUserLayer2JSON(ulayer); JSONHelper.putValue(userLayer, "featuresCount", ulayer.getFeatures_count()); JSONObject permissions = OskariLayerWorker.getAllowedPermissions(); JSONHelper.putValue(userLayer, "permissions", permissions); if (ulayer.getFeatures_skipped() > 0) { JSONObject featuresSkipped = new JSONObject(); JSONHelper.putValue(featuresSkipped, "featuresSkipped", ulayer.getFeatures_skipped()); JSONHelper.putValue(userLayer, "warning", featuresSkipped); } <START> response.getWriter().print(userLayer); <END> } catch (IOException e) { throw new ActionException("Failed to write response", e); } }</code><technical_language>do ResponseHelper.writeResponse(params, userLayer)</technical_language>

Target:
private void writeResponse(ActionParameters params, UserLayer ulayer) throws ActionException { JSONObject userLayer = UserLayerDataService.parseUserLayer2JSON(ulayer); JSONHelper.putValue(userLayer, "featuresCount", ulayer.getFeatures_count()); JSONObject permissions = OskariLayerWorker.getAllowedPermissions(); JSONHelper.putValue(userLayer, "permissions", permissions); if (ulayer.getFeatures_skipped() > 0) { JSONObject featuresSkipped = new JSONObject(); JSONHelper.putValue(featuresSkipped, "featuresSkipped", ulayer.getFeatures_skipped()); JSONHelper.putValue(userLayer, "warning", featuresSkipped); } ResponseHelper.writeResponse(params, userLayer); }
Source:
<code><START> private void createServiceBindings() { <END> createServiceBinding( TypeTranslatorInitiator.INSTANCE ); createServiceBinding( DatastoreServicesInitiator.INSTANCE ); createServiceBinding( DatastoreProviderInitiator.INSTANCE ); createServiceBinding( GridDialectFactoryInitiator.INSTANCE ); }</code><technical_language>I feel services kind of "hidden" in registry implementation here. In ORM is StandardSessionFactoryServiceInitiators apparently for a similar purpose. wold more transparent do similarly? entries registered in integrator instead</technical_language>

Target:
private void createServiceBindings() { for ( SessionFactoryServiceInitiator<?> inititator : OgmSessionFactoryServiceInitiators.LIST ) { createServiceBinding( inititator ); } }
Source:
<code>private boolean runAnsiblePackOvaPlaybook(String ovf, Collection<DiskImage> disks, Map<Guid, String> diskIdToPath) { String encodedOvf = genOvfParameter(ovf); AnsibleCommandBuilder command = new AnsibleCommandBuilder() <START> .hostnames(String.format("{0}:{1}", getVds().getHostName(), <END> getVds().getSshPort())) .variable("target_directory", getParameters().getDirectory()) .variable("entity_type", getParameters().getEntityType().name().toLowerCase()) .variable("ova_size", String.valueOf(calcOvaSize(disks, encodedOvf))) .variable("ova_name", getParameters().getName()) .variable("ovirt_ova_pack_ovf", encodedOvf) .variable("ovirt_ova_pack_disks", genDiskParameters(disks, diskIdToPath)) .logFileDirectory(CREATE_OVA_LOG_DIRECTORY) .logFilePrefix("ovirt-export-ova-ansible") .logFileName(getVds().getHostName()) .logFileSuffix(getCorrelationId()) .playbook(AnsibleConstants.EXPORT_OVA_PLAYBOOK); boolean succeeded = ansibleExecutor.runCommand(command).getAnsibleReturnCode() == AnsibleReturnCode.OK; if (!succeeded) { log.error("Failed to create OVA. Please check logs for more details: {}", command.logFile()); } return succeeded; }</code><technical_language>This is repetitive in places logic applied future of AnsibleCommandBuilder. instead introduce a method in AnsibleCommandBuilder perform ? i.e. if parameter of AnsibleCommandBuilder.hostnames(VDS) introduce coupling of AnsibleCommandBuilder VDS entity, resides common module, desired. However, feels error-prone host:ip format in place. If decouple two, extend AnsibleCommandBuilder AnsibleHostCommandBuilder this specific class aware of VDS/VdsStatic. do</technical_language>

Target:
private boolean runAnsiblePackOvaPlaybook(String ovf, Collection<DiskImage> disks, Map<Guid, String> diskIdToPath) { String encodedOvf = genOvfParameter(ovf); AnsibleCommandBuilder command = new AnsibleCommandBuilder() .hosts(getVds()) .variable("target_directory", getParameters().getDirectory()) .variable("entity_type", getParameters().getEntityType().name().toLowerCase()) .variable("ova_size", String.valueOf(calcOvaSize(disks, encodedOvf))) .variable("ova_name", getParameters().getName()) .variable("ovirt_ova_pack_ovf", encodedOvf) .variable("ovirt_ova_pack_disks", genDiskParameters(disks, diskIdToPath)) .logFileDirectory(CREATE_OVA_LOG_DIRECTORY) .logFilePrefix("ovirt-export-ova-ansible") .logFileName(getVds().getHostName()) .logFileSuffix(getCorrelationId()) .playbook(AnsibleConstants.EXPORT_OVA_PLAYBOOK); boolean succeeded = ansibleExecutor.runCommand(command).getAnsibleReturnCode() == AnsibleReturnCode.OK; if (!succeeded) { log.error("Failed to create OVA. Please check logs for more details: {}", command.logFile()); } return succeeded; }
Source:
<code>public <T> T readData(String path, boolean returnNullIfPathNotExists) { T data = null; try { return readData(path, null); } catch (ZkNoNodeException e) { if (!returnNullIfPathNotExists) { throw e; } } <START> return data; <END> }</code><technical_language>call _rawZkClient.readData(path, returnNullIfPathNotExists), is easier maintain code relies raw ZkClient, is initial purpose</technical_language>

Target:
public <T> T readData(String path, boolean returnNullIfPathNotExists) { checkIfPathContainsShardingKey(path); return _rawZkClient.readData(path, returnNullIfPathNotExists); }
Source:
<code>public ElementNode(AbstractNode root, AbstractNode parent, DetailAST detailAst) { super(root.getTreeInfo()); this.parent = parent; this.root = root; this.detailAst = detailAst; <START> nodeDepth = -1; <END> text = TokenUtil.getTokenName(detailAst.getType()); indexAmongSiblings = parent.getChildren().size(); createTextAttribute(); createChildren(); }</code><technical_language>@gaurabdg @rnveach suggestion - set nodeDepth constructing xpath tree nodeDepth field of AbstractNode class RootNode.nodeDepth zero this line have: nodeDepth = parent.nodeDepth + 1; all, share ideas</technical_language>

Target:
public ElementNode(AbstractNode root, AbstractNode parent, DetailAST detailAst) { super(root.getTreeInfo()); this.parent = parent; this.root = root; this.detailAst = detailAst; text = TokenUtil.getTokenName(detailAst.getType()); indexAmongSiblings = parent.getChildren().size(); setDepth(parent.getDepth() + 1); createTextAttribute(); createChildren(); }
Source:
<code>public void releaseShared( ResourceType resourceType, long... resourceIds ) { stateHolder.incrementActiveClients( this ); try { PrimitiveLongIntMap sharedLocks = sharedLockCounts[resourceType.typeId()]; PrimitiveLongIntMap exclusiveLocks = exclusiveLockCounts[resourceType.typeId()]; ConcurrentMap<Long,ForsetiLockManager.Lock> resourceTypeLocks = lockMaps[resourceType.typeId()]; for ( long resourceId : resourceIds ) { if ( releaseLocalLock( resourceType, resourceId, sharedLocks ) ) { return; } if ( !exclusiveLocks.containsKey( resourceId ) ) { <START> releaseGlobalLock( resourceTypeLocks, resourceId ); <END> } } } finally { stateHolder.decrementActiveClients(); } }</code><technical_language>This a continue, a return</technical_language>

Target:
public void releaseShared( ResourceType resourceType, long... resourceIds ) { stateHolder.incrementActiveClients( this ); try { PrimitiveLongIntMap sharedLocks = sharedLockCounts[resourceType.typeId()]; PrimitiveLongIntMap exclusiveLocks = exclusiveLockCounts[resourceType.typeId()]; ConcurrentMap<Long,ForsetiLockManager.Lock> resourceTypeLocks = lockMaps[resourceType.typeId()]; for ( long resourceId : resourceIds ) { if ( releaseLocalLock( resourceType, resourceId, sharedLocks ) ) { continue; } if ( !exclusiveLocks.containsKey( resourceId ) ) { releaseGlobalLock( resourceTypeLocks, resourceId ); } } } finally { stateHolder.decrementActiveClients(); } }
Source:
<code>public void onNarrowFillSendBox(Message message) { if(message.getType() == MessageType.PRIVATE_MESSAGE){ switchToPrivate(); streamActv.setText(message.getReplyTo(app)); messageEt.requestFocus(); } else { switchToStream(); streamActv.setText(message.getStream().getName()); topicActv.setText(message.getSubject()); <START> if (message.getSubject().equals("")) topicActv.requestFocus(); <END> else messageEt.requestFocus(); } }</code><technical_language>is for subject null? note a more Java-safe write this is: if ("".equals(message.getSubject()) ..</technical_language>

Target:
public void onNarrowFillSendBox(Message message) { if(message.getType() == MessageType.PRIVATE_MESSAGE){ switchToPrivate(); topicActv.setText(message.getReplyTo(app)); messageEt.requestFocus(); } else { switchToStream(); streamActv.setText(message.getStream().getName()); topicActv.setText(message.getSubject()); if ("".equals(message.getSubject())) topicActv.requestFocus(); else messageEt.requestFocus(); } ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY); }
Source:
<code>private String getChildDocId(Element element, String key, String name, Visibility visibility) { <START> NameSubstitutionStrategy substitutionStrategy = getConfig().getNameSubstitutionStrategy(); <END> return element.getId() + "_" + substitutionStrategy.deflate(name) + "_" + substitutionStrategy.deflate(key); }</code><technical_language>this a field create time</technical_language>

Target:
private String getChildDocId(Element element, String key, String name, Visibility visibility) { return element.getId() + "_" + this.nameSubstitutionStrategy.deflate(name) + "_" + this.nameSubstitutionStrategy.deflate(key); }
Source:
<code>public void setServerContent(Map<String, String> serverContent) { <START> Preconditions.checkNotNull(serverContent); <END> this.serverContent = serverContent; }</code><technical_language>prefer static imports for Preconditions, for improved readability consistency. do think</technical_language>

Target:
public void setServerContent(Map<String, String> serverContent) { checkNotNull(serverContent); this.serverContent = serverContent; }
Source:
<code>protected void powerOffRadioSafely() { DataConnectionTracker dcTracker = phone.mDataConnection; Message msg = dcTracker.obtainMessage(DataConnectionTracker.EVENT_CLEAN_UP_CONNECTION); msg.obj = CDMAPhone.REASON_RADIO_TURNED_OFF; if (networkType == ServiceState.RADIO_TECHNOLOGY_1xRTT) { msg.arg1 = 0; dcTracker.sendMessage(msg); Log.w(LOG_TAG, "Turn off the radio right away"); <START> hangupAndPowerOff(); <END> } else { synchronized (this) { if (!mPendingRadioPowerOffAfterDataOff) { DataConnectionTracker.State currentState = dcTracker.getState(); if (currentState != DataConnectionTracker.State.CONNECTED && currentState != DataConnectionTracker.State.DISCONNECTING && currentState != DataConnectionTracker.State.INITING) { msg.arg1 = 0; dcTracker.sendMessage(msg); if (DBG) log("Data disconnected, turn off radio right away."); hangupAndPowerOff(); } else { msg.arg1 = 1; dcTracker.sendMessage(msg); if (sendEmptyMessageDelayed(EVENT_SET_RADIO_POWER_OFF, 30000)) { if (DBG) { log("Wait upto 30s for data to disconnect, then turn off radio."); } mPendingRadioPowerOffAfterDataOff = true; } else { Log.w(LOG_TAG, "Cannot send delayed Msg, turn off radio right away."); hangupAndPowerOff(); } } } } } }</code><technical_language>other calls hangupAndPowerOff synchronized(this) blocks I suggest here. This done adding moving "out" cover entire if statement</technical_language>

Target:
protected void powerOffRadioSafely() { DataConnectionTracker dcTracker = phone.mDataConnection; Message msg = dcTracker.obtainMessage(DataConnectionTracker.EVENT_CLEAN_UP_CONNECTION); msg.obj = CDMAPhone.REASON_RADIO_TURNED_OFF; synchronized (this) { if (networkType == ServiceState.RADIO_TECHNOLOGY_1xRTT) { msg.arg1 = 0; dcTracker.sendMessage(msg); Log.w(LOG_TAG, "Turn off the radio right away"); hangupAndPowerOff(); } else { if (!mPendingRadioPowerOffAfterDataOff) { DataConnectionTracker.State currentState = dcTracker.getState(); if (currentState != DataConnectionTracker.State.CONNECTED && currentState != DataConnectionTracker.State.DISCONNECTING && currentState != DataConnectionTracker.State.INITING) { msg.arg1 = 0; dcTracker.sendMessage(msg); if (DBG) log("Data disconnected, turn off radio right away."); hangupAndPowerOff(); } else { msg.arg1 = 1; dcTracker.sendMessage(msg); if (sendEmptyMessageDelayed(EVENT_SET_RADIO_POWER_OFF, 30000)) { if (DBG) { log("Wait upto 30s for data to disconnect, then turn off radio."); } mPendingRadioPowerOffAfterDataOff = true; } else { Log.w(LOG_TAG, "Cannot send delayed Msg, turn off radio right away."); hangupAndPowerOff(); } } } } } }
Source:
<code>public static org.apache.stratos.common.beans.TenantInfoBean getTenantByDomain(String tenantDomain) throws Exception { TenantManager tenantManager = ServiceHolder.getTenantManager(); int tenantId; try { tenantId = tenantManager.getTenantId(tenantDomain); } catch (UserStoreException e) { String msg = "Error in retrieving the tenant id for the tenant domain: " + tenantDomain + "."; log.error(msg); throw new Exception(msg, e); } Tenant tenant; try { tenant = (Tenant) tenantManager.getTenant(tenantId); } catch (UserStoreException e) { String msg = "Error in retrieving the tenant from the tenant manager."; log.error(msg); throw new Exception(msg, e); } TenantInfoBean bean; try { bean = ObjectConverter .convertCarbonTenantInfoBeanToTenantInfoBean(TenantMgtUtil.initializeTenantInfoBean(tenantId, tenant)); } catch (Exception e) { <START> log.error(String.format("Couldn't find tenant for provided tenant domain. [Tenant Domain] %s", tenantDomain)); <END> return null; } bean.setFirstname(ClaimsMgtUtil.getFirstNamefromUserStoreManager(ServiceHolder.getRealmService(), tenantId)); bean.setLastname(ClaimsMgtUtil.getLastNamefromUserStoreManager(ServiceHolder.getRealmService(), tenantId)); return bean; }</code><technical_language>log.error() method call included exception object 'e'</technical_language>

Target:
public static org.apache.stratos.common.beans.TenantInfoBean getTenantByDomain(String tenantDomain) throws Exception { TenantManager tenantManager = ServiceHolder.getTenantManager(); int tenantId; try { tenantId = tenantManager.getTenantId(tenantDomain); } catch (UserStoreException e) { String msg = "Error in retrieving the tenant id for the tenant domain: " + tenantDomain + "."; log.error(msg,e); throw new Exception(msg, e); } Tenant tenant; try { tenant = (Tenant) tenantManager.getTenant(tenantId); } catch (UserStoreException e) { String msg = "Error in retrieving the tenant from the tenant manager."; log.error(msg,e); throw new Exception(msg, e); } TenantInfoBean bean; try { bean = ObjectConverter .convertCarbonTenantInfoBeanToTenantInfoBean(TenantMgtUtil.initializeTenantInfoBean(tenantId, tenant)); } catch (Exception e) { log.error(String.format("Couldn't find tenant for provided tenant domain. [Tenant Domain] %s", tenantDomain),e); return null; } bean.setFirstname(ClaimsMgtUtil.getFirstNamefromUserStoreManager(ServiceHolder.getRealmService(), tenantId)); bean.setLastname(ClaimsMgtUtil.getLastNamefromUserStoreManager(ServiceHolder.getRealmService(), tenantId)); return bean; }
Source:
<code>public Response getFirmwares(@PathParam("thingTypeUID") @ApiParam(value = "thingTypeUID") String thingTypeUID, @HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) @ApiParam(value = HttpHeaders.ACCEPT_LANGUAGE) String language) { ThingTypeUID athingTypeUID = new ThingTypeUID(thingTypeUID); <START> if (firmwareRegistry != null) { <END> Collection<Firmware> firmwares = firmwareRegistry.getFirmwares(athingTypeUID, LocaleUtil.getLocale(language)); List<FirmwareDTO> firmwareList = convertToFirmwareDTO(firmwares); return Response.ok().entity(firmwareList).build(); } else { return Response.status(Status.NO_CONTENT).build(); } }</code><technical_language>this check is needed.... is a filter implemented checks dependencies</technical_language>

Target:
public Response getFirmwares(@PathParam("thingTypeUID") @ApiParam(value = "thingTypeUID") String thingTypeUID, @HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) @ApiParam(value = HttpHeaders.ACCEPT_LANGUAGE) String language) { ThingTypeUID athingTypeUID = new ThingTypeUID(thingTypeUID); Collection<Firmware> firmwares = firmwareRegistry.getFirmwares(athingTypeUID, LocaleUtil.getLocale(language)); List<FirmwareDTO> firmwareList = convertToFirmwareDTO(firmwares); if (firmwareList.isEmpty()) { return Response.status(Status.NO_CONTENT).build(); } return Response.ok().entity(firmwareList).build(); }
Source:
<code>protected String mapRouteToService(String serviceId) { <START> if(this.serviceRouteMapper != null) { <END> return this.serviceRouteMapper.apply(serviceId); } return serviceId; }</code><technical_language>auto-configuration if regex mapper is enabled create one, default a passthru if statement here</technical_language>

Target:
protected String mapRouteToService(String serviceId) { return this.serviceRouteMapper.apply(serviceId); }
Source:
<code>public void registerDefaultActions() { if (initialized.getAndSet(true)) { <START> LOG.debug("Attempt to initialize default actions more than once!"); <END> return; } register(new StoreValueChangeAction()); register(new StoreAttributeAction()); register(new CreatePresentationModelAction()); register(new DeletePresentationModelAction()); }</code><technical_language>This want</technical_language>

Target:
public void registerDefaultActions() { if (initialized.getAndSet(true)) { LOG.warn("Attempt to initialize default actions more than once!"); return; } register(new StoreValueChangeAction()); register(new StoreAttributeAction()); register(new CreatePresentationModelAction()); register(new DeletePresentationModelAction()); }
Source:
<code>public void patchExtBadValue() throws IOException { String request = jsonParser.getJson("/ResourceIT/patchExtBadValue.req.json"); JsonNode result = jsonApiMapper.getObjectMapper().readTree(given() .contentType(JSONAPI_CONTENT_TYPE_WITH_JSON_PATCH_EXTENSION) .accept(JSONAPI_CONTENT_TYPE_WITH_JSON_PATCH_EXTENSION) .body(request) .patch("/") .then() .statusCode(HttpStatus.SC_LOCKED) .extract() .body() .asString()); JsonNode errors = result.get("errors"); assertNotNull(errors); assertEquals(errors.size(), 1); String error = errors.get(0).asText(); String expected = "TransactionException: Unique index or primary key violation:"; <START> assertTrue(error.startsWith(expected), "Error does not start with '" + expected + "' but found " + error); <END> }</code><technical_language>minor question: change equals startsWith</technical_language>

Target:
public void patchExtBadValue() throws IOException { String request = jsonParser.getJson("/ResourceIT/patchExtBadValue.req.json"); JsonNode result = jsonApiMapper.getObjectMapper().readTree(given() .contentType(JSONAPI_CONTENT_TYPE_WITH_JSON_PATCH_EXTENSION) .accept(JSONAPI_CONTENT_TYPE_WITH_JSON_PATCH_EXTENSION) .body(request) .patch("/") .then() .statusCode(HttpStatus.SC_LOCKED) .extract() .body() .asString()); JsonNode errors = result.get("errors"); assertNotNull(errors); assertEquals(errors.size(), 1); String error = errors.get(0).asText(); String expected = "TransactionException:"; assertTrue(error.startsWith(expected), "Error does not start with '" + expected + "' but found " + error); }
Source:
<code>private void updateMetaData(XWikiDocument doc, XWikiContext context) throws XWikiException { doc.removeXObjects(FeatureMetadatum.CLASS_REFERENCE); for (Feature feature : this.features) { @SuppressWarnings("unchecked") Map<String, FeatureMetadatum> metadataMap = (Map<String, FeatureMetadatum>) feature.getMetadata(); if (metadataMap.isEmpty() && feature.getNotes().isEmpty()) { continue; } BaseObject metaObject = doc.newXObject(FeatureMetadatum.CLASS_REFERENCE, context); <START> metaObject.set(PhenoTipsFeature.META_PROPERTY_NAME, ((PhenoTipsFeature) feature).getPropertyName(), <END> context); metaObject.set(PhenoTipsFeature.META_PROPERTY_VALUE, feature.getValue(), context); for (String type : metadataMap.keySet()) { PhenoTipsFeatureMetadatum metadatum = (PhenoTipsFeatureMetadatum) metadataMap.get(type); metaObject.set(type, metadatum.getId(), context); } metaObject.set("comments", feature.getNotes(), context); } }</code><technical_language>instantiate feature PhenoTipsFeature in beginning of for-loop? Saves this cast here, else work same. for updateCategories method</technical_language>

Target:
private void updateMetaData(XWikiDocument doc, XWikiContext context) throws XWikiException { doc.removeXObjects(FeatureMetadatum.CLASS_REFERENCE); for (Feature feature : this.features) { @SuppressWarnings("unchecked") Map<String, FeatureMetadatum> metadataMap = (Map<String, FeatureMetadatum>) feature.getMetadata(); if (metadataMap.isEmpty() && feature.getNotes().isEmpty()) { continue; } BaseObject metaObject = doc.newXObject(FeatureMetadatum.CLASS_REFERENCE, context); metaObject.set(PhenoTipsFeature.META_PROPERTY_NAME, feature.getPropertyName(), context); metaObject.set(PhenoTipsFeature.META_PROPERTY_VALUE, feature.getValue(), context); for (String type : metadataMap.keySet()) { PhenoTipsFeatureMetadatum metadatum = (PhenoTipsFeatureMetadatum) metadataMap.get(type); metaObject.set(type, metadatum.getId(), context); } metaObject.set("comments", feature.getNotes(), context); } }
Source:
<code>public synchronized void doPrepare(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, InterruptedException { JSONObject submittedForm = req.getSubmittedForm(); String inputReason = submittedForm.getString("shutdownReason"); <START> String shutdownReason = inputReason.isEmpty() ? null : inputReason; <END> LOGGER.log(Level.FINE, "Shutdown requested"); Jenkins.get().doQuietDown(false, 0, shutdownReason).generateResponse(req, rsp, null); }</code><technical_language>Lacks permission check. While #doQuietDown does, this logs messages permission is checked</technical_language>

Target:
public synchronized void doPrepare(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, InterruptedException { Jenkins.get().checkPermission(Jenkins.MANAGE); JSONObject submittedForm = req.getSubmittedForm(); String inputReason = submittedForm.getString("shutdownReason"); String shutdownReason = inputReason.isEmpty() ? null : inputReason; LOGGER.log(Level.FINE, "Shutdown requested"); Jenkins.get().doQuietDown(false, 0, shutdownReason).generateResponse(req, rsp, null); }
Source:
<code><START> public void setUp() throws Exception { <END> super.setUp(); impl = new HttpBreakpointManagementDaemonImpl(null); }</code><technical_language>added Override annotation</technical_language>

Target:
public void setUp() throws Exception { super.setUp(); impl = new HttpBreakpointManagementDaemonImpl(); }
Source:
<code>private @Nullable JobStatus mapStateToStatus(final States state) { <START> final JobStatus jobStatus; <END> if (States.SETUP_JOB.equals(state) && previousJobStatus == null) { jobStatus = JobStatus.INIT; } else if (States.MONITOR_JOB.equals(state) && JobStatus.INIT.equals(previousJobStatus)) { jobStatus = JobStatus.RUNNING; } else if ( States.HANDLE_ERROR.equals(state) && (JobStatus.INIT.equals(previousJobStatus) || JobStatus.RUNNING.equals(previousJobStatus))) { jobStatus = JobStatus.FAILED; } else if (States.CLEANUP_JOB.equals(state)) { jobStatus = executionContext.getFinalJobStatus(); } else { jobStatus = null; } return jobStatus; }</code><technical_language>do need call .equals here? enum ==</technical_language>

Target:
private @Nullable JobStatus mapStateToStatus(final States state) { final JobStatus jobStatus; if (States.SETUP_JOB == state && previousJobStatus == null) { jobStatus = JobStatus.INIT; } else if (States.MONITOR_JOB == state && JobStatus.INIT == previousJobStatus) { jobStatus = JobStatus.RUNNING; } else if ( States.HANDLE_ERROR == state && (JobStatus.INIT == previousJobStatus || JobStatus.RUNNING == previousJobStatus)) { jobStatus = JobStatus.FAILED; } else if (States.CLEANUP_JOB.equals(state)) { jobStatus = executionContext.getFinalJobStatus(); } else { jobStatus = null; } return jobStatus; }
Source:
<code>public Object eGet(EObject eObject, final String featureName) { if (eObject == null || featureName == null) { throw new NullPointerException(); } Optional<EStructuralFeature> feature = Iterables.tryFind( eObject.eClass().getEAllStructuralFeatures(), new Predicate<EStructuralFeature>() { @Override public boolean apply(EStructuralFeature input) { return input != null && featureName.equals(input.getName()); } }); Object result = null; if (feature.isPresent()) { result = eObject.eGet(feature.get()); } if (result instanceof Set<?>) { result = Sets.newLinkedHashSet((Set<?>)result); } else if (result instanceof Collection<?>) { result = Lists.newArrayList((Set<?>)result); <START> } <END> return result; }</code><technical_language>cast done Collection instead of Set... cover Map case</technical_language>

Target:
public Object eGet(EObject eObject, final String featureName) { if (eObject == null || featureName == null) { throw new NullPointerException(); } Optional<EStructuralFeature> feature = Iterables.tryFind( eObject.eClass().getEAllStructuralFeatures(), new Predicate<EStructuralFeature>() { @Override public boolean apply(EStructuralFeature input) { return input != null && featureName.equals(input.getName()); } }); Object result = null; if (feature.isPresent()) { result = eObject.eGet(feature.get()); } if (result instanceof Set<?>) { result = Sets.newLinkedHashSet((Set<?>)result); } else if (result instanceof EMap<?, ?>) { result = new BasicEMap<Object, Object>(((EMap<?, ?>)result).map()); } else if (result instanceof Collection<?>) { result = Lists.newArrayList((Collection<?>)result); } return result; }
Source:
<code>public void onNext(final AggregationMessage aggregationMessage) { <START> final AvroClockMsg rcvMsg = codec.decode(aggregationMessage.getData().array()); <END> final String workerId = aggregationMessage.getSourceId().toString(); switch (rcvMsg.getType()) { case RequestInitClock: final int workerClock = initializeWorkerClock(workerId); final byte[] data = codec.encode(getReplyInitialClockMessage(globalMinimumClock, workerClock)); try { aggregationMaster.send(AGGREGATION_CLIENT_NAME, workerId, data); } catch (final NetworkException e) { LOG.log(Level.INFO, "Target worker failed to receive the initial worker clock message.", e); } break; case Tick: tickClock(workerId); break; default: } }</code><technical_language>rcvMsg stand for</technical_language>

Target:
public void onNext(final AggregationMessage aggregationMessage) { final AvroClockMsg rcvMsg = codec.decode(aggregationMessage.getData().array()); final String workerId = aggregationMessage.getSourceId().toString(); switch (rcvMsg.getType()) { case RequestInitClockMsg: final int workerClock = initializeWorkerClock(workerId); final byte[] data = codec.encode(getReplyInitialClockMessage(globalMinimumClock, workerClock)); int retryCount = 0; while (true) { if (retryCount++ > MAXIMUM_RETRY_COUNTS) { throw new RuntimeException(String.format("Sending initialization message to %s has failed %d times", workerId, MAXIMUM_RETRY_COUNTS + 1)); } try { aggregationMaster.send(AGGREGATION_CLIENT_NAME, workerId, data); break; } catch (final NetworkException e) { LOG.log(Level.INFO, String.format("ClockManager failed to send initialization message to %s", workerId), e); } } break; case TickMsg: tickClock(workerId); break; default: throw new RuntimeException("Unexpected message type: " + rcvMsg.getType().toString()); } }
Source:
<code><START> @Override public long getSize(){ return managedCache.size(); } <END></code><technical_language>Incorrect</technical_language>

Target:
@Override public long getSize(){ long size = 0; for(ManagedCache<K, V> mc : managedCache){ size += mc.getSize(); } return size; }
Source:
<code>ListenableFuture<List<String>> getNames(final LabelId id, final LabelType type) { BoundStatement getNameBoundStatement = getNameStatement.bind(toLong(id), type.toValue()); final ListenableFuture<List<Row>> namesFuture = transform( session.executeAsync(getNameBoundStatement), <START> new ResultSetToRowListFunction("Found duplicate IDs for ({}, {})", id, type)); <END> return transform(namesFuture, new Function<List<Row>, List<String>>() { @Override public List<String> apply(final List<Row> rows) { final ImmutableList.Builder<String> names = ImmutableList.builder(); for (final Row row : rows) { final String name = row.getString("name"); names.add(name); } return names.build(); } }); }</code><technical_language>replace IDs names in this log message</technical_language>

Target:
ListenableFuture<List<String>> getNames(final LabelId id, final LabelType type) { BoundStatement getNameBoundStatement = getNameStatement.bind(toLong(id), type.toValue()); final ListenableFuture<List<Row>> namesFuture = transform( session.executeAsync(getNameBoundStatement), new MultipleRowLoggingFunction("Found duplicate IDs for ({}, {})", id, type)); return transform(namesFuture, new Function<List<Row>, List<String>>() { @Override public List<String> apply(final List<Row> rows) { final ImmutableList.Builder<String> names = ImmutableList.builder(); for (final Row row : rows) { final String name = row.getString("name"); names.add(name); } return names.build(); } }); }
Source:
<code>public VolumeChooserEnvironment(Table.ID tableId, ServerContext context) { this.scope = ChooserScope.TABLE; <START> this.context = context; <END> this.tableId = Objects.requireNonNull(tableId); tabletId = null; }</code><technical_language>I do need this method. I removed master branch. useful rebase yours</technical_language>

Target:
public VolumeChooserEnvironment(Table.ID tableId, ServerContext context) { this(tableId, null, context); }
Source:
<code>public void testAuthorized() throws Exception { ContextMapper classUnderTest = new ContextMapper(CONTEXT); HttpServletRequest originalRequest = createMockRequest("/a/plugins/", PLUGIN_NAME + "/" + RESOURCE); HttpServletRequest result = classUnderTest.create(originalRequest, PLUGIN_NAME); assertEquals(CONTEXT + "/a/plugins/" + PLUGIN_NAME, result.getContextPath()); assertEquals("", result.getServletPath()); assertEquals("/" + RESOURCE, result.getPathInfo()); assertEquals(CONTEXT + "/a/plugins/" + <START> (PLUGIN_NAME <END> + "/" + RESOURCE), result.getRequestURI()); }</code><technical_language>unneeded parentheses</technical_language>

Target:
public void testAuthorized() throws Exception { ContextMapper classUnderTest = new ContextMapper(CONTEXT); HttpServletRequest originalRequest = createMockRequest("/a/plugins/", PLUGIN_NAME + "/" + RESOURCE); HttpServletRequest result = classUnderTest.create(originalRequest, PLUGIN_NAME); assertEquals(CONTEXT + "/a/plugins/" + PLUGIN_NAME, result.getContextPath()); assertEquals("", result.getServletPath()); assertEquals("/" + RESOURCE, result.getPathInfo()); assertEquals(CONTEXT + "/a/plugins/" + PLUGIN_NAME + "/" + RESOURCE, result.getRequestURI()); }