auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public TayamLuminousEnigma(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{1}{W}{B}{G}"); this.addSuperType(SuperType.LEGENDARY); this.subtype.add(SubType.NIGHTMARE); this.subtype.add(SubType.BEAST); this.power = new MageInt(3); this.toughness = new MageInt(3); this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, new TayamLuminousEnigmaReplacementEffect())); PutTopCardOfLibraryIntoGraveControllerEffect millEffect = new PutTopCardOfLibraryIntoGraveControllerEffect(3); millEffect.concatBy("."); Ability ability = new SimpleActivatedAbility(Zone.BATTLEFIELD, millEffect, new GenericManaCost(3)); ability.addCost(new TayamLuminousEnigmaCost()); TayamLuminousEnigmaEffect effect = new TayamLuminousEnigmaEffect(); effect.setText(", then return a permanent card with converted mana cost 3 or less from your graveyard to the battlefield"); <START> ability.addEffect(effect); <END> this.addAbility(ability); }</code><technical_language>check if text out correctly</technical_language>

Target:
public TayamLuminousEnigma(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{1}{W}{B}{G}"); this.addSuperType(SuperType.LEGENDARY); this.subtype.add(SubType.NIGHTMARE); this.subtype.add(SubType.BEAST); this.power = new MageInt(3); this.toughness = new MageInt(3); this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, new TayamLuminousEnigmaReplacementEffect())); PutTopCardOfLibraryIntoGraveControllerEffect millEffect = new PutTopCardOfLibraryIntoGraveControllerEffect(3); millEffect.concatBy("."); Ability ability = new SimpleActivatedAbility(Zone.BATTLEFIELD, millEffect, new GenericManaCost(3)); ability.addCost(new TayamLuminousEnigmaCost()); TayamLuminousEnigmaEffect effect = new TayamLuminousEnigmaEffect(); ability.addEffect(effect); this.addAbility(ability); }
Source:
<code>public void getConditionByObsId_shouldReturnMatchingFHIRCondition() { Context.getAdministrationService().saveGlobalProperty(new GlobalProperty(FHIRConstants .CONCEPTS_CONVERTABLE_TO_CONDITIONS_STORED_AS_OBS, GLOBAL_PROPS_CONDITION_MAPPING_CONCEPT_ID_)); String openmrsAdminPersonUuid = "dagh524f-27ce-4bb2-86d6-6d1d05312bd5"; String openmrsQuestionConceptUuid = "4a5048b1-cf85-4c64-9339-7cab41e5e364"; Date openmrsDateApplies = new Date(); Person admin = Context.getPersonService().getPersonByUuid(openmrsAdminPersonUuid); Concept concept = Context.getConceptService().getConceptByUuid(openmrsQuestionConceptUuid); Obs problemAddedObs = new Obs(admin, concept, openmrsDateApplies, null); problemAddedObs.setValueNumeric(8d); problemAddedObs = Context.getObsService().saveObs(problemAddedObs, null); Condition fhirConditionForProblemAddedObs = getService().getConditionByObsId(problemAddedObs.getUuid()); <START> assertNotNull(fhirConditionForProblemAddedObs); <END> }</code><technical_language>assert null wouldnt enough add more assertions</technical_language>

Target:
public void getConditionByObsId_shouldReturnMatchingFHIRCondition() { Context.getAdministrationService().saveGlobalProperty(new GlobalProperty(FHIRConstants .CONCEPTS_CONVERTABLE_TO_CONDITIONS_STORED_AS_OBS, GLOBAL_PROPS_CONDITION_MAPPING_CONCEPT_ID)); String patientUuid = "61b38324-e2fd-4feb-95b7-9e9a2a4400df"; String conceptUuid = "4a5048b1-cf85-4c64-9339-7cab41e5e364"; Date openmrsDateApplies = new Date(); Person patient = Context.getPersonService().getPersonByUuid(patientUuid); Concept concept = Context.getConceptService().getConceptByUuid(conceptUuid); Obs problemAddedObs = new Obs(patient, concept, openmrsDateApplies, null); problemAddedObs.setValueNumeric(8d); problemAddedObs = Context.getObsService().saveObs(problemAddedObs, null); Condition fhirConditionForProblemAddedObs = getService().getConditionByObsId(problemAddedObs.getUuid()); CodingDt fhirCoding = fhirConditionForProblemAddedObs.getCode().getCoding().get(0); assertNotNull(fhirConditionForProblemAddedObs); assertEquals(patient.getUuid(), fhirConditionForProblemAddedObs.getPatient().getReference().getIdPart()); assertEquals("Patient",fhirConditionForProblemAddedObs.getPatient().getReference().getResourceType()); assertEquals(problemAddedObs.getComment(), fhirConditionForProblemAddedObs.getNotes()); assertEquals(fhirCoding.getSystem(), FHIRConstants.OPENMRS_URI); assertEquals(fhirCoding.getCode(), problemAddedObs.getConcept().getUuid()); assertEquals(fhirCoding.getDisplay(), problemAddedObs.getConcept().getName().getName()); }
Source:
<code>public EventReceiver(EventListener listener, ClientSessionFactory sessionFactory, ObjectMapper mapper) throws ActiveMQException { String queueName = EventSource.QUEUE_ADDRESS + "." + listener.getClass().getCanonicalName(); log.debug("registering listener for {}", queueName); session = sessionFactory.createSession(false, false, 0); try { session.createQueue(EventSource.QUEUE_ADDRESS, queueName, true); <START> log.debug("created new event queue " + queueName); <END> } catch (ActiveMQException e) { if (e.getType() != ActiveMQExceptionType.QUEUE_EXISTS) { throw e; } } ClientConsumer consumer = session.createConsumer(queueName); consumer.setMessageHandler(new ListenerWrapper(listener, mapper, session)); session.start(); }</code><technical_language>log.debug("created new event queue {}", queueName); please</technical_language>

Target:
public EventReceiver(EventListener listener, ClientSessionFactory sessionFactory, ObjectMapper mapper) throws ActiveMQException { String queueName = EventSource.QUEUE_ADDRESS + "." + listener.getClass().getCanonicalName(); log.debug("registering listener for {}", queueName); session = sessionFactory.createSession(false, false, 0); try { session.createQueue(EventSource.QUEUE_ADDRESS, queueName, true); log.debug("created new event queue: {}", queueName); } catch (ActiveMQException e) { if (e.getType() != ActiveMQExceptionType.QUEUE_EXISTS) { throw e; } } ClientConsumer consumer = session.createConsumer(queueName); consumer.setMessageHandler(new ListenerWrapper(listener, mapper, session)); session.start(); }
Source:
<code>protected UUID sendRequest(@NonNull ManagementClient managementClient) throws TimeoutException { Layout layout = new Layout(runtime.getLayoutView().getLayout()); boolean bootstrapped = <START> runtime.getManagementView().bootstrapManagementServer(nodeForWorkflow, layout); <END> if (!bootstrapped) { log.warn("Management server is already bootstrapped."); } CreateWorkflowResponse resp = managementClient.addNodeRequest(nodeForWorkflow); log.info("sendRequest: requested to add on orchestrator {}:{}", nodeForWorkflow, managementClient.getRouter().getHost(), managementClient.getRouter().getPort()); return resp.getWorkflowId(); }</code><technical_language>shouldnt timeoutException thrown bootstrapManagementServer caught here</technical_language>

Target:
protected UUID sendRequest(@NonNull ManagementClient managementClient) throws TimeoutException { Layout layout = new Layout(runtime.getLayoutView().getLayout()); CFUtils.getUninterruptibly(runtime.getManagementView().bootstrapManagementServer(nodeForWorkflow, layout), TimeoutException.class, NetworkException.class); CreateWorkflowResponse resp = managementClient.addNodeRequest(nodeForWorkflow); log.info("sendRequest: requested to add on orchestrator {}:{}", nodeForWorkflow, managementClient.getRouter().getHost(), managementClient.getRouter().getPort()); return resp.getWorkflowId(); }
Source:
<code>public void configure(WebSecurity web) { web.ignoring() .antMatchers( "/css report", "/perftest monitor", "/perftest graph", "/check/**", "/agent/download/**", "/monitor/download/**", <START> "/jnlp/**", <END> "/sign_up/**" ).and().expressionHandler(defaultWebSecurityExpressionHandler); }</code><technical_language>remove out jnlp. anymore</technical_language>

Target:
public void configure(WebSecurity web) { web.ignoring() .antMatchers( "/css report", "/perftest monitor", "/perftest graph", "/check/**", "/agent/download/**", "/monitor/download/**", "/sign_up/**" ).and().expressionHandler(defaultWebSecurityExpressionHandler); }
Source:
<code>default Block getPositions(int[] positions, int offset, int length) { checkValidPositionsArray(positions, offset, length); <START> int[] ids = length == positions.length ? positions : Arrays.copyOfRange(positions, offset, offset + length); <END> return new DictionaryBlock(this, ids); }</code><technical_language>readable. Also, consider DictionaryBlock constructor takes idsOffset instead of copying array</technical_language>

Target:
default Block getPositions(int[] positions, int offset, int length) { checkArrayRange(positions, offset, length); return new DictionaryBlock(offset, length, this, positions, false, randomDictionaryId()); }
Source:
<code>private void addArrivedRecordsInput(PrefetchRecordsRetrieved recordsRetrieved) throws InterruptedException { wasReset = false; <START> while (!publisherSession.prefetchRecordsQueue().offer(recordsRetrieved, idleMillisBetweenCalls, TimeUnit.MILLISECONDS)) { <END> resetLock.readLock().unlock(); resetLock.readLock().lock(); if (wasReset) { throw new PositionResetException(); } } publisherSession.prefetchCounters().added(recordsRetrieved.processRecordsInput); }</code><technical_language>this encapsulated in publisherSession? i.e. offerRecords(recordsRetrieved) update prefetched counters (line # 312) get updated if/when offer accepted</technical_language>

Target:
private void addArrivedRecordsInput(PrefetchRecordsRetrieved recordsRetrieved) throws InterruptedException { wasReset = false; while (!publisherSession.offerRecords(recordsRetrieved, idleMillisBetweenCalls)) { resetLock.readLock().unlock(); resetLock.readLock().lock(); if (wasReset) { throw new PositionResetException(); } } publisherSession.prefetchCounters().added(recordsRetrieved.processRecordsInput); }
Source:
<code>public synchronized void onHeaders(Response response) { long length = response.getHeaders().getLongField(HttpHeader.CONTENT_LENGTH.asString()); if (length > maxLength) { response.abort(new ResponseTooLargeException()); } <START> allocateCurrentArray(); <END> }</code><technical_language>This is needed</technical_language>

Target:
public synchronized void onHeaders(Response response) { long length = response.getHeaders().getLongField(HttpHeader.CONTENT_LENGTH.asString()); if (length > maxLength) { response.abort(new ResponseTooLargeException()); } }
Source:
<code>private void removeUI() { if (replyToBox != null) { replyToBox.unregisterReplyBox(); } Side side = comment.side(); removeFromParent(); if (!getCommentInfo().has_line()) { parent.removeFileCommentBox(this, side); return; } <START> parent.removeDraft(this, comment.side(), comment.line() - 1); <END> getSelfWidget().clear(); PaddingManager manager = getPaddingManager(); manager.remove(this); manager.resizePaddingWidget(); cm.focus(); }</code><technical_language>side variable above</technical_language>

Target:
private void removeUI() { if (replyToBox != null) { replyToBox.unregisterReplyBox(); } Side side = comment.side(); removeFromParent(); if (!getCommentInfo().has_line()) { parent.removeFileCommentBox(this, side); return; } parent.removeDraft(this, side, comment.line() - 1); getSelfWidget().clear(); PaddingManager manager = getPaddingManager(); manager.remove(this); manager.resizePaddingWidget(); cm.focus(); }
Source:
<code>private boolean lock(InvocationContext ctx, Object key, long timeoutMillis) throws InterruptedException { if (lockAndRecord(key, ctx, timeoutMillis)) { ctx.addLockedKey(key); return true; } else { Object owner = getOwner(key); if (key instanceof MarshalledValue) { key = ((MarshalledValue) key).get(); } String messagePreamble = rpcManager == null ? "Unable to acquire lock" : "Unable to acquire lock on [" + rpcManager.getAddress() + "]"; <START> throw new TimeoutException(messagePreamble + " after [" + Util.prettyPrintTime(timeoutMillis) + "] for key [" <END> + key + "] and requestor [" + ctx.getLockOwner() + "]! Lock is held by [" + owner + "] while lock request came from [" + ctx.getOrigin() + "]"); } }</code><technical_language>This a good time change this fire exception log object, i.e. org.infinispan.util.logging.Log.invalidConfigurationIndexingWithInvalidation</technical_language>

Target:
private boolean lock(InvocationContext ctx, Object key, long timeoutMillis) throws InterruptedException { if (lockAndRecord(key, ctx, timeoutMillis)) { ctx.addLockedKey(key); return true; } else { Object owner = getOwner(key); if (key instanceof MarshalledValue) { key = ((MarshalledValue) key).get(); } throw log.unableToAcquireLock(Util.prettyPrintTime(timeoutMillis), key, ctx.getLockOwner(), owner, ctx.getOrigin()); } }
Source:
<code>private void validateFlowTriggerBean(final FlowTriggerBean flowTriggerBean) { <START> Preconditions.checkArgument(flowTriggerBean.getMaxWaitMins() >= 1, "max wait min must be " <END> + "longer than 1 min"); validateSchedule(flowTriggerBean); validateTriggerDependencies(flowTriggerBean.getTriggerDependencies()); }</code><technical_language>Define numbers "2" "1" in constants</technical_language>

Target:
private void validateFlowTriggerBean(final FlowTriggerBean flowTriggerBean) { Preconditions.checkArgument(flowTriggerBean.getMaxWaitMins() >= Constants .MIN_FLOW_TRIGGER_WAIT_TIME.toMinutes(), "max wait min must be longer than " + Constants .MIN_FLOW_TRIGGER_WAIT_TIME + " min "); validateSchedule(flowTriggerBean); validateTriggerDependencies(flowTriggerBean.getTriggerDependencies()); }
Source:
<code>public synchronized boolean add(T t) { legacyInstances.add(new ExtensionComponent<T>(t)); if(extensions!=null) { List<ExtensionComponent<T>> r = new ArrayList<ExtensionComponent<T>>(extensions); r.add(new ExtensionComponent<T>(t)); extensions = sort(r); <START> fireOnChangeListeners(); <END> } return true; }</code><technical_language>want listeners lock</technical_language>

Target:
public boolean add(T t) { try { return addSync(t); } finally { if(extensions!=null) { fireOnChangeListeners(); } } }
Source:
<code>public void start() { queue.start(); if (srvInfo.getState() == ServerInformation.State.STARTUP && queue.replicateAllOnPluginStart) { ReplicationState state = <START> new ReplicationState(ReplicationType.START_UP); <END> pushAllFuture.set(pushAll.create(null, state).schedule(30, TimeUnit.SECONDS)); } }</code><technical_language>ServerInformation.State STARTUP (no underscore) in line 47, while START_UP (with underscore) here. I do a preference way, prefer stay consistent other</technical_language>

Target:
public void start() { queue.start(); if (srvInfo.getState() == ServerInformation.State.STARTUP && queue.replicateAllOnPluginStart) { ReplicationState state = new ReplicationState(ReplicationType.STARTUP); pushAllFuture.set(pushAll.create(null, state).schedule(30, TimeUnit.SECONDS)); } }
Source:
<code>public void setShouldDetectFaces(boolean shouldDetectFaces) { <START> if (shouldDetectFaces && !mFaceDetector) { <END> setupFaceDetector(); } this.mShouldDetectFaces = shouldDetectFaces; setScanning(mShouldDetectFaces || mShouldDetectBarcodes || mShouldScanBarCodes || mShouldRecognizeText); }</code><technical_language>too, mFaceDetector == null</technical_language>

Target:
public void setShouldDetectFaces(boolean shouldDetectFaces) { if (shouldDetectFaces && mFaceDetector == null) { setupFaceDetector(); } this.mShouldDetectFaces = shouldDetectFaces; setScanning(mShouldDetectFaces || mShouldDetectBarcodes || mShouldScanBarCodes || mShouldRecognizeText); }
Source:
<code>public RangeSet<String> getDimensionRangeSet(String dimension) { <START> if (!Objects.equals(getDimension(), dimension) || getExtractionFn() != null || !ordering.equals(StringComparatorType.LEXICOGRAPHIC)) { <END> return null; } RangeSet<String> retSet = TreeRangeSet.create(); Range<String> range; if (getLower() == null) { range = isUpperStrict() ? Range.lessThan(getUpper()) : Range.atMost(getUpper()); } else if (getUpper() == null) { range = isLowerStrict() ? Range.greaterThan(getLower()) : Range.atLeast(getLower()); } else { range = Range.range(getLower(), isLowerStrict() ? BoundType.OPEN : BoundType.CLOSED, getUpper(), isUpperStrict() ? BoundType.OPEN : BoundType.CLOSED); } retSet.add(range); return retSet; }</code><technical_language>hmm, this easier read a of ANDs of NOTs</technical_language>

Target:
public RangeSet<String> getDimensionRangeSet(String dimension) { if (!(Objects.equals(getDimension(), dimension) && getExtractionFn() == null && ordering.equals(StringComparators.LEXICOGRAPHIC))) { return null; } RangeSet<String> retSet = TreeRangeSet.create(); Range<String> range; if (getLower() == null) { range = isUpperStrict() ? Range.lessThan(getUpper()) : Range.atMost(getUpper()); } else if (getUpper() == null) { range = isLowerStrict() ? Range.greaterThan(getLower()) : Range.atLeast(getLower()); } else { range = Range.range(getLower(), isLowerStrict() ? BoundType.OPEN : BoundType.CLOSED, getUpper(), isUpperStrict() ? BoundType.OPEN : BoundType.CLOSED); } retSet.add(range); return retSet; }
Source:
<code>@Test public void createWithDensity() { Context context = mock(Context.class); Resources resources = mock(Resources.class); DisplayMetrics displayMetrics = new DisplayMetrics(); when(context.getResources()).thenReturn(resources); when(resources.getDisplayMetrics()).thenReturn(displayMetrics); displayMetrics.densityDpi = DisplayMetrics.DENSITY_XHIGH; <START> int[] densities = new int[] { <END> DisplayMetrics.DENSITY_MEDIUM, DisplayMetrics.DENSITY_HIGH, DisplayMetrics.DENSITY_XHIGH, DisplayMetrics.DENSITY_XXHIGH }; for (int density : densities) { Request data = new Request.Builder(URI_1).density(density).build(); BitmapFactory.Options options = createBitmapOptions(data, context); assertThat(options.inDensity).isEqualTo(density); assertThat(options.inTargetDensity).isEqualTo(DisplayMetrics.DENSITY_XHIGH); } }</code><technical_language>supernit: need new int[] right</technical_language>

Target:
@Test public void createWithDensity() { Context context = mock(Context.class); Resources resources = mock(Resources.class); DisplayMetrics displayMetrics = new DisplayMetrics(); when(context.getResources()).thenReturn(resources); when(resources.getDisplayMetrics()).thenReturn(displayMetrics); displayMetrics.densityDpi = DisplayMetrics.DENSITY_XHIGH; int[] densities = { DisplayMetrics.DENSITY_MEDIUM, DisplayMetrics.DENSITY_HIGH, DisplayMetrics.DENSITY_XHIGH, DisplayMetrics.DENSITY_XXHIGH }; for (int density : densities) { Request data = new Request.Builder(URI_1).originalDensity(density).build(); BitmapFactory.Options options = createBitmapOptions(data, context); assertThat(options.inDensity).isEqualTo(density); assertThat(options.inTargetDensity).isEqualTo(DisplayMetrics.DENSITY_XHIGH); } }
Source:
<code><START> public CompletableFuture<AsyncConnection> createAsyncConnection() throws IOException { <END> return ConnectionFactory.createAsyncConnection(configuration); }</code><technical_language>return AsyncConnection instead of CompletableFuture<AsyncConnection></technical_language>

Target:
public AsyncConnection createAsyncConnection() throws Exception { return ConnectionFactory.createAsyncConnection(configuration).get(); }
Source:
<code>protected void syncSearch() { if (getEntity() == null) { return; } super.syncSearch(); AsyncQuery _asyncQuery = new AsyncQuery(); _asyncQuery.setModel(this); _asyncQuery.asyncCallback = new INewAsyncCallback() { @Override public void onSuccess(Object model, Object ReturnValue) { SearchableListModel searchableListModel = (SearchableListModel) model; ArrayList<StorageDomain> domains = (ArrayList<StorageDomain>) ((VdcQueryReturnValue) ReturnValue).getReturnValue(); for (StorageDomain domain : domains) { <START> String guid = <END> domain.getStoragePoolId() != null ? domain.getStoragePoolId().toString() : Guid.Empty.toString(); domain.setId(domain.getStoragePoolId()); } searchableListModel.setItems(domains); setIsEmpty(((List) searchableListModel.getItems()).size() == 0); } }; IdQueryParameters tempVar = new IdQueryParameters(getEntity().getId()); tempVar.setRefresh(getIsQueryFirstTime()); Frontend.getInstance().runQuery(VdcQueryType.GetStorageDomainListById, tempVar, _asyncQuery); }</code><technical_language>lines redundant now, please remove..</technical_language>

Target:
protected void syncSearch() { if (getEntity() == null) { return; } super.syncSearch(); AsyncQuery _asyncQuery = new AsyncQuery(); _asyncQuery.setModel(this); _asyncQuery.asyncCallback = new INewAsyncCallback() { @Override public void onSuccess(Object model, Object ReturnValue) { SearchableListModel searchableListModel = (SearchableListModel) model; ArrayList<StorageDomain> domains = (ArrayList<StorageDomain>) ((VdcQueryReturnValue) ReturnValue).getReturnValue(); for (StorageDomain domain : domains) { domain.setId(domain.getStoragePoolId()); } searchableListModel.setItems(domains); setIsEmpty(((List) searchableListModel.getItems()).size() == 0); } }; IdQueryParameters tempVar = new IdQueryParameters(getEntity().getId()); tempVar.setRefresh(getIsQueryFirstTime()); Frontend.getInstance().runQuery(VdcQueryType.GetStorageDomainListById, tempVar, _asyncQuery); }
Source:
<code><START> protected Optional<PlanNodeStatsEstimate> visitNotExpression(NotExpression node, Void context) <END> { if (node.getValue() instanceof IsNullPredicate) { return process(new IsNotNullPredicate(((IsNullPredicate) node.getValue()).getValue())); } return process(node.getValue()).map(estimate -> differenceInStats(input, estimate)); }</code><technical_language>get rid of Optional (as in ComparisonCalculator)</technical_language>

Target:
protected PlanNodeStatsEstimate visitNotExpression(NotExpression node, Void context) { if (node.getValue() instanceof IsNullPredicate) { return process(new IsNotNullPredicate(((IsNullPredicate) node.getValue()).getValue())); } return differenceInStats(input, process(node.getValue())); }
Source:
<code>public String generateUserDelegationSas(BlobServiceSasSignatureValues blobServiceSasSignatureValues, UserDelegationKey userDelegationKey) { <START> return getBlobAsyncClient().generateUserDelegationSas(blobServiceSasSignatureValues, userDelegationKey); <END> }</code><technical_language>implementation of this method generateSas live in this class instead of BlobAsyncClient BlobAsyncClientBase is super class BlobAsyncClient? This common practice super class sub-classes implementation. Additionally moving implementation means AppendBlobAsyncClient, BlockBlobAsyncClient, PageBlobAsyncClient get implementation for free</technical_language>

Target:
public String generateUserDelegationSas(BlobServiceSasSignatureValues blobServiceSasSignatureValues, UserDelegationKey userDelegationKey) { return new BlobSasImplUtil(blobServiceSasSignatureValues, getContainerName(), getBlobName(), getSnapshotId()) .generateUserDelegationSas(userDelegationKey, getAccountName()); }
Source:
<code>protected boolean checkExistingStorageDomain() { if (getParameters().getStorageDomain().getStorageDomainType() == StorageDomainType.Data <START> && !FeatureSupported.importDataStorageDomain(getVds().getVdsGroupCompatibilityVersion())) { <END> return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_IMPORT_DATA_DOMAIN_IS_NOT_SUPPORTED); } if (DbFacade.getInstance().getStorageDomainStaticDao().get(getStorageDomain().getId()) != null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_NOT_EXIST); } List<Guid> storageIds = (ArrayList<Guid>) runVdsCommand(VDSCommandType.HSMGetStorageDomainsList, new HSMGetStorageDomainsListVDSCommandParameters(getVdsId(), Guid.Empty, getStorageDomain() .getStorageType(), getStorageDomain().getStorageDomainType(), "") ).getReturnValue(); if (!storageIds.contains(getStorageDomain().getId())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_ALREADY_EXIST); } Pair<StorageDomainStatic, SANState> domainFromIrs = (Pair<StorageDomainStatic, SANState>) runVdsCommand( VDSCommandType.HSMGetStorageDomainInfo, new HSMGetStorageDomainInfoVDSCommandParameters(getVdsId(), getStorageDomain().getId()) ).getReturnValue(); if (domainFromIrs.getFirst().getStorageDomainType() != getStorageDomain().getStorageDomainType()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_CANNOT_CHANGE_STORAGE_DOMAIN_TYPE); } return concreteCheckExistingStorageDomain(domainFromIrs); }</code><technical_language>done vs. DC compatibility version</technical_language>

Target:
protected boolean checkExistingStorageDomain() { if (DbFacade.getInstance().getStorageDomainStaticDao().get(getStorageDomain().getId()) != null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_NOT_EXIST); } List<Guid> storageIds = (ArrayList<Guid>) runVdsCommand(VDSCommandType.HSMGetStorageDomainsList, new HSMGetStorageDomainsListVDSCommandParameters(getVdsId(), Guid.Empty, getStorageDomain() .getStorageType(), getStorageDomain().getStorageDomainType(), "") ).getReturnValue(); if (!storageIds.contains(getStorageDomain().getId())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_ALREADY_EXIST); } Pair<StorageDomainStatic, Guid> domainFromIrs = (Pair<StorageDomainStatic, Guid>) runVdsCommand( VDSCommandType.HSMGetStorageDomainInfo, new HSMGetStorageDomainInfoVDSCommandParameters(getVdsId(), getStorageDomain().getId()) ).getReturnValue(); if (domainFromIrs.getFirst().getStorageDomainType() != getStorageDomain().getStorageDomainType()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_CANNOT_CHANGE_STORAGE_DOMAIN_TYPE); } return concreteCheckExistingStorageDomain(domainFromIrs); }
Source:
<code>public void dispose() { repoImage.dispose(); <START> for (Image image : images) { <END> image.dispose(); } }</code><technical_language>style nit: braces single line blocks</technical_language>

Target:
public void dispose() { repoImage.dispose(); for (Image image : images) image.dispose(); }
Source:
<code>public Closeable addServerCache(ImmutableBytesPtr cacheId, ImmutableBytesWritable cachePtr, byte[] txState, ServerCacheFactory cacheFactory, boolean useProtoForIndexMaintainer, boolean usePersistentCache, int clientVersion) throws SQLException { getServerCaches().cleanUp(); long available = this.getMemoryManager().getAvailableMemory(); int size = cachePtr.getLength() + txState.length; if (size > available) { <START> evictInactiveEntries(Math.max(size - available + EVICTION_MARGIN_BYTES, EVICTION_MARGIN_BYTES)); <END> } MemoryChunk chunk = this.getMemoryManager().allocate(size); boolean success = false; try { CacheEntry entry; synchronized(this) { entry = getIfPresent(cacheId); if (entry == null) { entry = new CacheEntry( cacheId, cachePtr, cacheFactory, txState, chunk, usePersistentCache, useProtoForIndexMaintainer, clientVersion); getServerCaches().put(cacheId, entry); available = this.getMemoryManager().getAvailableMemory(); if (usePersistentCache) { getPersistentServerCaches().put(cacheId, entry); } } entry.incrementLiveQueryCount(); } success = true; return entry; } finally { if (!success) { Closeables.closeAllQuietly(Collections.singletonList(chunk)); } } }</code><technical_language>scary points (that I hope I missed scanning): * I a update GlobalMemoryManager. accounting for size of persistentServerCaches else? * Do users execute queries persistentCaches ability deny queries of users running persistentCaches (by saturating total RS's serverCache). 30min default timeout start evicting persistentCaches worry a long time</technical_language>

Target:
public Closeable addServerCache(ImmutableBytesPtr cacheId, ImmutableBytesWritable cachePtr, byte[] txState, ServerCacheFactory cacheFactory, boolean useProtoForIndexMaintainer, boolean usePersistentCache, int clientVersion) throws SQLException { getServerCaches().cleanUp(); long available = this.getMemoryManager().getAvailableMemory(); int size = cachePtr.getLength() + txState.length; if (size > available) { evictInactiveEntries(size - available + EVICTION_MARGIN_BYTES); } MemoryChunk chunk = this.getMemoryManager().allocate(size); boolean success = false; try { CacheEntry entry; synchronized(this) { entry = getIfPresent(cacheId); if (entry == null) { entry = new CacheEntry( cacheId, cachePtr, cacheFactory, txState, chunk, usePersistentCache, useProtoForIndexMaintainer, clientVersion); getServerCaches().put(cacheId, entry); if (usePersistentCache) { getPersistentServerCaches().put(cacheId, entry); } } entry.incrementLiveQueryCount(); } success = true; return entry; } finally { if (!success) { Closeables.closeAllQuietly(Collections.singletonList(chunk)); } } }
Source:
<code>public boolean onHttpRequestSend(HttpMessage msg) { try { String url = msg.getRequestHeader().getURI().toString(); String path = msg.getRequestHeader().getURI().getPath(); LOGGER.debug("Callback received for URL : " + url + " path : " + path + " from " + msg.getRequestHeader().getSenderAddress()); if (path.startsWith("/" + TEST_PREFIX)) { String str = Constant.messages.getString( "callback.test.msg", url, msg.getRequestHeader() .getSenderAddress().toString()); if (View.isInitialised()) { View.getSingleton().getOutputPanel() .appendAsync(str + "\n"); } LOGGER.info(str); <START> callBackReceived(Constant.messages.getString("callback.handler.test.name"), msg.cloneAll()); <END> return true; } else if (path.startsWith("/favicon.ico")) { return true; } for (Entry<String, CallbackImplementor> callback : callbacks .entrySet()) { if (path.startsWith(callback.getKey())) { HttpMessage clonedMsg = msg.cloneAll(); CallbackImplementor implementor = callback.getValue(); implementor.handleCallBack(clonedMsg); callBackReceived(implementor.getClass().getSimpleName(), clonedMsg); return true; } } callBackReceived(Constant.messages.getString("callback.handler.none.name"), msg.cloneAll()); LOGGER.error("No callback handler for URL : " + url + " from " + msg.getRequestHeader().getSenderAddress()); } catch (URIException e) { LOGGER.error(e.getMessage(), e); } return true; }</code><technical_language>avoid cloning here? (The message is modified view?)</technical_language>

Target:
public boolean onHttpRequestSend(HttpMessage msg) { try { msg.setTimeSentMillis(new Date().getTime()); String url = msg.getRequestHeader().getURI().toString(); String path = msg.getRequestHeader().getURI().getPath(); LOGGER.debug("Callback received for URL : " + url + " path : " + path + " from " + msg.getRequestHeader().getSenderAddress()); msg.setResponseHeader(HttpHeader.HTTP11 + " " + HttpStatusCode.OK); if (path.startsWith("/" + TEST_PREFIX)) { String str = Constant.messages.getString( "callback.test.msg", url, msg.getRequestHeader() .getSenderAddress().toString()); if (View.isInitialised()) { View.getSingleton().getOutputPanel() .appendAsync(str + "\n"); } LOGGER.info(str); callbackReceived(Constant.messages.getString("callback.handler.test.name"), msg); return true; } else if (path.startsWith("/favicon.ico")) { return true; } for (Entry<String, CallbackImplementor> callback : callbacks .entrySet()) { if (path.startsWith(callback.getKey())) { CallbackImplementor implementor = callback.getValue(); implementor.handleCallBack(msg.cloneAll()); callbackReceived(implementor.getClass().getSimpleName(), msg); return true; } } callbackReceived(Constant.messages.getString("callback.handler.none.name"), msg); LOGGER.error("No callback handler for URL : " + url + " from " + msg.getRequestHeader().getSenderAddress()); } catch (URIException | HttpMalformedHeaderException e) { LOGGER.error(e.getMessage(), e); } return true; }
Source:
<code>private boolean isCurrentUserAdmin() { <START> String token = httpServletRequest.getHeader(AuthenticationFilter.TOKEN_REQUEST_HEADER_PARAM); <END> if (token != null) { Account account = accountRepository.findByToken(token); return account.getMember().getROLES().contains(Role.ADMIN); } return false; }</code><technical_language>Oops right... If REST service is public currentUser is loaded isolate this code portion in a service in <LINK_0> If need reuse this feature</technical_language>

Target:
private boolean isCurrentUserAdmin() { CurrentUser currentUser = applicationContext.getBean(CurrentUser.class); if (currentUser == null || !currentUser.getCredentials().isPresent()) { return false; } return currentUser.getCredentials().get().getMember().getROLES().contains(Role.ADMIN); }
Source:
<code><START> private void handleReturnStatement(SubscriptionContext ctx, PyReturnStatementTree retStmt) { <END> if (retStmt.expressions().size() == 1) { PyExpressionTree expr = retStmt.expressions().get(0); if ((expr.is(Tree.Kind.PARENTHESIZED) || (expr.is(Tree.Kind.TUPLE) && !((PyTupleTree) expr).elements().isEmpty())) && expr.firstToken().getLine() == expr.lastToken().getLine()) { ctx.addIssue(expr, String.format(MESSAGE, "return")); } } }</code><technical_language>This method static</technical_language>

Target:
private static void handleReturnStatement(SubscriptionContext ctx, PyReturnStatementTree retStmt) { if (retStmt.expressions().size() == 1) { PyExpressionTree expr = retStmt.expressions().get(0); if ((expr.is(Tree.Kind.PARENTHESIZED) || (expr.is(Tree.Kind.TUPLE) && !((PyTupleTree) expr).elements().isEmpty())) && expr.firstToken().getLine() == expr.lastToken().getLine()) { ctx.addIssue(expr, String.format(MESSAGE, "return")); } } }
Source:
<code>public void postCollectionAdminGroupCreateAdminGroupUnAuthorized() throws Exception { ObjectMapper mapper = new ObjectMapper(); GroupRest groupRest = new GroupRest(); MetadataRest metadataRest = new MetadataRest(); metadataRest.put("dc.description", new MetadataValueRest("testingDescription")); metadataRest.put("dc.subject", new MetadataValueRest("testSubject")); groupRest.setMetadata(metadataRest); getClient().perform(post("/api/core/collections/" + collection.getID() + "/adminGroup") .content(mapper.writeValueAsBytes(groupRest)) .contentType(contentType)) .andExpect(status().isUnauthorized()); <START> <END> }</code><technical_language>double check group created a get</technical_language>

Target:
public void postCollectionAdminGroupCreateAdminGroupUnAuthorized() throws Exception { ObjectMapper mapper = new ObjectMapper(); GroupRest groupRest = new GroupRest(); MetadataRest metadataRest = new MetadataRest(); metadataRest.put("dc.description", new MetadataValueRest("testingDescription")); metadataRest.put("dc.subject", new MetadataValueRest("testSubject")); groupRest.setMetadata(metadataRest); getClient().perform(post("/api/core/collections/" + collection.getID() + "/adminGroup") .content(mapper.writeValueAsBytes(groupRest)) .contentType(contentType)) .andExpect(status().isUnauthorized()); String token = getAuthToken(admin.getEmail(), password); getClient(token).perform(get("/api/core/collections/" + collection.getID() + "/adminGroup")) .andExpect(status().isNoContent()); }
Source:
<code><START> public void readRowsAsync(Query request, StreamObserver<Result> observer) { <END> delegate .readRowsCallable(new ResultRowAdapter()) .call(request, new StreamObserverAdapter<>(observer)); }</code><technical_language>Please a todo migrate gax's ResponseObserver here. do a waste of time try get classic implementation respect backpressure</technical_language>

Target:
public void readRowsAsync(Query request, StreamObserver<Result> observer) { delegate.readRowsCallable(RESULT_ADAPTER).call(request, new StreamObserverAdapter<>(observer)); }
Source:
<code>public ServiceTreeNode next() { currentPathSegment = pathIterator.next(); if (isID(currentPathSegment, node)) { node = node.getSubService("{id}"); } else if (node.containsSubService(currentPathSegment)) { node = node.getSubService(currentPathSegment); } else { throw new <START> IllegalArgumentException("segment <END> '" + currentPathSegment + "' of path does not exist"); } return node; }</code><technical_language>Start upper case: Segment ..</technical_language>

Target:
public ServiceTreeNode next() { currentPathSegment = pathIterator.next(); if (isID(currentPathSegment, node)) { node = node.getSubService("{id}"); } else if (node.containsSubService(currentPathSegment)) { node = node.getSubService(currentPathSegment); } else { throw new IllegalArgumentException("Segment '" + currentPathSegment + "' of path does not exist"); } return node; }
Source:
<code><START> private boolean isFunctionNameMatch(RowExpression rowExpression, String expectedName) <END> { if (castToExpression(rowExpression) instanceof FunctionCall) { return ((FunctionCall) castToExpression(rowExpression)).getName().toString().equalsIgnoreCase(expectedName); } return false; }</code><technical_language>static</technical_language>

Target:
private static boolean isFunctionNameMatch(RowExpression rowExpression, String expectedName) { if (castToExpression(rowExpression) instanceof FunctionCall) { return ((FunctionCall) castToExpression(rowExpression)).getName().toString().equalsIgnoreCase(expectedName); } return false; }
Source:
<code>private static Optional<ColumnDomain<HiveColumnHandle>> getPathDomain(TupleDomain<HiveColumnHandle> effectivePredicate) { if (!effectivePredicate.getColumnDomains().isPresent()) { return Optional.empty(); } return effectivePredicate.getColumnDomains().get().stream() <START> .filter(columnDomain -> columnDomain.getColumn().getName().equalsIgnoreCase(PATH_COLUMN_NAME)) <END> .findFirst(); }</code><technical_language>I want this IgnoreCase</technical_language>

Target:
private static Optional<Domain> getPathDomain(TupleDomain<HiveColumnHandle> effectivePredicate) { if (!effectivePredicate.getDomains().isPresent()) { return Optional.empty(); } return effectivePredicate.getDomains().get().entrySet().stream() .filter(entry -> isPathColumnHandle(entry.getKey())) .findFirst() .map(Map.Entry::getValue); }
Source:
<code>private BinaryContent createMetacard( InputStream stream, String contentType, String transformerParam) throws CatalogServiceException { String transformer = DEFAULT_METACARD_TRANSFORMER; if (transformerParam != null) { transformer = transformerParam; } MimeType mimeType = null; if (contentType != null) { try { mimeType = new MimeType(contentType); } catch (MimeTypeParseException e) { LOGGER.debug("Unable to create MimeType from raw data {}", contentType); } } else { LOGGER.debug("No content type specified in request"); } try { Metacard metacard = generateMetacard(mimeType, null, stream, null); String metacardId = metacard.getId(); LOGGER.debug("Metacard created", metacardId); LOGGER.debug( "Transforming metacard to to be able to return it to client", metacardId, transformer); final BinaryContent content = catalogFramework.transform(metacard, transformer, null); LOGGER.debug( "Metacard to transform complete for {}, preparing response.", transformer, metacardId); LOGGER.trace("EXITING: createMetacard"); return content; } catch (MetacardCreationException | CatalogTransformerException e) { throw new CatalogServiceException("Unable to create metacard"); } finally { try { if (stream != null) { stream.close(); } } catch (IOException e) { <START> LOGGER.error("Unexpected error closing stream", e); <END> } } }</code><technical_language>a good idea log this a lesser level. I I remember told able close a stream big of a deal. confirm this</technical_language>

Target:
private BinaryContent createMetacard( InputStream stream, String contentType, String transformerParam) throws CatalogServiceException { String transformer = DEFAULT_METACARD_TRANSFORMER; if (transformerParam != null) { transformer = transformerParam; } MimeType mimeType = null; if (contentType != null) { try { mimeType = new MimeType(contentType); } catch (MimeTypeParseException e) { LOGGER.debug("Unable to create MimeType from raw data {}", contentType); } } else { LOGGER.debug("No content type specified in request"); } try { Metacard metacard = generateMetacard(mimeType, null, stream, null); String metacardId = metacard.getId(); LOGGER.debug("Metacard created", metacardId); LOGGER.debug( "Transforming metacard to to be able to return it to client", metacardId, transformer); final BinaryContent content = catalogFramework.transform(metacard, transformer, null); LOGGER.debug( "Metacard to transform complete for {}, preparing response.", transformer, metacardId); LOGGER.trace("EXITING: createMetacard"); return content; } catch (MetacardCreationException | CatalogTransformerException e) { throw new CatalogServiceException("Unable to create metacard"); } finally { try { if (stream != null) { stream.close(); } } catch (IOException e) { LOGGER.debug("Unexpected error closing stream", e); } } }
Source:
<code>public SaslClient createSaslClient(String[] mechanisms, String authorizationId, String protocol, String serverName, Map<String, ?> props, CallbackHandler cbh) throws SaslException { String selectedMech = selectMechanism(mechanisms); if (selectedMech == null) { return null; } <START> <END> Boolean utf8 = (Boolean) props.get(AbstractMD5DigestMechanism.UTF8_PROPERTY); Charset charset = (utf8 == null || utf8.booleanValue()) ? Charsets.UTF_8 : Charsets.LATIN_1; String supprtedCipherOpts = (String) props.get(AbstractMD5DigestMechanism.SUPPORTED_CIPHERS_PROPERTY); String[] supportedCipherOpts = (supprtedCipherOpts == null ? null : supprtedCipherOpts.split(",")); final MD5DigestSaslClient client = new MD5DigestSaslClient(selectedMech, protocol, serverName, cbh, authorizationId, false, charset, supportedCipherOpts); client.init(); return client; }</code><technical_language>Spacing</technical_language>

Target:
public SaslClient createSaslClient(String[] mechanisms, String authorizationId, String protocol, String serverName, Map<String, ?> props, CallbackHandler cbh) throws SaslException { String selectedMech = selectMechanism(mechanisms); if (selectedMech == null) return null; Boolean utf8 = (Boolean)props.get(AbstractMD5DigestMechanism.UTF8_PROPERTY); Charset charset = (utf8==null || utf8.booleanValue()) ? Charsets.UTF_8 : Charsets.LATIN_1; String supprtedCipherOpts = (String)props.get(AbstractMD5DigestMechanism.SUPPORTED_CIPHERS_PROPERTY); String[] supportedCipherOpts = (supprtedCipherOpts == null ? null : supprtedCipherOpts.split(",")); final MD5DigestSaslClient client = new MD5DigestSaslClient(selectedMech, protocol, serverName, cbh, authorizationId, false, charset, supportedCipherOpts); client.init(); return client; }
Source:
<code><START> public String getStoreKey() { <END> return m_storeKey; }</code><technical_language>this protected, do want allow call this class</technical_language>

Target:
protected String getStoreKey() { return m_storeKey; }
Source:
<code>public SearchRequestBuilder buildScrollSearchRequest() { String indices = index != null && !index.isEmpty() ? index : "_all"; List<String> fields = columns.stream() .map(ElasticsearchColumnHandle::getColumnName) .collect(toList()); SearchRequestBuilder searchRequestBuilder = client.prepareSearch(indices) .setTypes(type) .setSearchType(QUERY_THEN_FETCH) .setScroll(new TimeValue(scrollTimeout.toMillis())) .setFetchSource(fields.toArray(new String[0]), null) .setQuery(buildSearchQuery()) .setPreference("_shards:" + shard) <START> .addSort("_doc", SortOrder.ASC) <END> .setSize(scrollSize); LOG.debug("Elasticsearch Request: %s", searchRequestBuilder); return searchRequestBuilder; }</code><technical_language>static import SortOrder.ASC</technical_language>

Target:
public SearchRequestBuilder buildScrollSearchRequest() { String indices = index != null && !index.isEmpty() ? index : "_all"; List<String> fields = columns.stream() .map(ElasticsearchColumnHandle::getColumnName) .collect(toList()); SearchRequestBuilder searchRequestBuilder = client.prepareSearch(indices) .setTypes(type) .setSearchType(QUERY_THEN_FETCH) .setScroll(new TimeValue(scrollTimeout.toMillis())) .setFetchSource(fields.toArray(new String[0]), null) .setQuery(buildSearchQuery()) .setPreference("_shards:" + shard) .addSort("_doc", ASC) .setSize(scrollSize); LOG.debug("Elasticsearch Request: %s", searchRequestBuilder); return searchRequestBuilder; }
Source:
<code>WebsocketConnectionAttemptState(ModularXmppClientToServerConnectionInternal connectionInternal, XmppWebsocketTransportModule.XmppWebsocketTransport.DiscoveredWebsocketEndpoints discoveredWebsocketEndpoints, EstablishingWebsocketConnectionState establishingWebsocketConnectionState) throws IOException { this.connectionInternal = connectionInternal; this.discoveredEndpoints = discoveredWebsocketEndpoints; List<WebsocketRemoteConnectionEndpoint> endpoints = discoveredWebsocketEndpoints.result.discoveredRemoteConnectionEndpoints; connectionEndpointIterator = endpoints.iterator(); connectionEndpoint = connectionEndpointIterator.next(); connectionExceptions = new ArrayList<>(endpoints.size()); <START> } <END></code><technical_language>group methods throwing disjunct exceptions in try-catch block! multiple try-catch blocks instead</technical_language>

Target:
WebsocketConnectionAttemptState(ModularXmppClientToServerConnectionInternal connectionInternal, XmppWebsocketTransportModule.XmppWebsocketTransport.DiscoveredWebsocketEndpoints discoveredWebsocketEndpoints, EstablishingWebsocketConnectionState establishingWebsocketConnectionState) { assert discoveredWebsocketEndpoints != null; this.connectionInternal = connectionInternal; this.discoveredEndpoints = discoveredWebsocketEndpoints; }
Source:
<code><START> public boolean isLocked() { return isLocked; } <END></code><technical_language>Please follow style guide in CONTRIBUTING.md add this for field access. enable save action automatically do so</technical_language>

Target:
public boolean isLocked() { return this.isLocked; }
Source:
<code>public boolean modifyEvent(String key, Construct value, BindableEvent e) { MCBlockBreakEvent event = (MCBlockBreakEvent)e; if (key.equals("drops")) { event.getBlock().setType(Material.AIR); if (value instanceof CArray) { <START> CArray arr = (CArray)value; <END> for(int i=0; i < arr.size(); i++) { CArray item = (CArray)arr.get(i); if(item.containsKey("type")){ ItemStack stk = new ItemStack(i, i); stk.setTypeId((int)((CInt)item.get("type")).getInt()); int amt; if(item.containsKey("amount")) { amt = (int)((CInt)item.get("amount")).getInt(); } else { amt = 1; } stk.setAmount(amt); if(item.containsKey("durability")) { short data = (short)((CInt)item.get("durability")).getInt(); stk.setDurability(data); } event.getBlock().getWorld().dropItemNaturally(event.getBlock().getLocation(), stk); } } return true; } } return false; }</code><technical_language>for this one, a method in Static converts CArray ItemStack</technical_language>

Target:
public boolean modifyEvent(String key, Construct value, BindableEvent e) { MCBlockBreakEvent event = (MCBlockBreakEvent)e; Block blk = event.getBlock(); if (key.equals("drops")) { blk.setType(Material.AIR); if (value instanceof CArray) { CArray arr = (CArray)value; for(int i=0; i < arr.size(); i++) { CArray item = (CArray)arr.get(i); MCItemStack stk = ObjectGenerator.GetGenerator().item(item, Target.UNKNOWN); blk.getWorld().dropItemNaturally(blk.getLocation(), (ItemStack)stk.getHandle()); } return true; } } return false; }